~bzr/bzr-webserve/webserve-dev

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
# templater.py - templater class
# this code is derived by the hgweb server of the Matt Mackall's mercurial
# project
#
# Copyright 2006 Goffredo Baroncelli <kreijack@inwind.it>
#
# This file is part of bazaar-webserve.
#
# bazaar-webserve is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# bazaar-webserve is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with bazaar-webserve; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

import time
import os
import re
import urllib
import cgi

def get_time():
    if "WEBSERVE_DEBUG_TIME" in os.environ:
        return float(os.environ["WEBSERVE_DEBUG_TIME"])
    else:
        return time.time()


def enumerate1(l):
    i = 1
    for e in l:
        yield (i, e)
        i += 1


def age(t):
    if t == 0:
        return "Unavailable"

    def plural(t, c):
        if c == 1:
            return t
        return t + "s"

    def fmt(t, c):
        return "%d %s" % (c, plural(t, c))

    now = get_time()
    delta = max(1, int(now - float(t)))

    scales = [["second", 1],
              ["minute", 60],
              ["hour", 3600],
              ["day", 3600 * 24],
              ["week", 3600 * 24 * 7],
              ["month", 3600 * 24 * 30],
              ["year", 3600 * 24 * 365]]

    scales.reverse()

    for t, s in scales:
        n = delta / s
        if n >= 2 or s == 1:
            return fmt(t, n)+" ago"


def nl2br(text):
    return text.replace('\n', '<br/>\n')


def obfuscate(text):
    return ''.join(['&#%d;' % ord(c) for c in text])


def up(p):
    if p[0] != "/":
        p = "/" + p
    if p[-1] == "/":
        p = p[:-1]
    up = os.path.dirname(p)
    if up == "/":
        return "/"
    return up + "/"


def rfc822date(x):
    return time.strftime("%a, %d %b %Y %H:%M:%S +0000",
                            time.gmtime(float(x)))


def breakentities(x):
    return x + "<br>\n"


def entities2nl(x):
    return x + "\n"

def escapehtml(s):
    s = cgi.escape(s)
    s = s.replace("#", "&#35;")
    s = s.replace("@", "&#64;")

    return s


def myurlquote(s):
    def _myurlquote(c):
        if c in ";?:@&=+$,":
            return urllib.quote(c)
        else:
            return c

    return "".join(map(_myurlquote, s))


common_filters = {
    "escape": escapehtml,
    "age": age,
    "date": (lambda x: time.asctime(time.gmtime(float(x)))),
    "addbreaks": nl2br,
    "obfuscate": obfuscate,
    "breakentities": breakentities,
    "addnl" : entities2nl,
    "short": (lambda x: x[:12]),
    "firstline": (lambda x: x.splitlines(1)[0]),
    "permissions": (lambda x: x and "rwxr-xr-x" or "rw-r--r--"),
    "rfc822date": rfc822date,
    "urlquote" :  myurlquote,
    #"urlquote" :  (lambda x: urllib.quote(x)),
}


def write2(stream, *things):
    for thing in things:
        if hasattr(thing, "__iter__"):
            for part in thing:
                write2(stream, part)
        else:
            if isinstance(thing, int):
                thing = str(thing)
            #elif isinstance(thing, str):
                #thing = thing.decode(encoding, 'replace')

            stream.write(thing.encode('utf-8', 'replace'))

def call_and_iter(s):
    while True:
        if callable(s):
            s = s ( )
        elif hasattr(s,"__iter__"):
            s = "".join(call_and_iter(i) for i in s)
        elif not isinstance(s, basestring):
            s = str(s)
        else:
            return s

def template(tmpl, filters={}, __internal_map={}, **map):
    while callable(tmpl):
        tmpl = tmpl()

    if hasattr(tmpl, "__iter__"):
        return "".join(template(i, filters, **map) for i in tmpl)

    tmpl=str(tmpl)

    out = ""
    while tmpl:
        m = re.search(r"#([a-zA-Z0-9]+)((?:\|[a-zA-Z0-9]+)*)(?:\|((?:\|[a-zA-Z0-9]+)*))?#", tmpl)

        if not m:
            out = out + tmpl
            break

        out = out + tmpl[:m.start(0)]

        key = m.group(1)

        if key in __internal_map:
            internal = True
            v = __internal_map.get(key)
        else:
            v = map.get(m.group(1), "")
            internal = False

        fl = m.group(2)
        fl_split = fl and fl.split("|")[1:] or []

        fl2 = m.group(3)
        fl2_split = fl2 and fl2.split("|")[1:] or []

        #import sys
        #sys.stderr.write("%s - %d %d\n"%(tmpl, m.start(), m.end()))
        while callable(v):
            v = v()

        if not hasattr(v, "__iter__"):
            v = [v]

        t = ""
        for i in v:
            if internal:
                i = template(i, filters, **map)
            else:
                i = call_and_iter(i)
            for f in fl_split:
                i = filters[f](i)
            t = t + i

        for f in fl2_split:
            t = filters[f](t)

        out = out + t

        tmpl = tmpl[m.end():]

    return out


class templater:

    def readfile(self, path):
        res = list()
        for l in file(path):
            # skip the empty line ad the ones wich start with "#"
            while len(l) > 0 and l[-1] in "\n\r":
                l = l[:-1]
            if not len(l):
                continue

            # if a line starts with a blank, concatenate
            # with the previous one
            if l[0] == ' ' or l[0] == '\t':
                if len(res):
                    res[-1] = res[-1] + l[1:]
            else:
                ls = l.strip()
                if ls == "":
                    continue
                if len(ls) > 0 and ls[0] == '#':
                    continue
                res.append(l)

        return res

    def __init__(self, mapfile=None, filters = {}, defaults = {}, maptext=None):
        self.cache = {}
        self.map = {}
        self.filters = filters
        self.defaults = defaults
        self.base = ""

        if mapfile:
            self.base = os.path.dirname(mapfile)
            for l in self.readfile(mapfile):
                while len(l) > 0 and l[-1] in "\n\r":
                    l = l[:-1]
                ls = l.strip()
                if ls == "":
                    continue
                if len(ls) > 0 and ls[0] == '#':
                    continue

                m = re.match(r'(\S+)\s*=\s*"(.*)"$', l)
                if m:
                    self.cache[m.group(1)] = m.group(2)
                else:
                    m = re.match(r'(\S+)\s*=\s*(\S+)', l)
                    if m:
                        self.map[m.group(1)] = os.path.join(
                                                    self.base, m.group(2))
                    else:
                        raise "unknown map entry '%s'" % l

        if maptext:
            self.cache.update(maptext)

    def add_filters(self, name, func):
        self.filters[name]=func

    def __call__(self, t, **map):
        try:
            tmpl = self.cache[t]
        except KeyError:
            tmpl = self.cache[t] = file(self.map[t]).read()

        return template(tmpl, self.filters, __internal_map=self.defaults, **map)