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