]> git.ipfire.org Git - ipfire.org.git/blob - src/backend/util.py
wiki: Implement search
[ipfire.org.git] / src / backend / util.py
1 #!/usr/bin/python3
2
3 import random
4 import re
5 import string
6
7 def parse_search_query(query):
8 q = []
9 for word in query.split():
10 # Is this lexeme negated?
11 negated = word.startswith("!")
12
13 # Remove any special characters
14 word = re.sub(r"\W+", "", word, flags=re.UNICODE)
15 if not word:
16 continue
17
18 # Restore negation
19 if negated:
20 word = "!%s" % word
21
22 q.append(word)
23
24 return " & ".join(q)
25
26 def format_size(s, max_unit=None):
27 units = ("B", "kB", "MB", "GB", "TB")
28
29 i = 0
30 while s >= 1024 and i < len(units) - 1:
31 s /= 1024
32 i += 1
33
34 if max_unit and units[i] == max_unit:
35 break
36
37 return "%.0f%s" % (s, units[i])
38
39 def format_time(s, shorter=True):
40 #_ = handler.locale.translate
41 _ = lambda x: x
42
43 hrs, s = divmod(s, 3600)
44 min, s = divmod(s, 60)
45
46 if s >= 30:
47 min += 1
48
49 if shorter and not hrs:
50 return _("%(min)d min") % { "min" : min }
51
52 return _("%(hrs)d:%(min)02d hrs") % {"hrs" : hrs, "min" : min}
53
54 def random_string(length=8):
55 input_chars = string.ascii_letters + string.digits
56
57 r = (random.choice(input_chars) for i in range(length))
58
59 return "".join(r)