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