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