misc_utils.py
Python script, ASCII text executable
1from common import * 2 3__all__ = ["git_command", "only_chars", "get_permission_level", "get_visibility", "get_favourite", "human_size", 4"guess_mime", "convert_to_html", "js_to_bool",] 5 6import subprocess 7import os 8import magic 9from models import * 10 11 12def only_chars(string, chars): 13chars = set(chars) 14all_chars = set(string) 15return all_chars.issubset(chars) 16 17 18def get_permission_level(logged_in, username, repository): 19user = User.query.filter_by(username=logged_in).first() 20repo = Repo.query.filter_by(route=f"/{username}/{repository}").first() 21 22if user and repo: 23permission = RepoAccess.query.filter_by(user=user, repo=repo).first() 24if permission: 25return permission.access_level 26 27return None 28 29 30def get_visibility(username, repository): 31repo = Repo.query.filter_by(route=f"/{username}/{repository}").first() 32 33if repo: 34return repo.visibility 35 36return None 37 38 39def get_favourite(logged_in, username, repository): 40relationship = RepoFavourite.query.filter_by(user_username=logged_in, 41repo_route=f"/{username}/{repository}").first() 42return relationship 43 44 45def human_size(value, decimals=2, scale=1024, 46units=("B", "kiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB", "RiB", "QiB")): 47for unit in units: 48if value < scale: 49break 50value /= scale 51if int(value) == value: 52# do not return decimals if the value is already round 53return int(value), unit 54return round(value * 10 ** decimals) / 10 ** decimals, unit 55 56 57def guess_mime(path): 58if os.path.isdir(path): 59mimetype = "inode/directory" 60elif magic.from_file(path, mime=True): 61mimetype = magic.from_file(path, mime=True) 62else: 63mimetype = "application/octet-stream" 64return mimetype 65 66 67def convert_to_html(path): 68with open(path, "r") as f: 69contents = f.read() 70return contents 71 72 73def js_to_bool(js): 74return js.lower() == "true" if isinstance(js, str) else bool(js) 75