]> git.ipfire.org Git - people/jschlag/pbs.git/blob - backend/misc.py
Drop dependency on textile
[people/jschlag/pbs.git] / backend / misc.py
1 #!/usr/bin/python
2
3 from __future__ import division
4
5 import hashlib
6 import os
7 import re
8 import tarfile
9
10 from tornado.escape import xhtml_escape
11
12 from constants import *
13
14 def format_size(s):
15 units = ("B", "k", "M", "G", "T")
16
17 i = 0
18 while s >= 1024 and i < len(units):
19 s /= 1024
20 i += 1
21
22 return "%d%s" % (round(s), units[i])
23
24 def friendly_time(t):
25 if not t:
26 return "--:--"
27
28 t = int(t)
29 ret = []
30
31 if t >= 604800:
32 ret.append("%s w" % (t // 604800))
33 t %= 604800
34
35 if t >= 86400:
36 ret.append("%s d" % (t // 38400))
37 t %= 86400
38
39 if t >= 3600:
40 ret.append("%s h" % (t // 3600))
41 t %= 3600
42
43 if t >= 60:
44 ret.append("%s m" % (t // 60))
45 t %= 60
46
47 if t:
48 ret.append("%s s" % t)
49
50 return " ".join(ret)
51
52 def format_email(email):
53 m = re.match(r"(.*) <(.*)>", email)
54 if m:
55 fmt = {
56 "name" : xhtml_escape(m.group(1)),
57 "mail" : xhtml_escape(m.group(2)),
58 }
59 else:
60 fmt = {
61 "name" : xhtml_escape(email),
62 "mail" : xhtml_escape(email),
63 }
64
65 return """<a class="email" href="mailto:%(mail)s">%(name)s</a>""" % fmt
66
67 def format_filemode(filetype, filemode):
68 if filetype == 2:
69 prefix = "l"
70 elif filetype == 5:
71 prefix = "d"
72 else:
73 prefix = "-"
74
75 return prefix + tarfile.filemode(filemode)[1:]
76
77 def calc_hash(filename, algo="sha512"):
78 assert algo in hashlib.algorithms
79 assert os.path.exists(filename)
80
81 f = open(filename, "rb")
82 h = hashlib.new(algo)
83
84 while True:
85 buf = f.read(BUFFER_SIZE)
86 if not buf:
87 break
88
89 h.update(buf)
90
91 f.close()
92
93 return h.hexdigest()
94
95 def calc_hash1(filename):
96 # XXX COMPAT FUNCTION
97 # to be removed
98 return calc_hash(filename, "sha1")
99
100 def guess_filetype(filename):
101 # XXX very cheap check. Need to do better here.
102 if tarfile.is_tarfile(filename):
103 return "pkg"
104
105 elif filename.endswith(".log"):
106 return "log"
107
108 return "unknown"