Debian Codegraph @

hgext/journal.py

raw
1 # journal.py
2 #
3 # Copyright 2014-2016 Facebook, Inc.
4 #
5 # This software may be used and distributed according to the terms of the
6 # GNU General Public License version 2 or any later version.
7 """track previous positions of bookmarks (EXPERIMENTAL)
8
9 This extension adds a new command: `hg journal`, which shows you where
10 bookmarks were previously located.
11
12 """
13
14 from __future__ import annotations
15
16 import collections
17 import os
18 import weakref
19
20 from mercurial.i18n import _
21 from mercurial.node import (
22 bin,
23 hex,
24 )
25
26 from mercurial import (
27 bookmarks,
28 cmdutil,
29 dispatch,
30 encoding,
31 error,
32 extensions,
33 hg,
34 localrepo,
35 lock,
36 logcmdutil,
37 merge,
38 pycompat,
39 registrar,
40 util,
41 )
42 from mercurial.cmd_impls import (
43 clone as clone_impl,
44 )
45 from mercurial.utils import (
46 dateutil,
47 procutil,
48 stringutil,
49 )
50
51 cmdtable = {}
52 command = registrar.command(cmdtable)
53
54 # Note for extension authors: ONLY specify testedwith = 'ships-with-hg-core' for
55 # extensions which SHIP WITH MERCURIAL. Non-mainline extensions should
56 # be specifying the version(s) of Mercurial they are tested with, or
57 # leave the attribute unspecified.
58 testedwith = b'ships-with-hg-core'
59
60 # storage format version; increment when the format changes
61 storageversion = 0
62
63 # namespaces
64 bookmarktype = b'bookmark'
65 wdirparenttype = b'wdirparent'
66 # In a shared repository, what shared feature name is used
67 # to indicate this namespace is shared with the source?
68 sharednamespaces = {
69 bookmarktype: clone_impl.sharedbookmarks,
70 }
71
72
73 # Journal recording, register hooks and storage object
74 def extsetup(ui):
75 merge.MAYBE_USE_RUST_UPDATE = False
76 extensions.wrapfunction(dispatch, 'runcommand', runcommand)
77 extensions.wrapfunction(bookmarks.bmstore, '_write', recordbookmarks)
78 extensions.wrapfilecache(
79 localrepo.localrepository, b'dirstate', wrapdirstate
80 )
81 extensions.wrapfunction(clone_impl, 'post_share', wrappostshare)
82 extensions.wrapfunction(clone_impl, 'copy_store', unsharejournal)
83
84
85 def reposetup(ui, repo):
86 if repo.local():
87 repo.journal = journalstorage(repo)
88 repo._wlockfreeprefix.add(b'namejournal')
89
90 dirstate, cached = localrepo.isfilecached(repo, b'dirstate')
91 if cached:
92 # already instantiated dirstate isn't yet marked as
93 # "journal"-ing, even though repo.dirstate() was already
94 # wrapped by own wrapdirstate()
95 _setupdirstate(repo, dirstate)
96
97
98 def runcommand(orig, lui, repo, cmd, fullargs, *args):
99 """Track the command line options for recording in the journal"""
100 journalstorage.recordcommand(*fullargs)
101 return orig(lui, repo, cmd, fullargs, *args)
102
103
104 def _setupdirstate(repo, dirstate):
105 dirstate.journalstorage = repo.journal
106 dirstate.addparentchangecallback(b'journal', recorddirstateparents)
107
108
109 # hooks to record dirstate changes
110 def wrapdirstate(orig, repo):
111 """Make journal storage available to the dirstate object"""
112 dirstate = orig(repo)
113 if hasattr(repo, 'journal'):
114 _setupdirstate(repo, dirstate)
115 return dirstate
116
117
118 def recorddirstateparents(dirstate, old, new):
119 """Records all dirstate parent changes in the journal."""
120 old = list(old)
121 new = list(new)
122 if hasattr(dirstate, 'journalstorage'):
123 # only record two hashes if there was a merge
124 oldhashes = old[:1] if old[1] == dirstate._nodeconstants.nullid else old
125 newhashes = new[:1] if new[1] == dirstate._nodeconstants.nullid else new
126 dirstate.journalstorage.record(
127 wdirparenttype, b'.', oldhashes, newhashes
128 )
129
130
131 # hooks to record bookmark changes (both local and remote)
132 def recordbookmarks(orig, store, fp):
133 """Records all bookmark changes in the journal."""
134 repo = store._repo
135 if hasattr(repo, 'journal'):
136 oldmarks = bookmarks.bmstore(repo)
137 all_marks = {b for b, n in oldmarks.items()}
138 all_marks.update(b for b, n in store.items())
139 for mark in sorted(all_marks):
140 value = store.get(mark, repo.nullid)
141 oldvalue = oldmarks.get(mark, repo.nullid)
142 if value != oldvalue:
143 repo.journal.record(bookmarktype, mark, oldvalue, value)
144 return orig(store, fp)
145
146
147 # shared repository support
148 def _readsharedfeatures(repo):
149 """A set of shared features for this repository"""
150 try:
151 return set(repo.vfs.read(b'shared').splitlines())
152 except FileNotFoundError:
153 return set()
154
155
156 def _mergeentriesiter(*iterables, **kwargs):
157 """Given a set of sorted iterables, yield the next entry in merged order
158
159 Note that by default entries go from most recent to oldest.
160 """
161 order = kwargs.pop('order', max)
162 iterables = [iter(it) for it in iterables]
163 # this tracks still active iterables; iterables are deleted as they are
164 # exhausted, which is why this is a dictionary and why each entry also
165 # stores the key. Entries are mutable so we can store the next value each
166 # time.
167 iterable_map = {}
168 for key, it in enumerate(iterables):
169 try:
170 iterable_map[key] = [next(it), key, it]
171 except StopIteration:
172 # empty entry, can be ignored
173 pass
174
175 while iterable_map:
176 value, key, it = order(iterable_map.values())
177 yield value
178 try:
179 iterable_map[key][0] = next(it)
180 except StopIteration:
181 # this iterable is empty, remove it from consideration
182 del iterable_map[key]
183
184
185 def wrappostshare(orig, sourcerepo, destrepo, **kwargs):
186 """Mark this shared working copy as sharing journal information"""
187 with destrepo.wlock():
188 orig(sourcerepo, destrepo, **kwargs)
189 with destrepo.vfs(b'shared', b'a') as fp:
190 fp.write(b'journal\n')
191
192
193 def unsharejournal(orig, ui, repo, repopath):
194 """Copy shared journal entries into this repo when unsharing"""
195 if repo.path == repopath and repo.shared() and hasattr(repo, 'journal'):
196 sharedrepo = hg.sharedreposource(repo)
197 sharedfeatures = _readsharedfeatures(repo)
198 if sharedrepo and sharedfeatures > {b'journal'}:
199 # there is a shared repository and there are shared journal entries
200 # to copy. move shared date over from source to destination but
201 # move the local file first
202 if repo.vfs.exists(b'namejournal'):
203 journalpath = repo.vfs.join(b'namejournal')
204 util.rename(journalpath, journalpath + b'.bak')
205 storage = repo.journal
206 local = storage._open(
207 repo.vfs, filename=b'namejournal.bak', _newestfirst=False
208 )
209 shared = (
210 e
211 for e in storage._open(sharedrepo.vfs, _newestfirst=False)
212 if sharednamespaces.get(e.namespace) in sharedfeatures
213 )
214 for entry in _mergeentriesiter(local, shared, order=min):
215 storage._write(repo.vfs, entry)
216
217 return orig(ui, repo, repopath)
218
219
220 class journalentry(
221 collections.namedtuple(
222 'journalentry',
223 'timestamp user command namespace name oldhashes newhashes',
224 )
225 ):
226 """Individual journal entry
227
228 * timestamp: a mercurial (time, timezone) tuple
229 * user: the username that ran the command
230 * namespace: the entry namespace, an opaque string
231 * name: the name of the changed item, opaque string with meaning in the
232 namespace
233 * command: the hg command that triggered this record
234 * oldhashes: a tuple of one or more binary hashes for the old location
235 * newhashes: a tuple of one or more binary hashes for the new location
236
237 Handles serialisation from and to the storage format. Fields are
238 separated by newlines, hashes are written out in hex separated by commas,
239 timestamp and timezone are separated by a space.
240
241 """
242
243 @classmethod
244 def fromstorage(cls, line):
245 (
246 time,
247 user,
248 command,
249 namespace,
250 name,
251 oldhashes,
252 newhashes,
253 ) = line.split(b'\n')
254 timestamp, tz = time.split()
255 timestamp, tz = float(timestamp), int(tz)
256 oldhashes = tuple(bin(hash) for hash in oldhashes.split(b','))
257 newhashes = tuple(bin(hash) for hash in newhashes.split(b','))
258 return cls(
259 (timestamp, tz),
260 user,
261 command,
262 namespace,
263 name,
264 oldhashes,
265 newhashes,
266 )
267
268 def __bytes__(self):
269 """bytes representation for storage"""
270 time = b' '.join(map(pycompat.bytestr, self.timestamp))
271 oldhashes = b','.join([hex(hash) for hash in self.oldhashes])
272 newhashes = b','.join([hex(hash) for hash in self.newhashes])
273 return b'\n'.join(
274 (
275 time,
276 self.user,
277 self.command,
278 self.namespace,
279 self.name,
280 oldhashes,
281 newhashes,
282 )
283 )
284
285 __str__ = encoding.strmethod(__bytes__)
286
287
288 class journalstorage:
289 """Storage for journal entries
290
291 Entries are divided over two files; one with entries that pertain to the
292 local working copy *only*, and one with entries that are shared across
293 multiple working copies when shared using the share extension.
294
295 Entries are stored with NUL bytes as separators. See the journalentry
296 class for the per-entry structure.
297
298 The file format starts with an integer version, delimited by a NUL.
299
300 This storage uses a dedicated lock; this makes it easier to avoid issues
301 with adding entries that added when the regular wlock is unlocked (e.g.
302 the dirstate).
303
304 """
305
306 _currentcommand = ()
307 _lockref = None
308
309 def __init__(self, repo):
310 self.user = procutil.getuser()
311 self.ui = repo.ui
312 self.vfs = repo.vfs
313
314 # is this working copy using a shared storage?
315 self.sharedfeatures = self.sharedvfs = None
316 if repo.shared():
317 features = _readsharedfeatures(repo)
318 sharedrepo = hg.sharedreposource(repo)
319 if sharedrepo is not None and b'journal' in features:
320 self.sharedvfs = sharedrepo.vfs
321 self.sharedfeatures = features
322
323 # track the current command for recording in journal entries
324 @property
325 def command(self):
326 commandstr = b' '.join(
327 map(procutil.shellquote, journalstorage._currentcommand)
328 )
329 if b'\n' in commandstr:
330 # truncate multi-line commands
331 commandstr = commandstr.partition(b'\n')[0] + b' ...'
332 return commandstr
333
334 @classmethod
335 def recordcommand(cls, *fullargs):
336 """Set the current hg arguments, stored with recorded entries"""
337 # Set the current command on the class because we may have started
338 # with a non-local repo (cloning for example).
339 cls._currentcommand = fullargs
340
341 def _currentlock(self, lockref):
342 """Returns the lock if it's held, or None if it's not.
343
344 (This is copied from the localrepo class)
345 """
346 if lockref is None:
347 return None
348 l = lockref()
349 if l is None or not l.held:
350 return None
351 return l
352
353 def jlock(self, vfs):
354 """Create a lock for the journal file"""
355 if self._currentlock(self._lockref) is not None:
356 raise error.Abort(_(b'journal lock does not support nesting'))
357 desc = _(b'journal of %s') % vfs.base
358 try:
359 l = lock.lock(vfs, b'namejournal.lock', 0, desc=desc)
360 except error.LockHeld as inst:
361 self.ui.warn(
362 _(b"waiting for lock on %s held by %r\n") % (desc, inst.locker)
363 )
364 # default to 600 seconds timeout
365 l = lock.lock(
366 vfs,
367 b'namejournal.lock',
368 self.ui.configint(b"ui", b"timeout"),
369 desc=desc,
370 )
371 self.ui.warn(_(b"got lock after %s seconds\n") % l.delay)
372 self._lockref = weakref.ref(l)
373 return l
374
375 def record(self, namespace, name, oldhashes, newhashes):
376 """Record a new journal entry
377
378 * namespace: an opaque string; this can be used to filter on the type
379 of recorded entries.
380 * name: the name defining this entry; for bookmarks, this is the
381 bookmark name. Can be filtered on when retrieving entries.
382 * oldhashes and newhashes: each a single binary hash, or a list of
383 binary hashes. These represent the old and new position of the named
384 item.
385
386 """
387 if not isinstance(oldhashes, list):
388 oldhashes = [oldhashes]
389 if not isinstance(newhashes, list):
390 newhashes = [newhashes]
391
392 entry = journalentry(
393 dateutil.makedate(),
394 self.user,
395 self.command,
396 namespace,
397 name,
398 oldhashes,
399 newhashes,
400 )
401
402 vfs = self.vfs
403 if self.sharedvfs is not None:
404 # write to the shared repository if this feature is being
405 # shared between working copies.
406 if sharednamespaces.get(namespace) in self.sharedfeatures:
407 vfs = self.sharedvfs
408
409 self._write(vfs, entry)
410
411 def _write(self, vfs, entry):
412 with self.jlock(vfs):
413 # open file in amend mode to ensure it is created if missing
414 with vfs(b'namejournal', mode=b'a+b') as f:
415 f.seek(0, os.SEEK_SET)
416 # Read just enough bytes to get a version number (up to 2
417 # digits plus separator)
418 version = f.read(3).partition(b'\0')[0]
419 if version and version != b"%d" % storageversion:
420 # different version of the storage. Exit early (and not
421 # write anything) if this is not a version we can handle or
422 # the file is corrupt. In future, perhaps rotate the file
423 # instead?
424 self.ui.warn(
425 _(b"unsupported journal file version '%s'\n") % version
426 )
427 return
428 if not version:
429 # empty file, write version first
430 f.write((b"%d" % storageversion) + b'\0')
431 f.seek(0, os.SEEK_END)
432 f.write(bytes(entry) + b'\0')
433
434 def filtered(self, namespace=None, name=None):
435 """Yield all journal entries with the given namespace or name
436
437 Both the namespace and the name are optional; if neither is given all
438 entries in the journal are produced.
439
440 Matching supports regular expressions by using the `re:` prefix
441 (use `literal:` to match names or namespaces that start with `re:`)
442
443 """
444 if namespace is not None:
445 namespace = stringutil.stringmatcher(namespace)[-1]
446 if name is not None:
447 name = stringutil.stringmatcher(name)[-1]
448 for entry in self:
449 if namespace is not None and not namespace(entry.namespace):
450 continue
451 if name is not None and not name(entry.name):
452 continue
453 yield entry
454
455 def __iter__(self):
456 """Iterate over the storage
457
458 Yields journalentry instances for each contained journal record.
459
460 """
461 local = self._open(self.vfs)
462
463 if self.sharedvfs is None:
464 return local
465
466 # iterate over both local and shared entries, but only those
467 # shared entries that are among the currently shared features
468 shared = (
469 e
470 for e in self._open(self.sharedvfs)
471 if sharednamespaces.get(e.namespace) in self.sharedfeatures
472 )
473 return _mergeentriesiter(local, shared)
474
475 def _open(self, vfs, filename=b'namejournal', _newestfirst=True):
476 if not vfs.exists(filename):
477 return
478
479 with vfs(filename) as f:
480 raw = f.read()
481
482 lines = raw.split(b'\0')
483 version = lines and lines[0]
484 if version != b"%d" % storageversion:
485 version = version or _(b'not available')
486 raise error.Abort(_(b"unknown journal file version '%s'") % version)
487
488 # Skip the first line, it's a version number. Normally we iterate over
489 # these in reverse order to list newest first; only when copying across
490 # a shared storage do we forgo reversing.
491 lines = lines[1:]
492 if _newestfirst:
493 lines = reversed(lines)
494 for line in lines:
495 if not line:
496 continue
497 yield journalentry.fromstorage(line)
498
499
500 # journal reading
501 # log options that don't make sense for journal
502 _ignoreopts = (b'no-merges', b'graph')
503
504
505 @command(
506 b'journal',
507 [
508 (b'', b'all', None, b'show history for all names'),
509 (b'c', b'commits', None, b'show commit metadata'),
510 ]
511 + [opt for opt in cmdutil.logopts if opt[1] not in _ignoreopts],
512 b'[OPTION]... [BOOKMARKNAME]',
513 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
514 )
515 def journal(ui, repo, *args, **opts):
516 """show the previous position of bookmarks and the working copy
517
518 The journal is used to see the previous commits that bookmarks and the
519 working copy pointed to. By default the previous locations for the working
520 copy. Passing a bookmark name will show all the previous positions of
521 that bookmark. Use the --all switch to show previous locations for all
522 bookmarks and the working copy; each line will then include the bookmark
523 name, or '.' for the working copy, as well.
524
525 If `name` starts with `re:`, the remainder of the name is treated as
526 a regular expression. To match a name that actually starts with `re:`,
527 use the prefix `literal:`.
528
529 By default hg journal only shows the commit hash and the command that was
530 running at that time. -v/--verbose will show the prior hash, the user, and
531 the time at which it happened.
532
533 Use -c/--commits to output log information on each commit hash; at this
534 point you can use the usual `--patch`, `--git`, `--stat` and `--template`
535 switches to alter the log output for these.
536
537 `hg journal -T json` can be used to produce machine readable output.
538
539 """
540 opts = pycompat.byteskwargs(opts)
541 name = b'.'
542 if opts.get(b'all'):
543 if args:
544 raise error.Abort(
545 _(b"You can't combine --all and filtering on a name")
546 )
547 name = None
548 if args:
549 name = args[0]
550
551 fm = ui.formatter(b'journal', opts)
552
553 def formatnodes(nodes):
554 return fm.formatlist(map(fm.hexfunc, nodes), name=b'node', sep=b',')
555
556 if opts.get(b"template") != b"json":
557 if name is None:
558 displayname = _(b'the working copy and bookmarks')
559 else:
560 displayname = b"'%s'" % name
561 ui.status(_(b"previous locations of %s:\n") % displayname)
562
563 limit = logcmdutil.getlimit(opts)
564 entry = None
565 ui.pager(b'journal')
566 for count, entry in enumerate(repo.journal.filtered(name=name)):
567 if count == limit:
568 break
569
570 fm.startitem()
571 fm.condwrite(
572 ui.verbose, b'oldnodes', b'%s -> ', formatnodes(entry.oldhashes)
573 )
574 fm.write(b'newnodes', b'%s', formatnodes(entry.newhashes))
575 fm.condwrite(ui.verbose, b'user', b' %-8s', entry.user)
576
577 # ``name`` is bytes, or None only if 'all' was an option.
578 fm.condwrite(
579 # pytype: disable=attribute-error
580 opts.get(b'all') or name.startswith(b're:'),
581 # pytype: enable=attribute-error
582 b'name',
583 b' %-8s',
584 entry.name,
585 )
586
587 fm.condwrite(
588 ui.verbose,
589 b'date',
590 b' %s',
591 fm.formatdate(entry.timestamp, b'%Y-%m-%d %H:%M %1%2'),
592 )
593 fm.write(b'command', b' %s\n', entry.command)
594
595 if opts.get(b"commits"):
596 if fm.isplain():
597 displayer = logcmdutil.changesetdisplayer(ui, repo, opts)
598 else:
599 displayer = logcmdutil.changesetformatter(
600 ui, repo, fm.nested(b'changesets'), diffopts=opts
601 )
602 for hash in entry.newhashes:
603 try:
604 ctx = repo[hash]
605 displayer.show(ctx)
606 except error.RepoLookupError as e:
607 fm.plain(b"%s\n\n" % pycompat.bytestr(e))
608 displayer.close()
609
610 fm.end()
611
612 if entry is None:
613 ui.status(_(b"no recorded locations\n"))