Patchwork D2050: util: extract makedate

login
register
mail settings
Submitter phabricator
Date Feb. 5, 2018, 4:24 p.m.
Message ID <differential-rev-PHID-DREV-6si3m6qdh6xnnef73im5-req@phab.mercurial-scm.org>
Download mbox | patch
Permalink /patch/27328/
State New
Headers show

Comments

phabricator - Feb. 5, 2018, 4:24 p.m.
lothiraldan created this revision.
Herald added a subscriber: mercurial-devel.
Herald added a reviewer: hg-reviewers.

REVISION SUMMARY
  Extract makedate from util.py to utils/dateutil.py

REPOSITORY
  rHG Mercurial

REVISION DETAIL
  https://phab.mercurial-scm.org/D2050

AFFECTED FILES
  contrib/synthrepo.py
  hgext/convert/common.py
  hgext/journal.py
  hgext/mq.py
  hgext/patchbomb.py
  hgext/shelve.py
  mercurial/changelog.py
  mercurial/commands.py
  mercurial/context.py
  mercurial/hgweb/hgwebdir_mod.py
  mercurial/obsolete.py
  mercurial/templater.py
  mercurial/util.py
  mercurial/utils/dateutil.py
  tests/test-journal.t

CHANGE DETAILS




To: lothiraldan, #hg-reviewers
Cc: mercurial-devel

Patch

diff --git a/tests/test-journal.t b/tests/test-journal.t
--- a/tests/test-journal.t
+++ b/tests/test-journal.t
@@ -4,6 +4,7 @@ 
   > # mock out util.getuser() and util.makedate() to supply testable values
   > import os
   > from mercurial import util
+  > from mercurial.utils import dateutil
   > def mockgetuser():
   >     return 'foobar'
   > 
@@ -19,7 +20,7 @@ 
   >     return (time, 0)
   > 
   > util.getuser = mockgetuser
-  > util.makedate = mockmakedate
+  > dateutil.makedate = mockmakedate
   > EOF
 
   $ cat >> $HGRCPATH << EOF
diff --git a/mercurial/utils/dateutil.py b/mercurial/utils/dateutil.py
--- a/mercurial/utils/dateutil.py
+++ b/mercurial/utils/dateutil.py
@@ -7,6 +7,14 @@ 
 
 from __future__ import absolute_import, print_function
 
+import datetime
+import time
+
+from ..i18n import _
+from .. import (
+    error,
+)
+
 # used by parsedate
 defaultdateformats = (
     '%Y-%m-%dT%H:%M:%S', # the 'real' ISO8601
@@ -48,3 +56,17 @@ 
     "%b",
     "%b %Y",
 )
+
+def makedate(timestamp=None):
+    '''Return a unix timestamp (or the current time) as a (unixtime,
+    offset) tuple based off the local timezone.'''
+    if timestamp is None:
+        timestamp = time.time()
+    if timestamp < 0:
+        hint = _("check your clock")
+        raise error.Abort(_("negative timestamp: %d") % timestamp, hint=hint)
+    delta = (datetime.datetime.utcfromtimestamp(timestamp) -
+             datetime.datetime.fromtimestamp(timestamp))
+    tz = delta.days * 86400 + delta.seconds
+    return timestamp, tz
+
diff --git a/mercurial/util.py b/mercurial/util.py
--- a/mercurial/util.py
+++ b/mercurial/util.py
@@ -1906,19 +1906,6 @@ 
             limit -= len(s)
         yield s
 
-def makedate(timestamp=None):
-    '''Return a unix timestamp (or the current time) as a (unixtime,
-    offset) tuple based off the local timezone.'''
-    if timestamp is None:
-        timestamp = time.time()
-    if timestamp < 0:
-        hint = _("check your clock")
-        raise Abort(_("negative timestamp: %d") % timestamp, hint=hint)
-    delta = (datetime.datetime.utcfromtimestamp(timestamp) -
-             datetime.datetime.fromtimestamp(timestamp))
-    tz = delta.days * 86400 + delta.seconds
-    return timestamp, tz
-
 def datestr(date=None, format='%a %b %d %H:%M:%S %Y %1%2'):
     """represent a (unixtime, offset) tuple as a localized time.
     unixtime is seconds since the epoch, and offset is the time zone's
@@ -1935,7 +1922,7 @@ 
     >>> datestr((-0x80000000, 0))
     'Fri Dec 13 20:45:52 1901 +0000'
     """
-    t, tz = date or makedate()
+    t, tz = date or dateutil.makedate()
     if "%1" in format or "%2" in format or "%z" in format:
         sign = (tz > 0) and "-" or "+"
         minutes = abs(tz) // 60
@@ -2033,7 +2020,7 @@ 
     ...     (datetime.date.today() - datetime.timedelta(days=1)
     ...      ).strftime('%b %d').encode('ascii'))
     True
-    >>> now, tz = makedate()
+    >>> now, tz = dateutil.makedate()
     >>> strnow, strtz = parsedate(b'now')
     >>> (strnow - now) < 1
     True
@@ -2051,7 +2038,7 @@ 
     date = date.strip()
 
     if date == 'now' or date == _('now'):
-        return makedate()
+        return dateutil.makedate()
     if date == 'today' or date == _('today'):
         date = datetime.date.today().strftime(r'%b %d')
         date = encoding.strtolocal(date)
@@ -2064,7 +2051,7 @@ 
         when, offset = map(int, date.split(' '))
     except ValueError:
         # fill out defaults
-        now = makedate()
+        now = dateutil.makedate()
         defaults = {}
         for part in ("d", "mb", "yY", "HI", "M", "S"):
             # this piece is for rounding the specific end of unknowns
@@ -2165,7 +2152,7 @@ 
         if days < 0:
             raise Abort(_("%s must be nonnegative (see 'hg help dates')")
                 % date[1:])
-        when = makedate()[0] - days * 3600 * 24
+        when = dateutil.makedate()[0] - days * 3600 * 24
         return lambda x: x >= when
     elif " to " in date:
         a, b = date.split(" to ")
@@ -3912,3 +3899,9 @@ 
 
 extendeddateformats = dateutil.extendeddateformats
 
+def makedate(*args, **kwargs):
+    msg = ("'util.makedate' is deprecated, "
+           "use 'utils.dateutil.makedate'")
+    nouideprecwarn(msg, "4.6")
+    return dateutil.makedate(*args, **kwargs)
+
diff --git a/mercurial/templater.py b/mercurial/templater.py
--- a/mercurial/templater.py
+++ b/mercurial/templater.py
@@ -29,6 +29,7 @@ 
     templatekw,
     util,
 )
+from .utils import dateutil
 
 # template parsing
 
@@ -922,7 +923,7 @@ 
                 # i18n: "localdate" is a keyword
                 raise error.ParseError(_("localdate expects a timezone"))
     else:
-        tzoffset = util.makedate()[1]
+        tzoffset = dateutil.makedate()[1]
     return (date[0], tzoffset)
 
 @templatefunc('max(iterable)')
diff --git a/mercurial/obsolete.py b/mercurial/obsolete.py
--- a/mercurial/obsolete.py
+++ b/mercurial/obsolete.py
@@ -81,6 +81,7 @@ 
     policy,
     util,
 )
+from .utils import dateutil
 
 parsers = policy.importmod(r'parsers')
 
@@ -612,9 +613,9 @@ 
             elif ui is not None:
                 date = ui.configdate('devel', 'default-date')
                 if date is None:
-                    date = util.makedate()
+                    date = dateutil.makedate()
             else:
-                date = util.makedate()
+                date = dateutil.makedate()
         if len(prec) != 20:
             raise ValueError(prec)
         for succ in succs:
diff --git a/mercurial/hgweb/hgwebdir_mod.py b/mercurial/hgweb/hgwebdir_mod.py
--- a/mercurial/hgweb/hgwebdir_mod.py
+++ b/mercurial/hgweb/hgwebdir_mod.py
@@ -40,6 +40,7 @@ 
     ui as uimod,
     util,
 )
+from ..utils import dateutil
 
 from . import (
     hgweb_mod,
@@ -376,7 +377,7 @@ 
                 if directory:
                     # get the directory's time information
                     try:
-                        d = (get_mtime(path), util.makedate()[1])
+                        d = (get_mtime(path), dateutil.makedate()[1])
                     except OSError:
                         continue
 
@@ -425,7 +426,7 @@ 
                     u.warn(_('error accessing repository at %s\n') % path)
                     continue
                 try:
-                    d = (get_mtime(r.spath), util.makedate()[1])
+                    d = (get_mtime(r.spath), dateutil.makedate()[1])
                 except OSError:
                     continue
 
diff --git a/mercurial/context.py b/mercurial/context.py
--- a/mercurial/context.py
+++ b/mercurial/context.py
@@ -48,6 +48,7 @@ 
     subrepo,
     util,
 )
+from .utils import dateutil
 
 propertycache = util.propertycache
 
@@ -1407,7 +1408,7 @@ 
         ui = self._repo.ui
         date = ui.configdate('devel', 'default-date')
         if date is None:
-            date = util.makedate()
+            date = dateutil.makedate()
         return date
 
     def subrev(self, subpath):
@@ -2154,11 +2155,11 @@ 
         if data is None:
             raise error.ProgrammingError("data must be non-None")
         self._auditconflicts(path)
-        self._markdirty(path, exists=True, data=data, date=util.makedate(),
+        self._markdirty(path, exists=True, data=data, date=dateutil.makedate(),
                         flags=flags)
 
     def setflags(self, path, l, x):
-        self._markdirty(path, exists=True, date=util.makedate(),
+        self._markdirty(path, exists=True, date=dateutil.makedate(),
                         flags=(l and 'l' or '') + (x and 'x' or ''))
 
     def remove(self, path):
diff --git a/mercurial/commands.py b/mercurial/commands.py
--- a/mercurial/commands.py
+++ b/mercurial/commands.py
@@ -60,6 +60,7 @@ 
     ui as uimod,
     util,
 )
+from .utils import dateutil
 
 release = lockmod.release
 
@@ -2153,7 +2154,7 @@ 
     if not opts.get('user') and opts.get('currentuser'):
         opts['user'] = ui.username()
     if not opts.get('date') and opts.get('currentdate'):
-        opts['date'] = "%d %d" % util.makedate()
+        opts['date'] = "%d %d" % dateutil.makedate()
 
     editor = cmdutil.getcommiteditor(editform='graft',
                                      **pycompat.strkwargs(opts))
diff --git a/mercurial/changelog.py b/mercurial/changelog.py
--- a/mercurial/changelog.py
+++ b/mercurial/changelog.py
@@ -23,6 +23,7 @@ 
     revlog,
     util,
 )
+from .utils import dateutil
 
 _defaultextra = {'branch': 'default'}
 
@@ -513,7 +514,7 @@ 
         if date:
             parseddate = "%d %d" % util.parsedate(date)
         else:
-            parseddate = "%d %d" % util.makedate()
+            parseddate = "%d %d" % dateutil.makedate()
         if extra:
             branch = extra.get("branch")
             if branch in ("default", ""):
diff --git a/hgext/shelve.py b/hgext/shelve.py
--- a/hgext/shelve.py
+++ b/hgext/shelve.py
@@ -51,6 +51,7 @@ 
     util,
     vfs as vfsmod,
 )
+from mercurial.utils import dateutil
 
 from . import (
     rebase,
@@ -563,7 +564,8 @@ 
             continue
         ui.write(' ' * (16 - len(sname)))
         used = 16
-        age = '(%s)' % templatefilters.age(util.makedate(mtime), abbrev=True)
+        date = dateutil.makedate(mtime)
+        age = '(%s)' % templatefilters.age(date, abbrev=True)
         ui.write(age, label='shelve.age')
         ui.write(' ' * (12 - len(age)))
         used += 12
diff --git a/hgext/patchbomb.py b/hgext/patchbomb.py
--- a/hgext/patchbomb.py
+++ b/hgext/patchbomb.py
@@ -96,6 +96,7 @@ 
     templater,
     util,
 )
+from mercurial.utils import dateutil
 stringio = util.stringio
 
 cmdtable = {}
@@ -664,7 +665,7 @@ 
     if date:
         start_time = util.parsedate(date)
     else:
-        start_time = util.makedate()
+        start_time = dateutil.makedate()
 
     def genmsgid(id):
         return '<%s.%s@%s>' % (id[:20], int(start_time[0]), socket.getfqdn())
diff --git a/hgext/mq.py b/hgext/mq.py
--- a/hgext/mq.py
+++ b/hgext/mq.py
@@ -97,6 +97,7 @@ 
     util,
     vfs as vfsmod,
 )
+from mercurial.utils import dateutil
 
 release = lockmod.release
 seriesopts = [('s', 'summary', None, _('print first line of patch header'))]
@@ -2597,7 +2598,7 @@ 
     if not opts.get('user') and opts.get('currentuser'):
         opts['user'] = ui.username()
     if not opts.get('date') and opts.get('currentdate'):
-        opts['date'] = "%d %d" % util.makedate()
+        opts['date'] = "%d %d" % dateutil.makedate()
 
 @command("^qnew",
          [('e', 'edit', None, _('invoke editor on commit messages')),
diff --git a/hgext/journal.py b/hgext/journal.py
--- a/hgext/journal.py
+++ b/hgext/journal.py
@@ -34,6 +34,7 @@ 
     registrar,
     util,
 )
+from mercurial.utils import dateutil
 
 from . import share
 
@@ -327,7 +328,7 @@ 
             newhashes = [newhashes]
 
         entry = journalentry(
-            util.makedate(), self.user, self.command, namespace, name,
+            dateutil.makedate(), self.user, self.command, namespace, name,
             oldhashes, newhashes)
 
         vfs = self.vfs
diff --git a/hgext/convert/common.py b/hgext/convert/common.py
--- a/hgext/convert/common.py
+++ b/hgext/convert/common.py
@@ -486,7 +486,7 @@ 
             self.fp = None
 
 def makedatetimestamp(t):
-    """Like util.makedate() but for time t instead of current time"""
+    """Like dateutil.makedate() but for time t instead of current time"""
     delta = (datetime.datetime.utcfromtimestamp(t) -
              datetime.datetime.fromtimestamp(t))
     tz = delta.days * 86400 + delta.seconds
diff --git a/contrib/synthrepo.py b/contrib/synthrepo.py
--- a/contrib/synthrepo.py
+++ b/contrib/synthrepo.py
@@ -59,8 +59,8 @@ 
     patch,
     registrar,
     scmutil,
-    util,
 )
+from mercurial.utils import dateutil
 
 # Note for extension authors: ONLY specify testedwith = 'ships-with-hg-core' for
 # extensions which SHIP WITH MERCURIAL. Non-mainline extensions should
@@ -382,7 +382,7 @@ 
         message = 'synthesized wide repo with %d files' % (len(files),)
         mc = context.memctx(repo, [pctx.node(), nullid], message,
                             files.iterkeys(), filectxfn, ui.username(),
-                            '%d %d' % util.makedate())
+                            '%d %d' % dateutil.makedate())
         initnode = mc.commit()
         if ui.debugflag:
             hexfn = hex