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): 34for i in string: 35if i not in chars: 36return False 37return True 38 39 40def get_permission_level(logged_in, username, repository): 41user = User.query.filter_by(username=logged_in).first() 42repo = Repo.query.filter_by(route=f"/{username}/{repository}").first() 43 44if user and repo: 45permission = RepoAccess.query.filter_by(user=user, repo=repo).first() 46if permission: 47return permission.access_level 48 49return None 50 51 52def get_visibility(username, repository): 53repo = Repo.query.filter_by(route=f"/{username}/{repository}").first() 54 55if repo: 56return repo.visibility 57 58return None 59 60 61def get_favourite(logged_in, username, repository): 62print(logged_in, username, repository) 63relationship = RepoFavourite.query.filter_by(user_username=logged_in, 64repo_route=f"/{username}/{repository}").first() 65return relationship 66 67 68def human_size(value, decimals=2, scale=1024, 69units=("B", "kiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB", "RiB", "QiB")): 70for unit in units: 71if value < scale: 72break 73value /= scale 74if int(value) == value: 75# do not return decimals if the value is already round 76return int(value), unit 77return round(value * 10 ** decimals) / 10 ** decimals, unit 78 79 80def guess_mime(path): 81if os.path.isdir(path): 82mimetype = "inode/directory" 83elif magic.from_file(path, mime=True): 84mimetype = magic.from_file(path, mime=True) 85else: 86mimetype = "application/octet-stream" 87return mimetype 88 89 90def convert_to_html(path): 91with open(path, "r") as f: 92contents = f.read() 93return contents 94