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.02 kiB
Python script, ASCII text executable
        
            
1
from common import *
2
3
__all__ = ["git_command", "only_chars", "get_permission_level", "get_visibility", "get_favourite", "human_size",
4
"guess_mime", "convert_to_html", "js_to_bool",]
5
6
import subprocess
7
import os
8
import magic
9
from models import *
10
11
12
def only_chars(string, chars):
13
chars = set(chars)
14
all_chars = set(string)
15
return all_chars.issubset(chars)
16
17
18
def get_permission_level(logged_in, username, repository):
19
user = User.query.filter_by(username=logged_in).first()
20
repo = Repo.query.filter_by(route=f"/{username}/{repository}").first()
21
22
if user and repo:
23
permission = RepoAccess.query.filter_by(user=user, repo=repo).first()
24
if permission:
25
return permission.access_level
26
27
return None
28
29
30
def get_visibility(username, repository):
31
repo = Repo.query.filter_by(route=f"/{username}/{repository}").first()
32
33
if repo:
34
return repo.visibility
35
36
return None
37
38
39
def get_favourite(logged_in, username, repository):
40
relationship = RepoFavourite.query.filter_by(user_username=logged_in,
41
repo_route=f"/{username}/{repository}").first()
42
return relationship
43
44
45
def human_size(value, decimals=2, scale=1024,
46
units=("B", "kiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB", "RiB", "QiB")):
47
for unit in units:
48
if value < scale:
49
break
50
value /= scale
51
if int(value) == value:
52
# do not return decimals if the value is already round
53
return int(value), unit
54
return round(value * 10 ** decimals) / 10 ** decimals, unit
55
56
57
def guess_mime(path):
58
if os.path.isdir(path):
59
mimetype = "inode/directory"
60
elif magic.from_file(path, mime=True):
61
mimetype = magic.from_file(path, mime=True)
62
else:
63
mimetype = "application/octet-stream"
64
return mimetype
65
66
67
def convert_to_html(path):
68
with open(path, "r") as f:
69
contents = f.read()
70
return contents
71
72
73
def js_to_bool(js):
74
return js.lower() == "true" if isinstance(js, str) else bool(js)
75