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): 40print(logged_in, username, repository) 41relationship = RepoFavourite.query.filter_by(user_username=logged_in, 42repo_route=f"/{username}/{repository}").first() 43return relationship 44 45 46def human_size(value, decimals=2, scale=1024, 47units=("B", "kiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB", "RiB", "QiB")): 48for unit in units: 49if value < scale: 50break 51value /= scale 52if int(value) == value: 53# do not return decimals if the value is already round 54return int(value), unit 55return round(value * 10 ** decimals) / 10 ** decimals, unit 56 57 58def guess_mime(path): 59if os.path.isdir(path): 60mimetype = "inode/directory" 61elif magic.from_file(path, mime=True): 62mimetype = magic.from_file(path, mime=True) 63else: 64mimetype = "application/octet-stream" 65return mimetype 66 67 68def convert_to_html(path): 69with open(path, "r") as f: 70contents = f.read() 71return contents 72 73 74def js_to_bool(js): 75return js.lower() == "true" if isinstance(js, str) else bool(js) 76