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
39
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'
41
73
def fix_year(year):
50
# date_day -- just the day
51
# date_time -- full date with time
53
# displaydate -- for use in sentences
54
# approximatedate -- for use in tables
56
# displaydate and approximatedate return an elementtree <span> Element
57
# with the full date in a tooltip.
60
return value.strftime('%Y-%m-%d')
65
return value.strftime('%Y-%m-%d %T')
70
def _displaydate(date):
71
delta = abs(datetime.datetime.now() - date)
72
if delta > datetime.timedelta(1, 0, 0):
73
# far in the past or future, display the date
74
return 'on ' + date_day(date)
75
return _approximatedate(date)
78
def _approximatedate(date):
81
_g_format = '%Y-%m-%d @ %H:%M'
83
def format_date(date):
84
if _g_format == 'fancy':
85
return fancy_format_date(date)
86
return date.strftime(_g_format)
88
def fancy_format_date(date):
79
89
delta = datetime.datetime.now() - date
80
if abs(delta) > datetime.timedelta(1, 0, 0):
81
# far in the past or future, display the date
83
future = delta < datetime.timedelta(0, 0, 0)
86
hours = delta.seconds / 3600
87
minutes = (delta.seconds - (3600*hours)) / 60
88
seconds = delta.seconds % 60
91
return date.strftime('%d %b %Y')
106
result += '%s %s' % (amount, unit)
112
def _wrap_with_date_time_title(date, formatted_date):
113
elem = ET.Element("span")
114
elem.text = formatted_date
115
elem.set("title", date_time(date))
119
def approximatedate(date):
120
#FIXME: Returns an object instead of a string
121
return _wrap_with_date_time_title(date, _approximatedate(date))
124
def displaydate(date):
125
return _wrap_with_date_time_title(date, _displaydate(date))
93
return date.strftime('%d %b %H:%M')
95
def set_date_format(format):
128
100
class Container (object):
174
162
return '%s at %s' % (username, domains[-2])
175
163
return '%s at %s' % (username, domains[0])
166
def triple_factors(min_value=1):
172
yield n * factors[index]
174
if index >= len(factors):
179
def scan_range(pos, max, pagesize=1):
181
given a position in a maximum range, return a list of negative and positive
182
jump factors for an hgweb-style triple-factor geometric scan.
184
for example, with pos=20 and max=500, the range would be:
185
[ -10, -3, -1, 1, 3, 10, 30, 100, 300 ]
187
i admit this is a very strange way of jumping through revisions. i didn't
191
for n in triple_factors(pagesize + 1):
178
200
# only do this if unicode turns out to be a problem
179
201
#_BADCHARS_RE = re.compile(ur'[\u007f-\uffff]')
314
324
navigation.count = len(navigation.revid_list)
315
325
navigation.page_position = navigation.position // navigation.pagesize + 1
316
326
navigation.page_count = (len(navigation.revid_list) + (navigation.pagesize - 1)) // navigation.pagesize
318
328
def get_offset(offset):
319
329
if (navigation.position + offset < 0) or (navigation.position + offset > navigation.count - 1):
321
331
return navigation.revid_list[navigation.position + offset]
323
navigation.last_in_page_revid = get_offset(navigation.pagesize - 1)
324
333
navigation.prev_page_revid = get_offset(-1 * navigation.pagesize)
325
334
navigation.next_page_revid = get_offset(1 * navigation.pagesize)
326
prev_page_revno = navigation.history.get_revno(
327
navigation.prev_page_revid)
328
next_page_revno = navigation.history.get_revno(
329
navigation.next_page_revid)
330
start_revno = navigation.history.get_revno(navigation.start_revid)
332
params = { 'filter_file_id': navigation.filter_file_id }
336
params = { 'file_id': navigation.file_id }
333
337
if getattr(navigation, 'query', None) is not None:
334
338
params['q'] = navigation.query
336
if getattr(navigation, 'start_revid', None) is not None:
337
params['start_revid'] = start_revno
340
params['start_revid'] = navigation.start_revid
339
342
if navigation.prev_page_revid:
340
navigation.prev_page_url = navigation.branch.context_url(
341
[navigation.scan_url, prev_page_revno], **params)
343
navigation.prev_page_url = navigation.branch.url([ navigation.scan_url, navigation.prev_page_revid ], **get_context(**params))
342
344
if navigation.next_page_revid:
343
navigation.next_page_url = navigation.branch.context_url(
344
[navigation.scan_url, next_page_revno], **params)
347
def directory_breadcrumbs(path, is_root, view):
349
Generate breadcrumb information from the directory path given
351
The path given should be a path up to any branch that is currently being
355
path -- The path to convert into breadcrumbs
356
is_root -- Whether or not loggerhead is serving a branch at its root
357
view -- The type of view we are showing (files, changes etc)
359
# Is our root directory itself a branch?
361
if view == 'directory':
369
# Create breadcrumb trail for the path leading up to the branch
371
'dir_name': "(root)",
376
dir_parts = path.strip('/').split('/')
377
for index, dir_name in enumerate(dir_parts):
379
'dir_name': dir_name,
380
'path': '/'.join(dir_parts[:index + 1]),
383
# If we are not in the directory view, the last crumb is a branch,
384
# so we need to specify a view
385
if view != 'directory':
386
breadcrumbs[-1]['suffix'] = '/' + view
390
def branch_breadcrumbs(path, inv, view):
392
Generate breadcrumb information from the branch path given
394
The path given should be a path that exists within a branch
397
path -- The path to convert into breadcrumbs
398
inv -- Inventory to get file information from
399
view -- The type of view we are showing (files, changes etc)
401
dir_parts = path.strip('/').split('/')
402
inner_breadcrumbs = []
403
for index, dir_name in enumerate(dir_parts):
404
inner_breadcrumbs.append({
405
'dir_name': dir_name,
406
'file_id': inv.path2id('/'.join(dir_parts[:index + 1])),
407
'suffix': '/' + view ,
409
return inner_breadcrumbs
345
navigation.next_page_url = navigation.branch.url([ navigation.scan_url, navigation.next_page_revid ], **get_context(**params))
348
def log_exception(log):
349
for line in ''.join(traceback.format_exception(*sys.exc_info())).split('\n'):
412
353
def decorator(unbound):
383
def strip_whitespace(f):
387
out = re.sub(r'\n\s+', '\n', out)
388
out = re.sub(r'[ \t]+', ' ', out)
389
out = re.sub(r'\s+\n', '\n', out)
391
log.debug('Saved %sB (%d%%) by stripping whitespace.',
392
human_size(orig_len - new_len),
393
round(100.0 - float(new_len) * 100.0 / float(orig_len)))
443
400
def _f(*a, **kw):
444
401
from loggerhead.lsprof import profile
464
421
# current location along the navigation path (while browsing)
465
422
# - starting revid (start_revid)
466
423
# the current beginning of navigation (navigation continues back to
467
# the original revision) -- this defines an 'alternate mainline'
468
# when the user navigates into a branch.
424
# the original revision) -- this may not be along the primary revision
425
# path since the user may have navigated into a branch
470
# the file being looked at
472
427
# if navigating the revisions that touched a file
474
429
# if navigating the revisions that matched a search query
512
463
overrides = dict((k, v) for (k, v) in overrides.iteritems() if k in _valid)
513
464
map.update(overrides)
517
class Reloader(object):
519
This class wraps all paste.reloader logic. All methods are @classmethod.
522
_reloader_environ_key = 'PYTHON_RELOADER_SHOULD_RUN'
525
def _turn_sigterm_into_systemexit(self):
527
Attempts to turn a SIGTERM exception into a SystemExit exception.
533
def handle_term(signo, frame):
535
signal.signal(signal.SIGTERM, handle_term)
538
def is_installed(self):
539
return os.environ.get(self._reloader_environ_key)
543
from paste import reloader
544
reloader.install(int(1))
547
def restart_with_reloader(self):
548
"""Based on restart_with_monitor from paste.script.serve."""
549
print 'Starting subprocess with file monitor'
551
args = [sys.executable] + sys.argv
552
new_environ = os.environ.copy()
553
new_environ[self._reloader_environ_key] = 'true'
557
self._turn_sigterm_into_systemexit()
558
proc = subprocess.Popen(args, env=new_environ)
559
exit_code = proc.wait()
561
except KeyboardInterrupt:
562
print '^C caught in monitor process'
566
and hasattr(os, 'kill')):
569
os.kill(proc.pid, signal.SIGTERM)
570
except (OSError, IOError):
573
# Reloader always exits with code 3; but if we are
574
# a monitor, any exit code will restart
577
print '-'*20, 'Restarting', '-'*20