19
17
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23
from xml.etree import ElementTree as ET
25
from elementtree import ElementTree as ET
27
from simpletal.simpleTALUtils import HTMLStructureCleaner
41
35
log = logging.getLogger("loggerhead.controllers")
41
return '%d years' % (int(delta.days // 365.25),)
43
return '%d days' % delta.days
49
seg.append('%d days' % delta.days)
50
hrs = delta.seconds // 3600
51
mins = (delta.seconds % 3600) // 60
56
seg.append('%d hours' % hrs)
60
seg.append('1 minute')
62
seg.append('%d minutes' % mins)
64
seg.append('less than a minute')
69
now = datetime.datetime.now()
70
return timespan(now - timestamp) + ' ago'
44
73
def fix_year(year):
53
# date_day -- just the day
54
# date_time -- full date with time
56
# displaydate -- for use in sentences
57
# approximatedate -- for use in tables
59
# displaydate and approximatedate return an elementtree <span> Element
60
# with the full date in a tooltip.
64
return value.strftime('%Y-%m-%d')
69
return value.strftime('%Y-%m-%d %T')
74
def _displaydate(date):
75
delta = abs(datetime.datetime.now() - date)
76
if delta > datetime.timedelta(1, 0, 0):
77
# far in the past or future, display the date
78
return 'on ' + date_day(date)
79
return _approximatedate(date)
82
def _approximatedate(date):
83
delta = datetime.datetime.now() - date
84
if abs(delta) > datetime.timedelta(1, 0, 0):
85
# far in the past or future, display the date
87
future = delta < datetime.timedelta(0, 0, 0)
90
hours = delta.seconds / 3600
91
minutes = (delta.seconds - (3600*hours)) / 60
92
seconds = delta.seconds % 60
110
result += '%s %s' % (amount, unit)
116
def _wrap_with_date_time_title(date, formatted_date):
117
elem = ET.Element("span")
118
elem.text = formatted_date
119
elem.set("title", date_time(date))
123
def approximatedate(date):
124
#FIXME: Returns an object instead of a string
125
return _wrap_with_date_time_title(date, _approximatedate(date))
128
def displaydate(date):
129
return _wrap_with_date_time_title(date, _displaydate(date))
132
81
class Container (object):
134
83
Convert a dict into an object with attributes.
137
85
def __init__(self, _dict=None, **kw):
138
86
if _dict is not None:
139
87
for key, value in _dict.iteritems():
140
88
setattr(self, key, value)
141
89
for key, value in kw.iteritems():
142
90
setattr(self, key, value)
144
92
def __repr__(self):
146
94
for key, value in self.__dict__.iteritems():
147
if key.startswith('_') or (getattr(self.__dict__[key],
148
'__call__', None) is not None):
95
if key.startswith('_') or (getattr(self.__dict__[key], '__call__', None) is not None):
150
97
out += '%r => %r, ' % (key, value)
102
def clean_revid(revid):
103
if revid == 'missing':
105
return sha.new(revid).hexdigest()
109
return ''.join([ '&#%d;' % ord(c) for c in text ])
155
112
def trunc(text, limit=10):
156
113
if len(text) <= limit:
158
115
return text[:limit] + '...'
119
if isinstance(s, unicode):
120
return s.encode('utf-8')
161
124
STANDARD_PATTERN = re.compile(r'^(.*?)\s*<(.*?)>\s*$')
162
125
EMAIL_PATTERN = re.compile(r'[-\w\d\+_!%\.]+@[-\w\d\+_!%\.]+')
165
127
def hide_email(email):
167
129
try to obsure any email address in a bazaar committer's name.
181
143
return '%s at %s' % (username, domains[-2])
182
144
return '%s at %s' % (username, domains[0])
184
def hide_emails(emails):
186
try to obscure any email address in a list of bazaar committers' names.
190
result.append(hide_email(email))
147
def triple_factors(min_value=1):
153
yield n * factors[index]
155
if index >= len(factors):
160
def scan_range(pos, max, pagesize=1):
162
given a position in a maximum range, return a list of negative and positive
163
jump factors for an hgweb-style triple-factor geometric scan.
165
for example, with pos=20 and max=500, the range would be:
166
[ -10, -3, -1, 1, 3, 10, 30, 100, 300 ]
168
i admit this is a very strange way of jumping through revisions. i didn't
172
for n in triple_factors(pagesize + 1):
193
181
# only do this if unicode turns out to be a problem
194
182
#_BADCHARS_RE = re.compile(ur'[\u007f-\uffff]')
196
184
# FIXME: get rid of this method; use fixed_width() and avoid XML().
199
185
def html_clean(s):
201
187
clean up a string for html display. expand any tabs, encode any html
337
304
navigation.position = 0
338
305
navigation.count = len(navigation.revid_list)
339
306
navigation.page_position = navigation.position // navigation.pagesize + 1
340
navigation.page_count = (len(navigation.revid_list) + (navigation.pagesize\
341
- 1)) // navigation.pagesize
307
navigation.page_count = (len(navigation.revid_list) + (navigation.pagesize - 1)) // navigation.pagesize
343
309
def get_offset(offset):
344
if (navigation.position + offset < 0) or (
345
navigation.position + offset > navigation.count - 1):
310
if (navigation.position + offset < 0) or (navigation.position + offset > navigation.count - 1):
347
312
return navigation.revid_list[navigation.position + offset]
349
navigation.last_in_page_revid = get_offset(navigation.pagesize - 1)
350
314
navigation.prev_page_revid = get_offset(-1 * navigation.pagesize)
351
315
navigation.next_page_revid = get_offset(1 * navigation.pagesize)
352
prev_page_revno = navigation.history.get_revno(
353
navigation.prev_page_revid)
354
next_page_revno = navigation.history.get_revno(
355
navigation.next_page_revid)
356
start_revno = navigation.history.get_revno(navigation.start_revid)
358
params = {'filter_file_id': navigation.filter_file_id}
317
params = { 'file_id': navigation.file_id }
359
318
if getattr(navigation, 'query', None) is not None:
360
319
params['q'] = navigation.query
362
if getattr(navigation, 'start_revid', None) is not None:
363
params['start_revid'] = start_revno
321
params['start_revid'] = navigation.start_revid
365
323
if navigation.prev_page_revid:
366
navigation.prev_page_url = navigation.branch.context_url(
367
[navigation.scan_url, prev_page_revno], **params)
324
navigation.prev_page_url = navigation.branch.url([ navigation.scan_url, navigation.prev_page_revid ], **get_context(**params))
368
325
if navigation.next_page_revid:
369
navigation.next_page_url = navigation.branch.context_url(
370
[navigation.scan_url, next_page_revno], **params)
373
def directory_breadcrumbs(path, is_root, view):
375
Generate breadcrumb information from the directory path given
377
The path given should be a path up to any branch that is currently being
381
path -- The path to convert into breadcrumbs
382
is_root -- Whether or not loggerhead is serving a branch at its root
383
view -- The type of view we are showing (files, changes etc)
385
# Is our root directory itself a branch?
387
if view == 'directory':
395
# Create breadcrumb trail for the path leading up to the branch
397
'dir_name': "(root)",
402
dir_parts = path.strip('/').split('/')
403
for index, dir_name in enumerate(dir_parts):
405
'dir_name': dir_name,
406
'path': '/'.join(dir_parts[:index + 1]),
409
# If we are not in the directory view, the last crumb is a branch,
410
# so we need to specify a view
411
if view != 'directory':
412
breadcrumbs[-1]['suffix'] = '/' + view
416
def branch_breadcrumbs(path, inv, view):
418
Generate breadcrumb information from the branch path given
420
The path given should be a path that exists within a branch
423
path -- The path to convert into breadcrumbs
424
inv -- Inventory to get file information from
425
view -- The type of view we are showing (files, changes etc)
427
dir_parts = path.strip('/').split('/')
428
inner_breadcrumbs = []
429
for index, dir_name in enumerate(dir_parts):
430
inner_breadcrumbs.append({
431
'dir_name': dir_name,
432
'file_id': inv.path2id('/'.join(dir_parts[:index + 1])),
433
'suffix': '/' + view,
435
return inner_breadcrumbs
326
navigation.next_page_url = navigation.branch.url([ navigation.scan_url, navigation.next_page_revid ], **get_context(**params))
329
def log_exception(log):
330
for line in ''.join(traceback.format_exception(*sys.exc_info())).split('\n'):
438
334
def decorator(unbound):
440
335
def new_decorator(f):
442
337
g.__name__ = f.__name__
449
344
return new_decorator
347
# common threading-lock decorator
348
def with_lock(lockname, debug_name=None):
349
if debug_name is None:
350
debug_name = lockname
352
def _decorator(unbound):
353
def locked(self, *args, **kw):
354
getattr(self, lockname).acquire()
356
return unbound(self, *args, **kw)
358
getattr(self, lockname).release()
364
def strip_whitespace(f):
368
out = re.sub(r'\n\s+', '\n', out)
369
out = re.sub(r'[ \t]+', ' ', out)
370
out = re.sub(r'\s+\n', '\n', out)
372
log.debug('Saved %sB (%d%%) by stripping whitespace.',
373
human_size(orig_len - new_len),
374
round(100.0 - float(new_len) * 100.0 / float(orig_len)))
456
381
def _f(*a, **kw):
457
382
from loggerhead.lsprof import profile
460
385
ret, stats = profile(f, *a, **kw)
461
log.debug('Finished profiled %s in %d msec.' % (f.__name__,
462
int((time.time() - z) * 1000)))
386
log.debug('Finished profiled %s in %d msec.' % (f.__name__, int((time.time() - z) * 1000)))
465
389
now = time.time()
466
390
msec = int(now * 1000) % 1000
467
timestr = time.strftime('%Y%m%d%H%M%S',
468
time.localtime(now)) + ('%03d' % msec)
391
timestr = time.strftime('%Y%m%d%H%M%S', time.localtime(now)) + ('%03d' % msec)
469
392
filename = f.__name__ + '-' + timestr + '.lsprof'
470
393
cPickle.dump(stats, open(filename, 'w'), 2)
527
444
overrides = dict((k, v) for (k, v) in overrides.iteritems() if k in _valid)
528
445
map.update(overrides)
532
class Reloader(object):
534
This class wraps all paste.reloader logic. All methods are @classmethod.
537
_reloader_environ_key = 'PYTHON_RELOADER_SHOULD_RUN'
540
def _turn_sigterm_into_systemexit(self):
542
Attempts to turn a SIGTERM exception into a SystemExit exception.
549
def handle_term(signo, frame):
551
signal.signal(signal.SIGTERM, handle_term)
554
def is_installed(self):
555
return os.environ.get(self._reloader_environ_key)
559
from paste import reloader
560
reloader.install(int(1))
563
def restart_with_reloader(self):
564
"""Based on restart_with_monitor from paste.script.serve."""
565
print 'Starting subprocess with file monitor'
567
args = [sys.executable] + sys.argv
568
new_environ = os.environ.copy()
569
new_environ[self._reloader_environ_key] = 'true'
573
self._turn_sigterm_into_systemexit()
574
proc = subprocess.Popen(args, env=new_environ)
575
exit_code = proc.wait()
577
except KeyboardInterrupt:
578
print '^C caught in monitor process'
582
and hasattr(os, 'kill')):
585
os.kill(proc.pid, signal.SIGTERM)
586
except (OSError, IOError):
589
# Reloader always exits with code 3; but if we are
590
# a monitor, any exit code will restart
593
print '-'*20, 'Restarting', '-'*20