misc_utils.py
Python script, ASCII text executable
1import subprocess 2import os 3import magic 4from models import * 5 6 7def git_command(repo, data, *args, return_err=False, return_exit=False): 8if not os.path.isdir(repo): 9raise FileNotFoundError(f"Repo {repo} not found") 10env = os.environ.copy() 11 12command = ["git", *args] 13 14proc = subprocess.Popen(" ".join(command), cwd=repo, env=env, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, 15stdin=subprocess.PIPE) 16 17if data: 18proc.stdin.write(data) 19 20out, err = proc.communicate() 21exit_code = proc.returncode 22 23result = (out,) 24 25if return_err: 26result = result + (err,) 27if return_exit: 28result = result + (exit_code,) 29 30return result[0] if len(result) == 1 else result 31 32 33def only_chars(string, chars): 34chars = set(chars) 35all_chars = set(string) 36return all_chars.issubset(chars) 37 38 39def get_permission_level(logged_in, username, repository): 40user = User.query.filter_by(username=logged_in).first() 41repo = Repo.query.filter_by(route=f"/{username}/{repository}").first() 42 43if user and repo: 44permission = RepoAccess.query.filter_by(user=user, repo=repo).first() 45if permission: 46return permission.access_level 47 48return None 49 50 51def get_visibility(username, repository): 52repo = Repo.query.filter_by(route=f"/{username}/{repository}").first() 53 54if repo: 55return repo.visibility 56 57return None 58 59 60def get_favourite(logged_in, username, repository): 61print(logged_in, username, repository) 62relationship = RepoFavourite.query.filter_by(user_username=logged_in, 63repo_route=f"/{username}/{repository}").first() 64return relationship 65 66 67def human_size(value, decimals=2, scale=1024, 68units=("B", "kiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB", "RiB", "QiB")): 69for unit in units: 70if value < scale: 71break 72value /= scale 73if int(value) == value: 74# do not return decimals if the value is already round 75return int(value), unit 76return round(value * 10 ** decimals) / 10 ** decimals, unit 77 78 79def guess_mime(path): 80if os.path.isdir(path): 81mimetype = "inode/directory" 82elif magic.from_file(path, mime=True): 83mimetype = magic.from_file(path, mime=True) 84else: 85mimetype = "application/octet-stream" 86return mimetype 87 88 89def convert_to_html(path): 90with open(path, "r") as f: 91contents = f.read() 92return contents 93