By using this site, you agree to have cookies stored on your device, strictly for functional purposes, such as storing your session and preferences.

Dismiss

 misc_utils.py

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