D370: templatefilters: add `reldate` for human-style relative dates
phillco (Phil Cohen)
phabricator at mercurial-scm.org
Mon Aug 14 03:06:10 UTC 2017
phillco created this revision.
Herald added a subscriber: mercurial-devel.
Herald added a reviewer: hg-reviewers.
REVISION SUMMARY
e.g., "3 days ago", "6 hours ago", etc.
REPOSITORY
rHG Mercurial
REVISION DETAIL
https://phab.mercurial-scm.org/D370
AFFECTED FILES
mercurial/templatefilters.py
tests/test-command-template.t
CHANGE DETAILS
diff --git a/tests/test-command-template.t b/tests/test-command-template.t
--- a/tests/test-command-template.t
+++ b/tests/test-command-template.t
@@ -2091,6 +2091,27 @@
1970-01-13 17:33:20 +0000
1970-01-12 13:46:40 +0000
+ $ cat > oldtime.py <<EOF
+ > import time
+ > def oldtime():
+ > return 1500500
+ > time.time = oldtime
+ > EOF
+ $ cp $HGRCPATH $HGRCPATH.bak
+ $ echo "[extensions]" >> $HGRCPATH
+ $ echo "loop=`pwd`/oldtime.py" >> $HGRCPATH
+ $ hg log --template '{date|reldate}\n'
+ 2020-01-01
+ 5 days ago
+ 8 minutes ago
+ 8 minutes ago
+ 1 day ago
+ 2 days ago
+ 3 days ago
+ 4 days ago
+ 5 days ago
+ $ mv $HGRCPATH.bak $HGRCPATH
+
$ hg log --template '{date|rfc822date}\n'
Wed, 01 Jan 2020 10:01:00 +0000
Mon, 12 Jan 1970 13:46:40 +0000
diff --git a/mercurial/templatefilters.py b/mercurial/templatefilters.py
--- a/mercurial/templatefilters.py
+++ b/mercurial/templatefilters.py
@@ -206,6 +206,37 @@
"""
return util.datestr(text, '%Y-%m-%d %H:%M:%S %1%2')
+ at templatefilter('reldate')
+def reldate(text):
+ """Date. Returns how long ago the date was in relative human-readable form,
+ e.g. "3 hours ago".
+
+ If the date is more than a week old, returns an ISO-like string in the
+ format "%Y-%m-%d".
+ """
+ # From https://stackoverflow.com/a/5164027/303833
+ date = util.hgdatetopython(text)
+ delta = util.hgdatetopython(util.makedate()) - date
+ secs = delta.seconds
+ if delta.days > 7 or delta.days < 0:
+ return date.strftime('%Y-%m-%d')
+ elif delta.days == 1:
+ return '1 day ago'
+ elif delta.days > 1:
+ return '%d days ago' % delta.days
+ elif secs <= 1:
+ return 'just now'
+ elif secs < 60:
+ return '%d seconds ago' % secs
+ elif secs < 120:
+ return '1 minute ago'
+ elif secs < 3600:
+ return '%d minutes ago' % (secs / 60)
+ elif secs < 7200:
+ return '1 hour ago'
+ else:
+ return '%d hours ago' % (secs / 3600)
+
def indent(text, prefix):
'''indent each non-empty line of text after first with prefix.'''
lines = text.splitlines()
To: phillco, #hg-reviewers
Cc: mercurial-devel
More information about the Mercurial-devel
mailing list