Debian Codegraph @

hgext/mq.py

raw
1 # mq.py - patch queues for mercurial
2 #
3 # Copyright 2005, 2006 Chris Mason <[email protected]>
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
8 '''manage a stack of patches
9
10 This extension lets you work with a stack of patches in a Mercurial
11 repository. It manages two stacks of patches - all known patches, and
12 applied patches (subset of known patches).
13
14 Known patches are represented as patch files in the .hg/patches
15 directory. Applied patches are both patch files and changesets.
16
17 Common tasks (use :hg:`help COMMAND` for more details)::
18
19 create new patch qnew
20 import existing patch qimport
21
22 print patch series qseries
23 print applied patches qapplied
24
25 add known patch to applied stack qpush
26 remove patch from applied stack qpop
27 refresh contents of top applied patch qrefresh
28
29 By default, mq will automatically use git patches when required to
30 avoid losing file mode changes, copy records, binary files or empty
31 files creations or deletions. This behavior can be configured with::
32
33 [mq]
34 git = auto/keep/yes/no
35
36 If set to 'keep', mq will obey the [diff] section configuration while
37 preserving existing git patches upon qrefresh. If set to 'yes' or
38 'no', mq will override the [diff] section and always generate git or
39 regular patches, possibly losing data in the second case.
40
41 It may be desirable for mq changesets to be kept in the secret phase (see
42 :hg:`help phases`), which can be enabled with the following setting::
43
44 [mq]
45 secret = True
46
47 You will by default be managing a patch queue named "patches". You can
48 create other, independent patch queues with the :hg:`qqueue` command.
49
50 If the working directory contains uncommitted files, qpush, qpop and
51 qgoto abort immediately. If -f/--force is used, the changes are
52 discarded. Setting::
53
54 [mq]
55 keepchanges = True
56
57 make them behave as if --keep-changes were passed, and non-conflicting
58 local changes will be tolerated and preserved. If incompatible options
59 such as -f/--force or --exact are passed, this setting is ignored.
60
61 This extension used to provide a strip command. This command now lives
62 in the strip extension.
63 '''
64
65 from __future__ import annotations
66
67 import os
68 import re
69 import shutil
70 import sys
71 from mercurial.i18n import _
72 from mercurial.node import (
73 bin,
74 hex,
75 nullrev,
76 short,
77 )
78 from mercurial import (
79 cmdutil,
80 commands,
81 encoding,
82 error,
83 extensions,
84 localrepo,
85 lock as lockmod,
86 logcmdutil,
87 patch as patchmod,
88 phases,
89 pycompat,
90 registrar,
91 repo as repo_utils,
92 revsetlang,
93 scmutil,
94 smartset,
95 strip,
96 subrepoutil,
97 util,
98 vfs as vfsmod,
99 )
100 from mercurial.cmd_impls import (
101 clone as clone_impl,
102 update as up_impl,
103 )
104 from mercurial.main_script import (
105 cmd_finder,
106 )
107 from mercurial.repo import (
108 factory as repo_factory,
109 )
110 from mercurial.utils import (
111 dateutil,
112 stringutil,
113 urlutil,
114 )
115
116 release = lockmod.release
117 seriesopts = [(b's', b'summary', None, _(b'print first line of patch header'))]
118
119 cmdtable = {}
120 command = registrar.command(cmdtable)
121 # Note for extension authors: ONLY specify testedwith = 'ships-with-hg-core' for
122 # extensions which SHIP WITH MERCURIAL. Non-mainline extensions should
123 # be specifying the version(s) of Mercurial they are tested with, or
124 # leave the attribute unspecified.
125 testedwith = b'ships-with-hg-core'
126
127 configtable = {}
128 configitem = registrar.configitem(configtable)
129
130 configitem(
131 b'mq',
132 b'git',
133 default=b'auto',
134 )
135 configitem(
136 b'mq',
137 b'keepchanges',
138 default=False,
139 )
140 configitem(
141 b'mq',
142 b'plain',
143 default=False,
144 )
145 configitem(
146 b'mq',
147 b'secret',
148 default=False,
149 )
150
151 # force load strip extension formerly included in mq and import some utility
152 try:
153 extensions.find(b'strip')
154 except KeyError:
155 # note: load is lazy so we could avoid the try-except,
156 # but I (marmoute) prefer this explicit code.
157 class dummyui:
158 def debug(self, msg):
159 pass
160
161 def log(self, event, msgfmt, *msgargs, **opts):
162 pass
163
164 extensions.load(dummyui(), b'strip', b'')
165
166 strip = strip.strip
167
168
169 def checksubstate(repo, baserev=None):
170 """return list of subrepos at a different revision than substate.
171 Abort if any subrepos have uncommitted changes."""
172 inclsubs = []
173 wctx = repo[None]
174 if baserev:
175 bctx = repo[baserev]
176 else:
177 bctx = wctx.p1()
178 for s in sorted(wctx.substate):
179 wctx.sub(s).bailifchanged(True)
180 if s not in bctx.substate or bctx.sub(s).dirty():
181 inclsubs.append(s)
182 return inclsubs
183
184
185 # Patch names looks like unix-file names.
186 # They must be joinable with queue directory and result in the patch path.
187 normname = util.normpath
188
189
190 class statusentry:
191 def __init__(self, node, name):
192 self.node, self.name = node, name
193
194 def __bytes__(self):
195 return hex(self.node) + b':' + self.name
196
197 __str__ = encoding.strmethod(__bytes__)
198 __repr__ = encoding.strmethod(__bytes__)
199
200
201 # The order of the headers in 'hg export' HG patches:
202 HGHEADERS = [
203 # '# HG changeset patch',
204 b'# User ',
205 b'# Date ',
206 b'# ',
207 b'# Branch ',
208 b'# Node ID ',
209 b'# Parent ', # can occur twice for merges - but that is not relevant for mq
210 ]
211 # The order of headers in plain 'mail style' patches:
212 PLAINHEADERS = {
213 b'from': 0,
214 b'date': 1,
215 b'subject': 2,
216 }
217
218
219 def inserthgheader(lines, header, value):
220 """Assuming lines contains a HG patch header, add a header line with value.
221 >>> try: inserthgheader([], b'# Date ', b'z')
222 ... except ValueError as inst: print("oops")
223 oops
224 >>> inserthgheader([b'# HG changeset patch'], b'# Date ', b'z')
225 ['# HG changeset patch', '# Date z']
226 >>> inserthgheader([b'# HG changeset patch', b''], b'# Date ', b'z')
227 ['# HG changeset patch', '# Date z', '']
228 >>> inserthgheader([b'# HG changeset patch', b'# User y'], b'# Date ', b'z')
229 ['# HG changeset patch', '# User y', '# Date z']
230 >>> inserthgheader([b'# HG changeset patch', b'# Date x', b'# User y'],
231 ... b'# User ', b'z')
232 ['# HG changeset patch', '# Date x', '# User z']
233 >>> inserthgheader([b'# HG changeset patch', b'# Date y'], b'# Date ', b'z')
234 ['# HG changeset patch', '# Date z']
235 >>> inserthgheader([b'# HG changeset patch', b'', b'# Date y'],
236 ... b'# Date ', b'z')
237 ['# HG changeset patch', '# Date z', '', '# Date y']
238 >>> inserthgheader([b'# HG changeset patch', b'# Parent y'],
239 ... b'# Date ', b'z')
240 ['# HG changeset patch', '# Date z', '# Parent y']
241 """
242 start = lines.index(b'# HG changeset patch') + 1
243 newindex = HGHEADERS.index(header)
244 bestpos = len(lines)
245 for i in range(start, len(lines)):
246 line = lines[i]
247 if not line.startswith(b'# '):
248 bestpos = min(bestpos, i)
249 break
250 for lineindex, h in enumerate(HGHEADERS):
251 if line.startswith(h):
252 if lineindex == newindex:
253 lines[i] = header + value
254 return lines
255 if lineindex > newindex:
256 bestpos = min(bestpos, i)
257 break # next line
258 lines.insert(bestpos, header + value)
259 return lines
260
261
262 def insertplainheader(lines, header, value):
263 """For lines containing a plain patch header, add a header line with value.
264 >>> insertplainheader([], b'Date', b'z')
265 ['Date: z']
266 >>> insertplainheader([b''], b'Date', b'z')
267 ['Date: z', '']
268 >>> insertplainheader([b'x'], b'Date', b'z')
269 ['Date: z', '', 'x']
270 >>> insertplainheader([b'From: y', b'x'], b'Date', b'z')
271 ['From: y', 'Date: z', '', 'x']
272 >>> insertplainheader([b' date : x', b' from : y', b''], b'From', b'z')
273 [' date : x', 'From: z', '']
274 >>> insertplainheader([b'', b'Date: y'], b'Date', b'z')
275 ['Date: z', '', 'Date: y']
276 >>> insertplainheader([b'foo: bar', b'DATE: z', b'x'], b'From', b'y')
277 ['From: y', 'foo: bar', 'DATE: z', '', 'x']
278 """
279 newprio = PLAINHEADERS[header.lower()]
280 bestpos = len(lines)
281 for i, line in enumerate(lines):
282 if b':' in line:
283 lheader = line.split(b':', 1)[0].strip().lower()
284 lprio = PLAINHEADERS.get(lheader, newprio + 1)
285 if lprio == newprio:
286 lines[i] = b'%s: %s' % (header, value)
287 return lines
288 if lprio > newprio and i < bestpos:
289 bestpos = i
290 else:
291 if line:
292 lines.insert(i, b'')
293 if i < bestpos:
294 bestpos = i
295 break
296 lines.insert(bestpos, b'%s: %s' % (header, value))
297 return lines
298
299
300 class patchheader:
301 def __init__(self, pf, plainmode=False):
302 def eatdiff(lines):
303 while lines:
304 l = lines[-1]
305 if (
306 l.startswith(b"diff -")
307 or l.startswith(b"Index:")
308 or l.startswith(b"===========")
309 ):
310 del lines[-1]
311 else:
312 break
313
314 def eatempty(lines):
315 while lines:
316 if not lines[-1].strip():
317 del lines[-1]
318 else:
319 break
320
321 message = []
322 comments = []
323 user = None
324 date = None
325 parent = None
326 format = None
327 subject = None
328 branch = None
329 nodeid = None
330 diffstart = 0
331
332 with open(pf, 'rb') as fp:
333 for line in fp:
334 line = line.rstrip()
335 if line.startswith(b'diff --git') or (
336 diffstart and line.startswith(b'+++ ')
337 ):
338 diffstart = 2
339 break
340 diffstart = 0 # reset
341 if line.startswith(b"--- "):
342 diffstart = 1
343 continue
344 elif format == b"hgpatch":
345 # parse values when importing the result of an hg export
346 if line.startswith(b"# User "):
347 user = line[7:]
348 elif line.startswith(b"# Date "):
349 date = line[7:]
350 elif line.startswith(b"# Parent "):
351 parent = line[
352 9:
353 ].lstrip() # handle double trailing space
354 elif line.startswith(b"# Branch "):
355 branch = line[9:]
356 elif line.startswith(b"# Node ID "):
357 nodeid = line[10:]
358 elif not line.startswith(b"# ") and line:
359 message.append(line)
360 format = None
361 elif line == b'# HG changeset patch':
362 message = []
363 format = b"hgpatch"
364 elif format != b"tagdone" and (
365 line.startswith(b"Subject: ")
366 or line.startswith(b"subject: ")
367 ):
368 subject = line[9:]
369 format = b"tag"
370 elif format != b"tagdone" and (
371 line.startswith(b"From: ") or line.startswith(b"from: ")
372 ):
373 user = line[6:]
374 format = b"tag"
375 elif format != b"tagdone" and (
376 line.startswith(b"Date: ") or line.startswith(b"date: ")
377 ):
378 date = line[6:]
379 format = b"tag"
380 elif format == b"tag" and line == b"":
381 # when looking for tags (subject: from: etc) they
382 # end once you find a blank line in the source
383 format = b"tagdone"
384 elif message or line:
385 message.append(line)
386 comments.append(line)
387
388 eatdiff(message)
389 eatdiff(comments)
390 # Remember the exact starting line of the patch diffs before consuming
391 # empty lines, for external use by TortoiseHg and others
392 self.diffstartline = len(comments)
393 eatempty(message)
394 eatempty(comments)
395
396 # make sure message isn't empty
397 if format and format.startswith(b"tag") and subject:
398 message.insert(0, subject)
399
400 self.message = message
401 self.comments = comments
402 self.user = user
403 self.date = date
404 self.parent = parent
405 # nodeid and branch are for external use by TortoiseHg and others
406 self.nodeid = nodeid
407 self.branch = branch
408 self.haspatch = diffstart > 1
409 self.plainmode = (
410 plainmode
411 or b'# HG changeset patch' not in self.comments
412 and any(
413 c.startswith(b'Date: ') or c.startswith(b'From: ')
414 for c in self.comments
415 )
416 )
417
418 def setuser(self, user):
419 try:
420 inserthgheader(self.comments, b'# User ', user)
421 except ValueError:
422 if self.plainmode:
423 insertplainheader(self.comments, b'From', user)
424 else:
425 tmp = [b'# HG changeset patch', b'# User ' + user]
426 self.comments = tmp + self.comments
427 self.user = user
428
429 def setdate(self, date):
430 try:
431 inserthgheader(self.comments, b'# Date ', date)
432 except ValueError:
433 if self.plainmode:
434 insertplainheader(self.comments, b'Date', date)
435 else:
436 tmp = [b'# HG changeset patch', b'# Date ' + date]
437 self.comments = tmp + self.comments
438 self.date = date
439
440 def setparent(self, parent):
441 try:
442 inserthgheader(self.comments, b'# Parent ', parent)
443 except ValueError:
444 if not self.plainmode:
445 tmp = [b'# HG changeset patch', b'# Parent ' + parent]
446 self.comments = tmp + self.comments
447 self.parent = parent
448
449 def setmessage(self, message):
450 if self.comments:
451 self._delmsg()
452 self.message = [message]
453 if message:
454 if self.plainmode and self.comments and self.comments[-1]:
455 self.comments.append(b'')
456 self.comments.append(message)
457
458 def __bytes__(self):
459 s = b'\n'.join(self.comments).rstrip()
460 if not s:
461 return b''
462 return s + b'\n\n'
463
464 __str__ = encoding.strmethod(__bytes__)
465
466 def _delmsg(self):
467 """Remove existing message, keeping the rest of the comments fields.
468 If comments contains 'subject: ', message will prepend
469 the field and a blank line."""
470 if self.message:
471 subj = b'subject: ' + self.message[0].lower()
472 for i in range(len(self.comments)):
473 if subj == self.comments[i].lower():
474 del self.comments[i]
475 self.message = self.message[2:]
476 break
477 ci = 0
478 for mi in self.message:
479 while mi != self.comments[ci]:
480 ci += 1
481 del self.comments[ci]
482
483
484 def newcommit(repo, phase, *args, **kwargs):
485 """helper dedicated to ensure a commit respect mq.secret setting
486
487 It should be used instead of repo.commit inside the mq source for operation
488 creating new changeset.
489 """
490 repo = repo.unfiltered()
491 if phase is None:
492 if repo.ui.configbool(b'mq', b'secret'):
493 phase = phases.secret
494 overrides = {(b'ui', b'allowemptycommit'): True}
495 if phase is not None:
496 overrides[(b'phases', b'new-commit')] = phase
497 with repo.ui.configoverride(overrides, b'mq'):
498 repo.ui.setconfig(b'ui', b'allowemptycommit', True)
499 return repo.commit(*args, **kwargs)
500
501
502 class AbortNoCleanup(error.Abort):
503 pass
504
505
506 class queue:
507 def __init__(self, ui, baseui, path, patchdir=None):
508 self.basepath = path
509 try:
510 with open(os.path.join(path, b'patches.queue'), 'rb') as fh:
511 cur = fh.read().rstrip()
512
513 if not cur:
514 curpath = os.path.join(path, b'patches')
515 else:
516 curpath = os.path.join(path, b'patches-' + cur)
517 except OSError:
518 curpath = os.path.join(path, b'patches')
519 self.path = patchdir or curpath
520 self.opener = vfsmod.vfs(self.path)
521 self.ui = ui
522 self.baseui = baseui
523 self.applieddirty = False
524 self.seriesdirty = False
525 self.added = []
526 self.seriespath = b"series"
527 self.statuspath = b"status"
528 self.guardspath = b"guards"
529 self.activeguards = None
530 self.guardsdirty = False
531 # Handle mq.git as a bool with extended values
532 gitmode = ui.config(b'mq', b'git').lower()
533 boolmode = stringutil.parsebool(gitmode)
534 if boolmode is not None:
535 if boolmode:
536 gitmode = b'yes'
537 else:
538 gitmode = b'no'
539 self.gitmode = gitmode
540 # deprecated config: mq.plain
541 self.plainmode = ui.configbool(b'mq', b'plain')
542 self.checkapplied = True
543
544 @util.propertycache
545 def applied(self):
546 def parselines(lines):
547 for l in lines:
548 entry = l.split(b':', 1)
549 if len(entry) > 1:
550 n, name = entry
551 yield statusentry(bin(n), name)
552 elif l.strip():
553 self.ui.warn(
554 _(b'malformated mq status line: %s\n')
555 % stringutil.pprint(entry)
556 )
557 # else we ignore empty lines
558
559 try:
560 lines = self.opener.read(self.statuspath).splitlines()
561 return list(parselines(lines))
562 except FileNotFoundError:
563 return []
564
565 @util.propertycache
566 def fullseries(self):
567 try:
568 return self.opener.read(self.seriespath).splitlines()
569 except FileNotFoundError:
570 return []
571
572 @util.propertycache
573 def series(self):
574 self.parseseries()
575 return self.series
576
577 @util.propertycache
578 def seriesguards(self):
579 self.parseseries()
580 return self.seriesguards
581
582 def invalidate(self):
583 for a in 'applied fullseries series seriesguards'.split():
584 if a in self.__dict__:
585 delattr(self, a)
586 self.applieddirty = False
587 self.seriesdirty = False
588 self.guardsdirty = False
589 self.activeguards = None
590
591 def diffopts(self, opts=None, patchfn=None, plain=False):
592 """Return diff options tweaked for this mq use, possibly upgrading to
593 git format, and possibly plain and without lossy options."""
594 diffopts = patchmod.difffeatureopts(
595 self.ui,
596 opts,
597 git=True,
598 whitespace=not plain,
599 formatchanging=not plain,
600 )
601 if self.gitmode == b'auto':
602 diffopts.upgrade = True
603 elif self.gitmode == b'keep':
604 pass
605 elif self.gitmode in (b'yes', b'no'):
606 diffopts.git = self.gitmode == b'yes'
607 else:
608 raise error.Abort(
609 _(b'mq.git option can be auto/keep/yes/no got %s')
610 % self.gitmode
611 )
612 if patchfn:
613 diffopts = self.patchopts(diffopts, patchfn)
614 return diffopts
615
616 def patchopts(self, diffopts, *patches):
617 """Return a copy of input diff options with git set to true if
618 referenced patch is a git patch and should be preserved as such.
619 """
620 diffopts = diffopts.copy()
621 if not diffopts.git and self.gitmode == b'keep':
622 for patchfn in patches:
623 patchf = self.opener(patchfn, b'r')
624 # if the patch was a git patch, refresh it as a git patch
625 diffopts.git = any(
626 line.startswith(b'diff --git') for line in patchf
627 )
628 patchf.close()
629 return diffopts
630
631 def join(self, *p):
632 return os.path.join(self.path, *p)
633
634 def findseries(self, patch):
635 def matchpatch(l):
636 l = l.split(b'#', 1)[0]
637 return l.strip() == patch
638
639 for index, l in enumerate(self.fullseries):
640 if matchpatch(l):
641 return index
642 return None
643
644 guard_re = re.compile(br'\s?#([-+][^-+# \t\r\n\f][^# \t\r\n\f]*)')
645
646 def parseseries(self):
647 self.series = []
648 self.seriesguards = []
649 for l in self.fullseries:
650 h = l.find(b'#')
651 if h == -1:
652 patch = l
653 comment = b''
654 elif h == 0:
655 continue
656 else:
657 patch = l[:h]
658 comment = l[h:]
659 patch = patch.strip()
660 if patch:
661 if patch in self.series:
662 raise error.Abort(
663 _(b'%s appears more than once in %s')
664 % (patch, self.join(self.seriespath))
665 )
666 self.series.append(patch)
667 self.seriesguards.append(self.guard_re.findall(comment))
668
669 def checkguard(self, guard):
670 if not guard:
671 return _(b'guard cannot be an empty string')
672 bad_chars = b'# \t\r\n\f'
673 first = guard[0]
674 if first in b'-+':
675 return _(b'guard %r starts with invalid character: %r') % (
676 guard,
677 first,
678 )
679 for c in bad_chars:
680 if c in guard:
681 return _(b'invalid character in guard %r: %r') % (guard, c)
682
683 def setactive(self, guards):
684 for guard in guards:
685 bad = self.checkguard(guard)
686 if bad:
687 raise error.Abort(bad)
688 guards = sorted(set(guards))
689 self.ui.debug(b'active guards: %s\n' % b' '.join(guards))
690 self.activeguards = guards
691 self.guardsdirty = True
692
693 def active(self):
694 if self.activeguards is None:
695 self.activeguards = []
696 try:
697 guards = self.opener.read(self.guardspath).split()
698 except FileNotFoundError:
699 guards = []
700 for i, guard in enumerate(guards):
701 bad = self.checkguard(guard)
702 if bad:
703 self.ui.warn(
704 b'%s:%d: %s\n'
705 % (self.join(self.guardspath), i + 1, bad)
706 )
707 else:
708 self.activeguards.append(guard)
709 return self.activeguards
710
711 def setguards(self, idx, guards):
712 for g in guards:
713 if len(g) < 2:
714 raise error.Abort(_(b'guard %r too short') % g)
715 if g[0] not in b'-+':
716 raise error.Abort(_(b'guard %r starts with invalid char') % g)
717 bad = self.checkguard(g[1:])
718 if bad:
719 raise error.Abort(bad)
720 drop = self.guard_re.sub(b'', self.fullseries[idx])
721 self.fullseries[idx] = drop + b''.join([b' #' + g for g in guards])
722 self.parseseries()
723 self.seriesdirty = True
724
725 def pushable(self, idx):
726 if isinstance(idx, bytes):
727 idx = self.series.index(idx)
728 patchguards = self.seriesguards[idx]
729 if not patchguards:
730 return True, None
731 guards = self.active()
732 exactneg = [
733 g for g in patchguards if g.startswith(b'-') and g[1:] in guards
734 ]
735 if exactneg:
736 return False, stringutil.pprint(exactneg[0])
737 pos = [g for g in patchguards if g.startswith(b'+')]
738 exactpos = [g for g in pos if g[1:] in guards]
739 if pos:
740 if exactpos:
741 return True, stringutil.pprint(exactpos[0])
742 return False, b' '.join([stringutil.pprint(p) for p in pos])
743 return True, b''
744
745 def explainpushable(self, idx, all_patches=False):
746 if all_patches:
747 write = self.ui.write
748 else:
749 write = self.ui.warn
750
751 if all_patches or self.ui.verbose:
752 if isinstance(idx, bytes):
753 idx = self.series.index(idx)
754 pushable, why = self.pushable(idx)
755 if all_patches and pushable:
756 if why is None:
757 write(
758 _(b'allowing %s - no guards in effect\n')
759 % self.series[idx]
760 )
761 else:
762 if not why:
763 write(
764 _(b'allowing %s - no matching negative guards\n')
765 % self.series[idx]
766 )
767 else:
768 write(
769 _(b'allowing %s - guarded by %s\n')
770 % (self.series[idx], why)
771 )
772 if not pushable:
773 if why:
774 write(
775 _(b'skipping %s - guarded by %s\n')
776 % (self.series[idx], why)
777 )
778 else:
779 write(
780 _(b'skipping %s - no matching guards\n')
781 % self.series[idx]
782 )
783
784 def savedirty(self):
785 def writelist(items, path):
786 fp = self.opener(path, b'wb')
787 for i in items:
788 fp.write(b"%s\n" % i)
789 fp.close()
790
791 if self.applieddirty:
792 writelist(map(bytes, self.applied), self.statuspath)
793 self.applieddirty = False
794 if self.seriesdirty:
795 writelist(self.fullseries, self.seriespath)
796 self.seriesdirty = False
797 if self.guardsdirty:
798 writelist(self.activeguards, self.guardspath)
799 self.guardsdirty = False
800 if self.added:
801 qrepo = self.qrepo()
802 if qrepo:
803 with qrepo.wlock(), qrepo.dirstate.changing_files(qrepo):
804 qrepo[None].add(
805 f for f in self.added if f not in qrepo[None]
806 )
807 self.added = []
808
809 def removeundo(self, repo):
810 undo = repo.sjoin(b'undo')
811 if not os.path.exists(undo):
812 return
813 try:
814 os.unlink(undo)
815 except OSError as inst:
816 self.ui.warn(
817 _(b'error removing undo: %s\n') % stringutil.forcebytestr(inst)
818 )
819
820 def backup(self, repo, files, copy=False):
821 # backup local changes in --force case
822 for f in sorted(files):
823 absf = repo.wjoin(f)
824 if os.path.lexists(absf):
825 absorig = scmutil.backuppath(self.ui, repo, f)
826 self.ui.note(
827 _(b'saving current version of %s as %s\n')
828 % (f, os.path.relpath(absorig))
829 )
830
831 if copy:
832 util.copyfile(absf, absorig)
833 else:
834 util.rename(absf, absorig)
835
836 def printdiff(
837 self,
838 repo,
839 diffopts,
840 node1,
841 node2=None,
842 files=None,
843 fp=None,
844 changes=None,
845 opts=None,
846 ):
847 if opts is None:
848 opts = {}
849 stat = opts.get(b'stat')
850 m = scmutil.match(repo[node1], files, opts)
851 logcmdutil.diffordiffstat(
852 self.ui,
853 repo,
854 diffopts,
855 repo[node1],
856 repo[node2],
857 m,
858 changes,
859 stat,
860 fp,
861 )
862
863 def mergeone(self, repo, mergeq, head, patch, rev, diffopts):
864 # first try just applying the patch
865 (err, n) = self.apply(
866 repo, [patch], update_status=False, strict=True, merge=rev
867 )
868
869 if err == 0:
870 return (err, n)
871
872 if n is None:
873 raise error.Abort(_(b"apply failed for patch %s") % patch)
874
875 self.ui.warn(_(b"patch didn't work out, merging %s\n") % patch)
876
877 # apply failed, strip away that rev and merge.
878 up_impl.clean(repo, head)
879 strip(self.ui, repo, [n], update=False, backup=False)
880
881 ctx = repo[rev]
882 ret = up_impl.merge(ctx, remind=False)
883 if ret:
884 raise error.Abort(_(b"update returned %d") % ret)
885 n = newcommit(repo, None, ctx.description(), ctx.user(), force=True)
886 if n is None:
887 raise error.Abort(_(b"repo commit failed"))
888 try:
889 ph = patchheader(mergeq.join(patch), self.plainmode)
890 except Exception:
891 raise error.Abort(_(b"unable to read %s") % patch)
892
893 diffopts = self.patchopts(diffopts, patch)
894 patchf = self.opener(patch, b"w")
895 comments = bytes(ph)
896 if comments:
897 patchf.write(comments)
898 self.printdiff(repo, diffopts, head, n, fp=patchf)
899 patchf.close()
900 self.removeundo(repo)
901 return (0, n)
902
903 def qparents(self, repo, rev=None):
904 """return the mq handled parent or p1
905
906 In some case where mq get himself in being the parent of a merge the
907 appropriate parent may be p2.
908 (eg: an in progress merge started with mq disabled)
909
910 If no parent are managed by mq, p1 is returned.
911 """
912 if rev is None:
913 (p1, p2) = repo.dirstate.parents()
914 if p2 == repo.nullid:
915 return p1
916 if not self.applied:
917 return None
918 return self.applied[-1].node
919 p1, p2 = repo.changelog.parents(rev)
920 if p2 != repo.nullid and p2 in [x.node for x in self.applied]:
921 return p2
922 return p1
923
924 def mergepatch(self, repo, mergeq, series, diffopts):
925 if not self.applied:
926 # each of the patches merged in will have two parents. This
927 # can confuse the qrefresh, qdiff, and strip code because it
928 # needs to know which parent is actually in the patch queue.
929 # so, we insert a merge marker with only one parent. This way
930 # the first patch in the queue is never a merge patch
931 #
932 pname = b".hg.patches.merge.marker"
933 n = newcommit(repo, None, b'[mq]: merge marker', force=True)
934 self.removeundo(repo)
935 self.applied.append(statusentry(n, pname))
936 self.applieddirty = True
937
938 head = self.qparents(repo)
939
940 for patch in series:
941 patch = mergeq.lookup(patch, strict=True)
942 if not patch:
943 self.ui.warn(_(b"patch %s does not exist\n") % patch)
944 return (1, None)
945 pushable, reason = self.pushable(patch)
946 if not pushable:
947 self.explainpushable(patch, all_patches=True)
948 continue
949 info = mergeq.isapplied(patch)
950 if not info:
951 self.ui.warn(_(b"patch %s is not applied\n") % patch)
952 return (1, None)
953 rev = info[1]
954 err, head = self.mergeone(repo, mergeq, head, patch, rev, diffopts)
955 if head:
956 self.applied.append(statusentry(head, patch))
957 self.applieddirty = True
958 if err:
959 return (err, head)
960 self.savedirty()
961 return (0, head)
962
963 def patch(self, repo, patchfile):
964 """Apply patchfile to the working directory.
965 patchfile: name of patch file"""
966 files = set()
967 try:
968 fuzz = patchmod.patch(
969 self.ui, repo, patchfile, strip=1, files=files, eolmode=None
970 )
971 return (True, list(files), fuzz)
972 except Exception as inst:
973 self.ui.note(stringutil.forcebytestr(inst) + b'\n')
974 if not self.ui.verbose:
975 self.ui.warn(_(b"patch failed, unable to continue (try -v)\n"))
976 self.ui.traceback()
977 return (False, list(files), False)
978
979 def apply(
980 self,
981 repo,
982 series,
983 list=False,
984 update_status=True,
985 strict=False,
986 patchdir=None,
987 merge=None,
988 all_files=None,
989 tobackup=None,
990 keepchanges=False,
991 ):
992 wlock = lock = tr = None
993 try:
994 wlock = repo.wlock()
995 lock = repo.lock()
996 tr = repo.transaction(b"qpush")
997 try:
998 ret = self._apply(
999 repo,
1000 series,
1001 list,
1002 update_status,
1003 strict,
1004 patchdir,
1005 merge,
1006 all_files=all_files,
1007 tobackup=tobackup,
1008 keepchanges=keepchanges,
1009 )
1010 tr.close()
1011 self.savedirty()
1012 return ret
1013 except AbortNoCleanup:
1014 tr.close()
1015 self.savedirty()
1016 raise
1017 except: # re-raises
1018 try:
1019 tr.abort()
1020 finally:
1021 self.invalidate()
1022 raise
1023 finally:
1024 release(tr, lock, wlock)
1025 self.removeundo(repo)
1026
1027 def _apply(
1028 self,
1029 repo,
1030 series,
1031 list=False,
1032 update_status=True,
1033 strict=False,
1034 patchdir=None,
1035 merge=None,
1036 all_files=None,
1037 tobackup=None,
1038 keepchanges=False,
1039 ):
1040 """returns (error, hash)
1041
1042 error = 1 for unable to read, 2 for patch failed, 3 for patch
1043 fuzz. tobackup is None or a set of files to backup before they
1044 are modified by a patch.
1045 """
1046 # TODO unify with commands.py
1047 if not patchdir:
1048 patchdir = self.path
1049 err = 0
1050 n = None
1051 for patchname in series:
1052 pushable, reason = self.pushable(patchname)
1053 if not pushable:
1054 self.explainpushable(patchname, all_patches=True)
1055 continue
1056 self.ui.status(_(b"applying %s\n") % patchname)
1057 pf = os.path.join(patchdir, patchname)
1058
1059 try:
1060 ph = patchheader(self.join(patchname), self.plainmode)
1061 except OSError:
1062 self.ui.warn(_(b"unable to read %s\n") % patchname)
1063 err = 1
1064 break
1065
1066 message = ph.message
1067 if not message:
1068 # The commit message should not be translated
1069 message = b"imported patch %s\n" % patchname
1070 else:
1071 if list:
1072 # The commit message should not be translated
1073 message.append(b"\nimported patch %s" % patchname)
1074 message = b'\n'.join(message)
1075
1076 if ph.haspatch:
1077 if tobackup:
1078 touched = patchmod.changedfiles(self.ui, repo, pf)
1079 touched = set(touched) & tobackup
1080 if touched and keepchanges:
1081 raise AbortNoCleanup(
1082 _(b"conflicting local changes found"),
1083 hint=_(b"did you forget to qrefresh?"),
1084 )
1085 self.backup(repo, touched, copy=True)
1086 tobackup = tobackup - touched
1087 (patcherr, files, fuzz) = self.patch(repo, pf)
1088 if all_files is not None:
1089 all_files.update(files)
1090 patcherr = not patcherr
1091 else:
1092 self.ui.warn(_(b"patch %s is empty\n") % patchname)
1093 patcherr, files, fuzz = 0, [], 0
1094
1095 if merge and files:
1096 # Mark as removed/merged and update dirstate parent info
1097 with repo.dirstate.changing_parents(repo):
1098 for f in files:
1099 repo.dirstate.update_file_p1(f, p1_tracked=True)
1100 p1 = repo.dirstate.p1()
1101 repo.setparents(p1, merge)
1102
1103 if all_files and b'.hgsubstate' in all_files:
1104 wctx = repo[None]
1105 pctx = repo[b'.']
1106 overwrite = False
1107 mergedsubstate = subrepoutil.submerge(
1108 repo, pctx, wctx, wctx, overwrite
1109 )
1110 files += mergedsubstate.keys()
1111
1112 match = scmutil.matchfiles(repo, files or [])
1113 oldtip = repo.changelog.tip()
1114 n = newcommit(
1115 repo, None, message, ph.user, ph.date, match=match, force=True
1116 )
1117 if repo.changelog.tip() == oldtip:
1118 raise error.Abort(
1119 _(b"qpush exactly duplicates child changeset")
1120 )
1121 if n is None:
1122 raise error.Abort(_(b"repository commit failed"))
1123
1124 if update_status:
1125 self.applied.append(statusentry(n, patchname))
1126
1127 if patcherr:
1128 self.ui.warn(
1129 _(b"patch failed, rejects left in working directory\n")
1130 )
1131 err = 2
1132 break
1133
1134 if fuzz and strict:
1135 self.ui.warn(_(b"fuzz found when applying patch, stopping\n"))
1136 err = 3
1137 break
1138 return (err, n)
1139
1140 def _cleanup(self, patches, numrevs, keep=False):
1141 if not keep:
1142 r = self.qrepo()
1143 if r:
1144 with r.wlock(), r.dirstate.changing_files(r):
1145 r[None].forget(patches)
1146 for p in patches:
1147 try:
1148 os.unlink(self.join(p))
1149 except FileNotFoundError:
1150 pass
1151
1152 qfinished = []
1153 if numrevs:
1154 qfinished = self.applied[:numrevs]
1155 del self.applied[:numrevs]
1156 self.applieddirty = True
1157
1158 unknown = []
1159
1160 sortedseries = []
1161 for p in patches:
1162 idx = self.findseries(p)
1163 if idx is None:
1164 sortedseries.append((-1, p))
1165 else:
1166 sortedseries.append((idx, p))
1167
1168 sortedseries.sort(reverse=True)
1169 for i, p in sortedseries:
1170 if i != -1:
1171 del self.fullseries[i]
1172 else:
1173 unknown.append(p)
1174
1175 if unknown:
1176 if numrevs:
1177 rev = {entry.name: entry.node for entry in qfinished}
1178 for p in unknown:
1179 msg = _(b'revision %s refers to unknown patches: %s\n')
1180 self.ui.warn(msg % (short(rev[p]), p))
1181 else:
1182 msg = _(b'unknown patches: %s\n')
1183 raise error.Abort(b''.join(msg % p for p in unknown))
1184
1185 self.parseseries()
1186 self.seriesdirty = True
1187 return [entry.node for entry in qfinished]
1188
1189 def _revpatches(self, repo, revs):
1190 firstrev = repo[self.applied[0].node].rev()
1191 patches = []
1192 for i, rev in enumerate(revs):
1193 if rev < firstrev:
1194 raise error.Abort(_(b'revision %d is not managed') % rev)
1195
1196 ctx = repo[rev]
1197 base = self.applied[i].node
1198 if ctx.node() != base:
1199 msg = _(b'cannot delete revision %d above applied patches')
1200 raise error.Abort(msg % rev)
1201
1202 patch = self.applied[i].name
1203 for fmt in (b'[mq]: %s', b'imported patch %s'):
1204 if ctx.description() == fmt % patch:
1205 msg = _(b'patch %s finalized without changeset message\n')
1206 repo.ui.status(msg % patch)
1207 break
1208
1209 patches.append(patch)
1210 return patches
1211
1212 def finish(self, repo, revs):
1213 # Manually trigger phase computation to ensure phasedefaults is
1214 # executed before we remove the patches.
1215 repo._phasecache
1216 patches = self._revpatches(repo, sorted(revs))
1217 qfinished = self._cleanup(patches, len(patches))
1218 if qfinished and repo.ui.configbool(b'mq', b'secret'):
1219 # only use this logic when the secret option is added
1220 oldqbase = repo[qfinished[0]]
1221 tphase = phases.newcommitphase(repo.ui)
1222 if oldqbase.phase() > tphase and oldqbase.p1().phase() <= tphase:
1223 with repo.transaction(b'qfinish') as tr:
1224 phases.advanceboundary(repo, tr, tphase, qfinished)
1225
1226 def delete(self, repo, patches, opts):
1227 if not patches and not opts.get(b'rev'):
1228 raise error.Abort(
1229 _(b'qdelete requires at least one revision or patch name')
1230 )
1231
1232 realpatches = []
1233 for patch in patches:
1234 patch = self.lookup(patch, strict=True)
1235 info = self.isapplied(patch)
1236 if info:
1237 raise error.Abort(_(b"cannot delete applied patch %s") % patch)
1238 if patch not in self.series:
1239 raise error.Abort(_(b"patch %s not in series file") % patch)
1240 if patch not in realpatches:
1241 realpatches.append(patch)
1242
1243 numrevs = 0
1244 if opts.get(b'rev'):
1245 if not self.applied:
1246 raise error.Abort(_(b'no patches applied'))
1247 revs = logcmdutil.revrange(repo, opts.get(b'rev'))
1248 revs.sort()
1249 revpatches = self._revpatches(repo, revs)
1250 realpatches += revpatches
1251 numrevs = len(revpatches)
1252
1253 self._cleanup(realpatches, numrevs, opts.get(b'keep'))
1254
1255 def checktoppatch(self, repo):
1256 '''check that working directory is at qtip'''
1257 if self.applied:
1258 top = self.applied[-1].node
1259 patch = self.applied[-1].name
1260 if repo.dirstate.p1() != top:
1261 raise error.Abort(_(b"working directory revision is not qtip"))
1262 return top, patch
1263 return None, None
1264
1265 def putsubstate2changes(self, substatestate, changes):
1266 if isinstance(changes, list):
1267 mar = changes[:3]
1268 else:
1269 mar = (changes.modified, changes.added, changes.removed)
1270 if any(b'.hgsubstate' in files for files in mar):
1271 return # already listed up
1272 # not yet listed up
1273 if substatestate.added or not substatestate.any_tracked:
1274 mar[1].append(b'.hgsubstate')
1275 elif substatestate.removed:
1276 mar[2].append(b'.hgsubstate')
1277 else: # modified
1278 mar[0].append(b'.hgsubstate')
1279
1280 def checklocalchanges(self, repo, force=False, refresh=True):
1281 excsuffix = b''
1282 if refresh:
1283 excsuffix = b', qrefresh first'
1284 # plain versions for i18n tool to detect them
1285 _(b"local changes found, qrefresh first")
1286 _(b"local changed subrepos found, qrefresh first")
1287
1288 s = repo.status()
1289 if not force:
1290 cmdutil.checkunfinished(repo)
1291 if s.modified or s.added or s.removed or s.deleted:
1292 _(b"local changes found") # i18n tool detection
1293 raise error.Abort(_(b"local changes found" + excsuffix))
1294 if checksubstate(repo):
1295 _(b"local changed subrepos found") # i18n tool detection
1296 raise error.Abort(
1297 _(b"local changed subrepos found" + excsuffix)
1298 )
1299 else:
1300 cmdutil.checkunfinished(repo, skipmerge=True)
1301 return s
1302
1303 _reserved = (b'series', b'status', b'guards', b'.', b'..')
1304
1305 def checkreservedname(self, name):
1306 if name in self._reserved:
1307 raise error.Abort(
1308 _(b'"%s" cannot be used as the name of a patch') % name
1309 )
1310 if name != name.strip():
1311 # whitespace is stripped by parseseries()
1312 raise error.Abort(
1313 _(b'patch name cannot begin or end with whitespace')
1314 )
1315 for prefix in (b'.hg', b'.mq'):
1316 if name.startswith(prefix):
1317 raise error.Abort(
1318 _(b'patch name cannot begin with "%s"') % prefix
1319 )
1320 for c in (b'#', b':', b'\r', b'\n'):
1321 if c in name:
1322 raise error.Abort(
1323 _(b'%r cannot be used in the name of a patch')
1324 % pycompat.bytestr(c)
1325 )
1326
1327 def checkpatchname(self, name, force=False):
1328 self.checkreservedname(name)
1329 if not force and os.path.exists(self.join(name)):
1330 if os.path.isdir(self.join(name)):
1331 raise error.Abort(
1332 _(b'"%s" already exists as a directory') % name
1333 )
1334 else:
1335 raise error.Abort(_(b'patch "%s" already exists') % name)
1336
1337 def makepatchname(self, title, fallbackname):
1338 """Return a suitable filename for title, adding a suffix to make
1339 it unique in the existing list"""
1340 namebase = re.sub(br'[\s\W_]+', b'_', title.lower()).strip(b'_')
1341 namebase = namebase[:75] # avoid too long name (issue5117)
1342 if namebase:
1343 try:
1344 self.checkreservedname(namebase)
1345 except error.Abort:
1346 namebase = fallbackname
1347 else:
1348 namebase = fallbackname
1349 name = namebase
1350 i = 0
1351 while True:
1352 if name not in self.fullseries:
1353 try:
1354 self.checkpatchname(name)
1355 break
1356 except error.Abort:
1357 pass
1358 i += 1
1359 name = b'%s__%d' % (namebase, i)
1360 return name
1361
1362 def checkkeepchanges(self, keepchanges, force):
1363 if force and keepchanges:
1364 raise error.Abort(_(b'cannot use both --force and --keep-changes'))
1365
1366 def new(self, repo, patchfn, *pats, **opts):
1367 """options:
1368 msg: a string or a no-argument function returning a string
1369 """
1370 opts = pycompat.byteskwargs(opts)
1371 msg = opts.get(b'msg')
1372 edit = opts.get(b'edit')
1373 editform = opts.get(b'editform', b'mq.qnew')
1374 user = opts.get(b'user')
1375 date = opts.get(b'date')
1376 if date:
1377 date = dateutil.parsedate(date)
1378 diffopts = self.diffopts({b'git': opts.get(b'git')}, plain=True)
1379 if opts.get(b'checkname', True):
1380 self.checkpatchname(patchfn)
1381 inclsubs = checksubstate(repo)
1382 if inclsubs:
1383 substatestate = repo.dirstate.get_entry(b'.hgsubstate')
1384 if opts.get(b'include') or opts.get(b'exclude') or pats:
1385 # detect missing files in pats
1386 def badfn(f, msg):
1387 if f != b'.hgsubstate': # .hgsubstate is auto-created
1388 raise error.Abort(b'%s: %s' % (f, msg))
1389
1390 match = scmutil.match(repo[None], pats, opts, badfn=badfn)
1391 changes = repo.status(match=match)
1392 else:
1393 changes = self.checklocalchanges(repo, force=True)
1394 commitfiles = list(inclsubs)
1395 commitfiles.extend(changes.modified)
1396 commitfiles.extend(changes.added)
1397 commitfiles.extend(changes.removed)
1398 match = scmutil.matchfiles(repo, commitfiles)
1399 if len(repo[None].parents()) > 1:
1400 raise error.Abort(_(b'cannot manage merge changesets'))
1401 self.checktoppatch(repo)
1402 insert = self.fullseriesend()
1403 with repo.wlock():
1404 try:
1405 # if patch file write fails, abort early
1406 p = self.opener(patchfn, b"w")
1407 except OSError as e:
1408 raise error.Abort(
1409 _(b'cannot write patch "%s": %s')
1410 % (patchfn, encoding.strtolocal(e.strerror))
1411 )
1412 try:
1413 defaultmsg = b"[mq]: %s" % patchfn
1414 editor = cmdutil.getcommiteditor(editform=editform)
1415 if edit:
1416
1417 def finishdesc(desc):
1418 if desc.rstrip():
1419 return desc
1420 else:
1421 return defaultmsg
1422
1423 # i18n: this message is shown in editor with "HG: " prefix
1424 extramsg = _(b'Leave message empty to use default message.')
1425 editor = cmdutil.getcommiteditor(
1426 finishdesc=finishdesc,
1427 extramsg=extramsg,
1428 editform=editform,
1429 )
1430 commitmsg = msg
1431 else:
1432 commitmsg = msg or defaultmsg
1433
1434 n = newcommit(
1435 repo,
1436 None,
1437 commitmsg,
1438 user,
1439 date,
1440 match=match,
1441 force=True,
1442 editor=editor,
1443 )
1444 if n is None:
1445 raise error.Abort(_(b"repo commit failed"))
1446 try:
1447 self.fullseries[insert:insert] = [patchfn]
1448 self.applied.append(statusentry(n, patchfn))
1449 self.parseseries()
1450 self.seriesdirty = True
1451 self.applieddirty = True
1452 nctx = repo[n]
1453 ph = patchheader(self.join(patchfn), self.plainmode)
1454 if user:
1455 ph.setuser(user)
1456 if date:
1457 ph.setdate(b'%d %d' % date)
1458 ph.setparent(hex(nctx.p1().node()))
1459 msg = nctx.description().strip()
1460 if msg == defaultmsg.strip():
1461 msg = b''
1462 ph.setmessage(msg)
1463 p.write(bytes(ph))
1464 if commitfiles:
1465 parent = self.qparents(repo, n)
1466 if inclsubs:
1467 self.putsubstate2changes(substatestate, changes)
1468 chunks = patchmod.diff(
1469 repo,
1470 node1=parent,
1471 node2=n,
1472 changes=changes,
1473 opts=diffopts,
1474 )
1475 for chunk in chunks:
1476 p.write(chunk)
1477 p.close()
1478 r = self.qrepo()
1479 if r:
1480 with r.wlock(), r.dirstate.changing_files(r):
1481 r[None].add([patchfn])
1482 except: # re-raises
1483 repo.rollback()
1484 raise
1485 except Exception:
1486 patchpath = self.join(patchfn)
1487 try:
1488 os.unlink(patchpath)
1489 except OSError:
1490 self.ui.warn(_(b'error unlinking %s\n') % patchpath)
1491 raise
1492 self.removeundo(repo)
1493
1494 def isapplied(self, patch):
1495 """returns (index, rev, patch)"""
1496 for i, a in enumerate(self.applied):
1497 if a.name == patch:
1498 return (i, a.node, a.name)
1499 return None
1500
1501 # if the exact patch name does not exist, we try a few
1502 # variations. If strict is passed, we try only #1
1503 #
1504 # 1) a number (as string) to indicate an offset in the series file
1505 # 2) a unique substring of the patch name was given
1506 # 3) patchname[-+]num to indicate an offset in the series file
1507 def lookup(self, patch, strict=False):
1508 def partialname(s):
1509 if s in self.series:
1510 return s
1511 matches = [x for x in self.series if s in x]
1512 if len(matches) > 1:
1513 self.ui.warn(_(b'patch name "%s" is ambiguous:\n') % s)
1514 for m in matches:
1515 self.ui.warn(b' %s\n' % m)
1516 return None
1517 if matches:
1518 return matches[0]
1519 if self.series and self.applied:
1520 if s == b'qtip':
1521 return self.series[self.seriesend(True) - 1]
1522 if s == b'qbase':
1523 return self.series[0]
1524 return None
1525
1526 if patch in self.series:
1527 return patch
1528
1529 if not os.path.isfile(self.join(patch)):
1530 try:
1531 sno = int(patch)
1532 except (ValueError, OverflowError):
1533 pass
1534 else:
1535 if -len(self.series) <= sno < len(self.series):
1536 return self.series[sno]
1537
1538 if not strict:
1539 res = partialname(patch)
1540 if res:
1541 return res
1542 minus = patch.rfind(b'-')
1543 if minus >= 0:
1544 res = partialname(patch[:minus])
1545 if res:
1546 i = self.series.index(res)
1547 try:
1548 off = int(patch[minus + 1 :] or 1)
1549 except (ValueError, OverflowError):
1550 pass
1551 else:
1552 if i - off >= 0:
1553 return self.series[i - off]
1554 plus = patch.rfind(b'+')
1555 if plus >= 0:
1556 res = partialname(patch[:plus])
1557 if res:
1558 i = self.series.index(res)
1559 try:
1560 off = int(patch[plus + 1 :] or 1)
1561 except (ValueError, OverflowError):
1562 pass
1563 else:
1564 if i + off < len(self.series):
1565 return self.series[i + off]
1566 raise error.Abort(_(b"patch %s not in series") % patch)
1567
1568 def push(
1569 self,
1570 repo,
1571 patch=None,
1572 force=False,
1573 list=False,
1574 mergeq=None,
1575 all=False,
1576 move=False,
1577 exact=False,
1578 nobackup=False,
1579 keepchanges=False,
1580 ):
1581 self.checkkeepchanges(keepchanges, force)
1582 diffopts = self.diffopts()
1583 with repo.wlock():
1584 p1 = repo.dirstate.p1()
1585 if not (repo.branchmap().all_nodes_are_heads([p1]) or exact):
1586 self.ui.status(_(b"(working directory not at a head)\n"))
1587
1588 if not self.series:
1589 self.ui.warn(_(b'no patches in series\n'))
1590 return 0
1591
1592 # Suppose our series file is: A B C and the current 'top'
1593 # patch is B. qpush C should be performed (moving forward)
1594 # qpush B is a NOP (no change) qpush A is an error (can't
1595 # go backwards with qpush)
1596 if patch:
1597 patch = self.lookup(patch)
1598 info = self.isapplied(patch)
1599 if info and info[0] >= len(self.applied) - 1:
1600 self.ui.warn(
1601 _(b'qpush: %s is already at the top\n') % patch
1602 )
1603 return 0
1604
1605 pushable, reason = self.pushable(patch)
1606 if pushable:
1607 if self.series.index(patch) < self.seriesend():
1608 raise error.Abort(
1609 _(b"cannot push to a previous patch: %s") % patch
1610 )
1611 else:
1612 if reason:
1613 reason = _(b'guarded by %s') % reason
1614 else:
1615 reason = _(b'no matching guards')
1616 self.ui.warn(
1617 _(b"cannot push '%s' - %s\n") % (patch, reason)
1618 )
1619 return 1
1620 elif all:
1621 patch = self.series[-1]
1622 if self.isapplied(patch):
1623 self.ui.warn(_(b'all patches are currently applied\n'))
1624 return 0
1625
1626 # Following the above example, starting at 'top' of B:
1627 # qpush should be performed (pushes C), but a subsequent
1628 # qpush without an argument is an error (nothing to
1629 # apply). This allows a loop of "...while hg qpush..." to
1630 # work as it detects an error when done
1631 start = self.seriesend()
1632 if start == len(self.series):
1633 self.ui.warn(_(b'patch series already fully applied\n'))
1634 return 1
1635 if not force and not keepchanges:
1636 self.checklocalchanges(repo, refresh=self.applied)
1637
1638 if exact:
1639 if keepchanges:
1640 raise error.Abort(
1641 _(b"cannot use --exact and --keep-changes together")
1642 )
1643 if move:
1644 raise error.Abort(
1645 _(b'cannot use --exact and --move together')
1646 )
1647 if self.applied:
1648 raise error.Abort(
1649 _(b'cannot push --exact with applied patches')
1650 )
1651 root = self.series[start]
1652 target = patchheader(self.join(root), self.plainmode).parent
1653 if not target:
1654 raise error.Abort(
1655 _(b"%s does not have a parent recorded") % root
1656 )
1657 if not repo[target] == repo[b'.']:
1658 up_impl.update(repo, target)
1659
1660 if move:
1661 if not patch:
1662 raise error.Abort(_(b"please specify the patch to move"))
1663 for fullstart, rpn in enumerate(self.fullseries):
1664 # strip markers for patch guards
1665 if self.guard_re.split(rpn, 1)[0] == self.series[start]:
1666 break
1667 for i, rpn in enumerate(self.fullseries[fullstart:]):
1668 # strip markers for patch guards
1669 if self.guard_re.split(rpn, 1)[0] == patch:
1670 break
1671 index = fullstart + i
1672 assert index < len(self.fullseries)
1673 fullpatch = self.fullseries[index]
1674 del self.fullseries[index]
1675 self.fullseries.insert(fullstart, fullpatch)
1676 self.parseseries()
1677 self.seriesdirty = True
1678
1679 self.applieddirty = True
1680 if start > 0:
1681 self.checktoppatch(repo)
1682 if not patch:
1683 patch = self.series[start]
1684 end = start + 1
1685 else:
1686 end = self.series.index(patch, start) + 1
1687
1688 tobackup = set()
1689 if (not nobackup and force) or keepchanges:
1690 status = self.checklocalchanges(repo, force=True)
1691 if keepchanges:
1692 tobackup.update(
1693 status.modified
1694 + status.added
1695 + status.removed
1696 + status.deleted
1697 )
1698 else:
1699 tobackup.update(status.modified + status.added)
1700
1701 s = self.series[start:end]
1702 all_files = set()
1703 try:
1704 if mergeq:
1705 ret = self.mergepatch(repo, mergeq, s, diffopts)
1706 else:
1707 ret = self.apply(
1708 repo,
1709 s,
1710 list,
1711 all_files=all_files,
1712 tobackup=tobackup,
1713 keepchanges=keepchanges,
1714 )
1715 except AbortNoCleanup:
1716 raise
1717 except: # re-raises
1718 self.ui.warn(_(b'cleaning up working directory...\n'))
1719 cmdutil.revert(
1720 self.ui,
1721 repo,
1722 repo[b'.'],
1723 no_backup=True,
1724 )
1725 # only remove unknown files that we know we touched or
1726 # created while patching
1727 for f in all_files:
1728 if f not in repo.dirstate:
1729 repo.wvfs.unlinkpath(f, ignoremissing=True)
1730 self.ui.warn(_(b'done\n'))
1731 raise
1732
1733 if not self.applied:
1734 return ret[0]
1735 top = self.applied[-1].name
1736 if ret[0] and ret[0] > 1:
1737 msg = _(b"errors during apply, please fix and qrefresh %s\n")
1738 self.ui.write(msg % top)
1739 else:
1740 self.ui.write(_(b"now at: %s\n") % top)
1741 return ret[0]
1742
1743 def pop(
1744 self,
1745 repo,
1746 patch=None,
1747 force=False,
1748 update=True,
1749 all=False,
1750 nobackup=False,
1751 keepchanges=False,
1752 ):
1753 self.checkkeepchanges(keepchanges, force)
1754 with repo.wlock():
1755 if patch:
1756 # index, rev, patch
1757 info = self.isapplied(patch)
1758 if not info:
1759 patch = self.lookup(patch)
1760 info = self.isapplied(patch)
1761 if not info:
1762 raise error.Abort(_(b"patch %s is not applied") % patch)
1763
1764 if not self.applied:
1765 # Allow qpop -a to work repeatedly,
1766 # but not qpop without an argument
1767 self.ui.warn(_(b"no patches applied\n"))
1768 return not all
1769
1770 if all:
1771 start = 0
1772 elif patch:
1773 start = info[0] + 1
1774 else:
1775 start = len(self.applied) - 1
1776
1777 if start >= len(self.applied):
1778 self.ui.warn(_(b"qpop: %s is already at the top\n") % patch)
1779 return
1780
1781 if not update:
1782 parents = repo.dirstate.parents()
1783 rr = [x.node for x in self.applied]
1784 for p in parents:
1785 if p in rr:
1786 self.ui.warn(_(b"qpop: forcing dirstate update\n"))
1787 update = True
1788 else:
1789 parents = [p.node() for p in repo[None].parents()]
1790 update = any(
1791 entry.node in parents for entry in self.applied[start:]
1792 )
1793
1794 tobackup = set()
1795 if update:
1796 s = self.checklocalchanges(repo, force=force or keepchanges)
1797 if force:
1798 if not nobackup:
1799 tobackup.update(s.modified + s.added)
1800 elif keepchanges:
1801 tobackup.update(
1802 s.modified + s.added + s.removed + s.deleted
1803 )
1804
1805 self.applieddirty = True
1806 end = len(self.applied)
1807 rev = self.applied[start].node
1808
1809 try:
1810 heads = repo.changelog.heads(rev)
1811 except error.LookupError:
1812 node = short(rev)
1813 raise error.Abort(_(b'trying to pop unknown node %s') % node)
1814
1815 if heads != [self.applied[-1].node]:
1816 raise error.Abort(
1817 _(
1818 b"popping would remove a revision not "
1819 b"managed by this patch queue"
1820 )
1821 )
1822 if not repo[self.applied[-1].node].mutable():
1823 raise error.Abort(
1824 _(b"popping would remove a public revision"),
1825 hint=_(b"see 'hg help phases' for details"),
1826 )
1827
1828 # we know there are no local changes, so we can make a simplified
1829 # form of up_impl.update.
1830 if update:
1831 qp = self.qparents(repo, rev)
1832 ctx = repo[qp]
1833 st = repo.status(qp, b'.')
1834 m, a, r, d = st.modified, st.added, st.removed, st.deleted
1835 if d:
1836 raise error.Abort(_(b"deletions found between repo revs"))
1837
1838 tobackup = set(a + m + r) & tobackup
1839 if keepchanges and tobackup:
1840 raise error.Abort(_(b"local changes found, qrefresh first"))
1841 self.backup(repo, tobackup)
1842 with repo.dirstate.changing_parents(repo):
1843 for f in a:
1844 repo.wvfs.unlinkpath(f, ignoremissing=True)
1845 repo.dirstate.update_file(
1846 f, p1_tracked=False, wc_tracked=False
1847 )
1848 for f in m + r:
1849 fctx = ctx[f]
1850 repo.wwrite(f, fctx.data(), fctx.flags())
1851 repo.dirstate.update_file(
1852 f, p1_tracked=True, wc_tracked=True
1853 )
1854 repo.setparents(qp, repo.nullid)
1855 for patch in reversed(self.applied[start:end]):
1856 self.ui.status(_(b"popping %s\n") % patch.name)
1857 del self.applied[start:end]
1858 strip(self.ui, repo, [rev], update=False, backup=False)
1859 for s, state in repo[b'.'].substate.items():
1860 repo[b'.'].sub(s).get(state)
1861 if self.applied:
1862 self.ui.write(_(b"now at: %s\n") % self.applied[-1].name)
1863 else:
1864 self.ui.write(_(b"patch queue now empty\n"))
1865
1866 def diff(self, repo, pats, opts):
1867 top, patch = self.checktoppatch(repo)
1868 if not top:
1869 self.ui.write(_(b"no patches applied\n"))
1870 return
1871 qp = self.qparents(repo, top)
1872 if opts.get(b'reverse'):
1873 node1, node2 = None, qp
1874 else:
1875 node1, node2 = qp, None
1876 diffopts = self.diffopts(opts, patch)
1877 self.printdiff(repo, diffopts, node1, node2, files=pats, opts=opts)
1878
1879 def refresh(self, repo, pats=None, **opts):
1880 opts = pycompat.byteskwargs(opts)
1881 if not self.applied:
1882 self.ui.write(_(b"no patches applied\n"))
1883 return 1
1884 msg = opts.get(b'msg', b'').rstrip()
1885 edit = opts.get(b'edit')
1886 editform = opts.get(b'editform', b'mq.qrefresh')
1887 newuser = opts.get(b'user')
1888 newdate = opts.get(b'date')
1889 if newdate:
1890 newdate = b'%d %d' % dateutil.parsedate(newdate)
1891 wlock = repo.wlock()
1892
1893 try:
1894 self.checktoppatch(repo)
1895 (top, patchfn) = (self.applied[-1].node, self.applied[-1].name)
1896 if repo.changelog.heads(top) != [top]:
1897 raise error.Abort(
1898 _(b"cannot qrefresh a revision with children")
1899 )
1900 if not repo[top].mutable():
1901 raise error.Abort(
1902 _(b"cannot qrefresh public revision"),
1903 hint=_(b"see 'hg help phases' for details"),
1904 )
1905
1906 cparents = repo.changelog.parents(top)
1907 patchparent = self.qparents(repo, top)
1908
1909 inclsubs = checksubstate(repo, patchparent)
1910 if inclsubs:
1911 substatestate = repo.dirstate.get_entry(b'.hgsubstate')
1912
1913 ph = patchheader(self.join(patchfn), self.plainmode)
1914 diffopts = self.diffopts(
1915 {b'git': opts.get(b'git')}, patchfn, plain=True
1916 )
1917 if newuser:
1918 ph.setuser(newuser)
1919 if newdate:
1920 ph.setdate(newdate)
1921 ph.setparent(hex(patchparent))
1922
1923 # only commit new patch when write is complete
1924 patchf = self.opener(patchfn, b'w', atomictemp=True)
1925
1926 # update the dirstate in place, strip off the qtip commit
1927 # and then commit.
1928 #
1929 # this should really read:
1930 # st = repo.status(top, patchparent)
1931 # but we do it backwards to take advantage of manifest/changelog
1932 # caching against the next repo.status call
1933 st = repo.status(patchparent, top)
1934 mm, aa, dd = st.modified, st.added, st.removed
1935 ctx = repo[top]
1936 aaa = aa[:]
1937 match1 = scmutil.match(repo[None], pats, opts)
1938 # in short mode, we only diff the files included in the
1939 # patch already plus specified files
1940 if opts.get(b'short'):
1941 # if amending a patch, we start with existing
1942 # files plus specified files - unfiltered
1943 match = scmutil.matchfiles(repo, mm + aa + dd + match1.files())
1944 # filter with include/exclude options
1945 match1 = scmutil.match(repo[None], opts=opts)
1946 else:
1947 match = scmutil.matchall(repo)
1948 stb = repo.status(match=match)
1949 m, a, r, d = stb.modified, stb.added, stb.removed, stb.deleted
1950 mm = set(mm)
1951 aa = set(aa)
1952 dd = set(dd)
1953
1954 # we might end up with files that were added between
1955 # qtip and the dirstate parent, but then changed in the
1956 # local dirstate. in this case, we want them to only
1957 # show up in the added section
1958 for x in m:
1959 if x not in aa:
1960 mm.add(x)
1961 # we might end up with files added by the local dirstate that
1962 # were deleted by the patch. In this case, they should only
1963 # show up in the changed section.
1964 for x in a:
1965 if x in dd:
1966 dd.remove(x)
1967 mm.add(x)
1968 else:
1969 aa.add(x)
1970 # make sure any files deleted in the local dirstate
1971 # are not in the add or change column of the patch
1972 forget = []
1973 for x in d + r:
1974 if x in aa:
1975 aa.remove(x)
1976 forget.append(x)
1977 continue
1978 else:
1979 mm.discard(x)
1980 dd.add(x)
1981
1982 m = list(mm)
1983 r = list(dd)
1984 a = list(aa)
1985
1986 # create 'match' that includes the files to be recommitted.
1987 # apply match1 via repo.status to ensure correct case handling.
1988 st = repo.status(patchparent, match=match1)
1989 cm, ca, cr, cd = st.modified, st.added, st.removed, st.deleted
1990 allmatches = set(cm + ca + cr + cd)
1991 refreshchanges = [x.intersection(allmatches) for x in (mm, aa, dd)]
1992
1993 files = set(inclsubs)
1994 for x in refreshchanges:
1995 files.update(x)
1996 match = scmutil.matchfiles(repo, files)
1997
1998 bmlist = repo[top].bookmarks()
1999
2000 with repo.dirstate.changing_parents(repo):
2001 if diffopts.git or diffopts.upgrade:
2002 copies = {}
2003 for dst in a:
2004 src = repo.dirstate.copied(dst)
2005 # during qfold, the source file for copies may
2006 # be removed. Treat this as a simple add.
2007 if src is not None and src in repo.dirstate:
2008 copies.setdefault(src, []).append(dst)
2009 repo.dirstate.update_file(
2010 dst, p1_tracked=False, wc_tracked=True
2011 )
2012 # remember the copies between patchparent and qtip
2013 for dst in aaa:
2014 src = ctx[dst].copysource()
2015 if src:
2016 copies.setdefault(src, []).extend(
2017 copies.get(dst, [])
2018 )
2019 if dst in a:
2020 copies[src].append(dst)
2021 # we can't copy a file created by the patch itself
2022 if dst in copies:
2023 del copies[dst]
2024 for src, dsts in copies.items():
2025 for dst in dsts:
2026 repo.dirstate.copy(src, dst)
2027 else:
2028 for dst in a:
2029 repo.dirstate.update_file(
2030 dst, p1_tracked=False, wc_tracked=True
2031 )
2032 # Drop useless copy information
2033 for f in list(repo.dirstate.copies()):
2034 repo.dirstate.copy(None, f)
2035 for f in r:
2036 repo.dirstate.update_file_p1(f, p1_tracked=True)
2037 # if the patch excludes a modified file, mark that
2038 # file with mtime=0 so status can see it.
2039 mm = []
2040 for i in range(len(m) - 1, -1, -1):
2041 if not match1(m[i]):
2042 mm.append(m[i])
2043 del m[i]
2044 for f in m:
2045 repo.dirstate.update_file_p1(f, p1_tracked=True)
2046 for f in mm:
2047 repo.dirstate.update_file_p1(f, p1_tracked=True)
2048 for f in forget:
2049 repo.dirstate.update_file_p1(f, p1_tracked=False)
2050
2051 user = ph.user or ctx.user()
2052
2053 oldphase = repo[top].phase()
2054
2055 # assumes strip can roll itself back if interrupted
2056 repo.setparents(*cparents)
2057 repo.dirstate.write(repo.currenttransaction())
2058 self.applied.pop()
2059 self.applieddirty = True
2060 strip(self.ui, repo, [top], update=False, backup=False)
2061
2062 try:
2063 # might be nice to attempt to roll back strip after this
2064
2065 defaultmsg = b"[mq]: %s" % patchfn
2066 editor = cmdutil.getcommiteditor(editform=editform)
2067 if edit:
2068
2069 def finishdesc(desc):
2070 if desc.rstrip():
2071 ph.setmessage(desc)
2072 return desc
2073 return defaultmsg
2074
2075 # i18n: this message is shown in editor with "HG: " prefix
2076 extramsg = _(b'Leave message empty to use default message.')
2077 editor = cmdutil.getcommiteditor(
2078 finishdesc=finishdesc,
2079 extramsg=extramsg,
2080 editform=editform,
2081 )
2082 message = msg or b"\n".join(ph.message)
2083 elif not msg:
2084 if not ph.message:
2085 message = defaultmsg
2086 else:
2087 message = b"\n".join(ph.message)
2088 else:
2089 message = msg
2090 ph.setmessage(msg)
2091
2092 # Ensure we create a new changeset in the same phase than
2093 # the old one.
2094 lock = tr = None
2095 try:
2096 lock = repo.lock()
2097 tr = repo.transaction(b'mq')
2098 n = newcommit(
2099 repo,
2100 oldphase,
2101 message,
2102 user,
2103 ph.date,
2104 match=match,
2105 force=True,
2106 editor=editor,
2107 )
2108 # only write patch after a successful commit
2109 c = [list(x) for x in refreshchanges]
2110 if inclsubs:
2111 self.putsubstate2changes(substatestate, c)
2112 chunks = patchmod.diff(
2113 repo, patchparent, changes=c, opts=diffopts
2114 )
2115 comments = bytes(ph)
2116 if comments:
2117 patchf.write(comments)
2118 for chunk in chunks:
2119 patchf.write(chunk)
2120 patchf.close()
2121
2122 marks = repo._bookmarks
2123 marks.applychanges(repo, tr, [(bm, n) for bm in bmlist])
2124 tr.close()
2125
2126 self.applied.append(statusentry(n, patchfn))
2127 finally:
2128 lockmod.release(tr, lock)
2129 except: # re-raises
2130 with repo.dirstate.changing_parents(repo):
2131 ctx = repo[cparents[0]]
2132 repo.dirstate.rebuild(ctx.node(), ctx.manifest())
2133 self.savedirty()
2134 self.ui.warn(
2135 _(
2136 b'qrefresh interrupted while patch was popped! '
2137 b'(revert --all, qpush to recover)\n'
2138 )
2139 )
2140 raise
2141 finally:
2142 wlock.release()
2143 self.removeundo(repo)
2144
2145 def init(self, repo, create=False):
2146 if not create and os.path.isdir(self.path):
2147 raise error.Abort(_(b"patch queue directory already exists"))
2148 try:
2149 os.mkdir(self.path)
2150 except FileExistsError:
2151 if not create:
2152 raise
2153 if create:
2154 return self.qrepo(create=True)
2155
2156 def unapplied(self, repo, patch=None):
2157 if patch and patch not in self.series:
2158 raise error.Abort(_(b"patch %s is not in series file") % patch)
2159 if not patch:
2160 start = self.seriesend()
2161 else:
2162 start = self.series.index(patch) + 1
2163 unapplied = []
2164 for i in range(start, len(self.series)):
2165 pushable, reason = self.pushable(i)
2166 if pushable:
2167 unapplied.append((i, self.series[i]))
2168 self.explainpushable(i)
2169 return unapplied
2170
2171 def qseries(
2172 self,
2173 repo,
2174 missing=None,
2175 start=0,
2176 length=None,
2177 status=None,
2178 summary=False,
2179 ):
2180 def displayname(pfx, patchname, state):
2181 if pfx:
2182 self.ui.write(pfx)
2183 if summary:
2184 ph = patchheader(self.join(patchname), self.plainmode)
2185 if ph.message:
2186 msg = ph.message[0]
2187 else:
2188 msg = b''
2189
2190 if self.ui.formatted():
2191 width = self.ui.termwidth() - len(pfx) - len(patchname) - 2
2192 if width > 0:
2193 msg = stringutil.ellipsis(msg, width)
2194 else:
2195 msg = b''
2196 self.ui.write(patchname, label=b'qseries.' + state)
2197 self.ui.write(b': ')
2198 self.ui.write(msg, label=b'qseries.message.' + state)
2199 else:
2200 self.ui.write(patchname, label=b'qseries.' + state)
2201 self.ui.write(b'\n')
2202
2203 applied = {p.name for p in self.applied}
2204 if length is None:
2205 length = len(self.series) - start
2206 if not missing:
2207 if self.ui.verbose:
2208 idxwidth = len(b"%d" % (start + length - 1))
2209 for i in range(start, start + length):
2210 patch = self.series[i]
2211 if patch in applied:
2212 char, state = b'A', b'applied'
2213 elif self.pushable(i)[0]:
2214 char, state = b'U', b'unapplied'
2215 else:
2216 char, state = b'G', b'guarded'
2217 pfx = b''
2218 if self.ui.verbose:
2219 pfx = b'%*d %s ' % (idxwidth, i, char)
2220 elif status and status != char:
2221 continue
2222 displayname(pfx, patch, state)
2223 else:
2224 msng_list = []
2225 for root, dirs, files in os.walk(self.path):
2226 d = root[len(self.path) + 1 :]
2227 for f in files:
2228 fl = os.path.join(d, f)
2229 if (
2230 fl not in self.series
2231 and fl
2232 not in (
2233 self.statuspath,
2234 self.seriespath,
2235 self.guardspath,
2236 )
2237 and not fl.startswith(b'.')
2238 ):
2239 msng_list.append(fl)
2240 for x in sorted(msng_list):
2241 pfx = self.ui.verbose and b'D ' or b''
2242 displayname(pfx, x, b'missing')
2243
2244 def issaveline(self, l):
2245 if l.name == b'.hg.patches.save.line':
2246 return True
2247
2248 def qrepo(self, create=False):
2249 ui = self.baseui.copy()
2250 # copy back attributes set by ui.pager()
2251 if self.ui.pageractive and not ui.pageractive:
2252 ui.pageractive = self.ui.pageractive
2253 # internal config: ui.formatted
2254 ui.setconfig(
2255 b'ui',
2256 b'formatted',
2257 self.ui.config(b'ui', b'formatted'),
2258 b'mqpager',
2259 )
2260 ui.setconfig(
2261 b'ui',
2262 b'interactive',
2263 self.ui.config(b'ui', b'interactive'),
2264 b'mqpager',
2265 )
2266 if create or os.path.isdir(self.join(b".hg")):
2267 return repo_factory.repository(ui, path=self.path, create=create)
2268
2269 def restore(self, repo, rev, delete=None, qupdate=None):
2270 desc = repo[rev].description().strip()
2271 lines = desc.splitlines()
2272 datastart = None
2273 series = []
2274 applied = []
2275 qpp = None
2276 for i, line in enumerate(lines):
2277 if line == b'Patch Data:':
2278 datastart = i + 1
2279 elif line.startswith(b'Dirstate:'):
2280 l = line.rstrip()
2281 l = l[10:].split(b' ')
2282 qpp = [bin(x) for x in l]
2283 elif datastart is not None:
2284 l = line.rstrip()
2285 n, name = l.split(b':', 1)
2286 if n:
2287 applied.append(statusentry(bin(n), name))
2288 else:
2289 series.append(l)
2290 if datastart is None:
2291 self.ui.warn(_(b"no saved patch data found\n"))
2292 return 1
2293 self.ui.warn(_(b"restoring status: %s\n") % lines[0])
2294 self.fullseries = series
2295 self.applied = applied
2296 self.parseseries()
2297 self.seriesdirty = True
2298 self.applieddirty = True
2299 heads = repo.changelog.heads()
2300 if delete:
2301 if rev not in heads:
2302 self.ui.warn(_(b"save entry has children, leaving it alone\n"))
2303 else:
2304 self.ui.warn(_(b"removing save entry %s\n") % short(rev))
2305 pp = repo.dirstate.parents()
2306 if rev in pp:
2307 update = True
2308 else:
2309 update = False
2310 strip(self.ui, repo, [rev], update=update, backup=False)
2311 if qpp:
2312 self.ui.warn(
2313 _(b"saved queue repository parents: %s %s\n")
2314 % (short(qpp[0]), short(qpp[1]))
2315 )
2316 if qupdate:
2317 self.ui.status(_(b"updating queue directory\n"))
2318 r = self.qrepo()
2319 if not r:
2320 self.ui.warn(_(b"unable to load queue repository\n"))
2321 return 1
2322 up_impl.clean(r, qpp[0])
2323
2324 def save(self, repo, msg=None):
2325 if not self.applied:
2326 self.ui.warn(_(b"save: no patches applied, exiting\n"))
2327 return 1
2328 if self.issaveline(self.applied[-1]):
2329 self.ui.warn(_(b"status is already saved\n"))
2330 return 1
2331
2332 if not msg:
2333 msg = _(b"hg patches saved state")
2334 else:
2335 msg = b"hg patches: " + msg.rstrip(b'\r\n')
2336 r = self.qrepo()
2337 if r:
2338 pp = r.dirstate.parents()
2339 msg += b"\nDirstate: %s %s" % (hex(pp[0]), hex(pp[1]))
2340 msg += b"\n\nPatch Data:\n"
2341 msg += b''.join(b'%s\n' % x for x in self.applied)
2342 msg += b''.join(b':%s\n' % x for x in self.fullseries)
2343 n = repo.commit(msg, force=True)
2344 if not n:
2345 self.ui.warn(_(b"repo commit failed\n"))
2346 return 1
2347 self.applied.append(statusentry(n, b'.hg.patches.save.line'))
2348 self.applieddirty = True
2349 self.removeundo(repo)
2350
2351 def fullseriesend(self):
2352 if self.applied:
2353 p = self.applied[-1].name
2354 end = self.findseries(p)
2355 if end is None:
2356 return len(self.fullseries)
2357 return end + 1
2358 return 0
2359
2360 def seriesend(self, all_patches=False):
2361 """If all_patches is False, return the index of the next pushable patch
2362 in the series, or the series length. If all_patches is True, return the
2363 index of the first patch past the last applied one.
2364 """
2365 end = 0
2366
2367 def nextpatch(start):
2368 if all_patches or start >= len(self.series):
2369 return start
2370 for i in range(start, len(self.series)):
2371 p, reason = self.pushable(i)
2372 if p:
2373 return i
2374 self.explainpushable(i)
2375 return len(self.series)
2376
2377 if self.applied:
2378 p = self.applied[-1].name
2379 try:
2380 end = self.series.index(p)
2381 except ValueError:
2382 return 0
2383 return nextpatch(end + 1)
2384 return nextpatch(end)
2385
2386 def appliedname(self, index):
2387 pname = self.applied[index].name
2388 if not self.ui.verbose:
2389 p = pname
2390 else:
2391 p = (b"%d" % self.series.index(pname)) + b" " + pname
2392 return p
2393
2394 def qimport(
2395 self,
2396 repo,
2397 files,
2398 patchname=None,
2399 rev=None,
2400 existing=None,
2401 force=None,
2402 git=False,
2403 ):
2404 def checkseries(patchname):
2405 if patchname in self.series:
2406 raise error.Abort(
2407 _(b'patch %s is already in the series file') % patchname
2408 )
2409
2410 if rev:
2411 if files:
2412 raise error.Abort(
2413 _(b'option "-r" not valid when importing files')
2414 )
2415 rev = logcmdutil.revrange(repo, rev)
2416 rev.sort(reverse=True)
2417 elif not files:
2418 raise error.Abort(_(b'no files or revisions specified'))
2419 if (len(files) > 1 or len(rev) > 1) and patchname:
2420 raise error.Abort(
2421 _(b'option "-n" not valid when importing multiple patches')
2422 )
2423 imported = []
2424 if rev:
2425 # If mq patches are applied, we can only import revisions
2426 # that form a linear path to qbase.
2427 # Otherwise, they should form a linear path to a head.
2428 heads = repo.changelog.heads(repo.changelog.node(rev.first()))
2429 if len(heads) > 1:
2430 raise error.Abort(
2431 _(b'revision %d is the root of more than one branch')
2432 % rev.last()
2433 )
2434 if self.applied:
2435 base = repo.changelog.node(rev.first())
2436 if base in [n.node for n in self.applied]:
2437 raise error.Abort(
2438 _(b'revision %d is already managed') % rev.first()
2439 )
2440 if heads != [self.applied[-1].node]:
2441 raise error.Abort(
2442 _(b'revision %d is not the parent of the queue')
2443 % rev.first()
2444 )
2445 base = repo.changelog.rev(self.applied[0].node)
2446 lastparent = repo.changelog.parentrevs(base)[0]
2447 else:
2448 if heads != [repo.changelog.node(rev.first())]:
2449 raise error.Abort(
2450 _(b'revision %d has unmanaged children') % rev.first()
2451 )
2452 lastparent = None
2453
2454 diffopts = self.diffopts({b'git': git})
2455 with repo.transaction(b'qimport') as tr:
2456 for r in rev:
2457 if not repo[r].mutable():
2458 raise error.Abort(
2459 _(b'revision %d is not mutable') % r,
2460 hint=_(b"see 'hg help phases' " b'for details'),
2461 )
2462 p1, p2 = repo.changelog.parentrevs(r)
2463 n = repo.changelog.node(r)
2464 if p2 != nullrev:
2465 raise error.Abort(
2466 _(b'cannot import merge revision %d') % r
2467 )
2468 if lastparent and lastparent != r:
2469 raise error.Abort(
2470 _(b'revision %d is not the parent of %d')
2471 % (r, lastparent)
2472 )
2473 lastparent = p1
2474
2475 if not patchname:
2476 patchname = self.makepatchname(
2477 repo[r].description().split(b'\n', 1)[0],
2478 b'%d.diff' % r,
2479 )
2480 checkseries(patchname)
2481 self.checkpatchname(patchname, force)
2482 self.fullseries.insert(0, patchname)
2483
2484 with self.opener(patchname, b"w") as fp:
2485 cmdutil.exportfile(repo, [n], fp, opts=diffopts)
2486
2487 se = statusentry(n, patchname)
2488 self.applied.insert(0, se)
2489
2490 self.added.append(patchname)
2491 imported.append(patchname)
2492 patchname = None
2493 if rev and repo.ui.configbool(b'mq', b'secret'):
2494 # if we added anything with --rev, move the secret root
2495 phases.retractboundary(repo, tr, phases.secret, [n])
2496 self.parseseries()
2497 self.applieddirty = True
2498 self.seriesdirty = True
2499
2500 for i, filename in enumerate(files):
2501 if existing:
2502 if filename == b'-':
2503 raise error.Abort(
2504 _(b'-e is incompatible with import from -')
2505 )
2506 filename = normname(filename)
2507 self.checkreservedname(filename)
2508 if urlutil.url(filename).islocal():
2509 originpath = self.join(filename)
2510 if not os.path.isfile(originpath):
2511 raise error.Abort(
2512 _(b"patch %s does not exist") % filename
2513 )
2514
2515 if patchname:
2516 self.checkpatchname(patchname, force)
2517
2518 self.ui.write(
2519 _(b'renaming %s to %s\n') % (filename, patchname)
2520 )
2521 util.rename(originpath, self.join(patchname))
2522 else:
2523 patchname = filename
2524
2525 else:
2526 if filename == b'-' and not patchname:
2527 raise error.Abort(
2528 _(b'need --name to import a patch from -')
2529 )
2530 elif not patchname:
2531 patchname = normname(
2532 os.path.basename(filename.rstrip(b'/'))
2533 )
2534 self.checkpatchname(patchname, force)
2535 try:
2536 if filename == b'-':
2537 text = self.ui.fin.read()
2538 else:
2539 fp = scmutil.open_path(self.ui, filename)
2540 text = fp.read()
2541 fp.close()
2542 except OSError:
2543 raise error.Abort(_(b"unable to read file %s") % filename)
2544 patchf = self.opener(patchname, b"w")
2545 patchf.write(text)
2546 patchf.close()
2547 if not force:
2548 checkseries(patchname)
2549 if patchname not in self.series:
2550 index = self.fullseriesend() + i
2551 self.fullseries[index:index] = [patchname]
2552 self.parseseries()
2553 self.seriesdirty = True
2554 self.ui.warn(_(b"adding %s to series file\n") % patchname)
2555 self.added.append(patchname)
2556 imported.append(patchname)
2557 patchname = None
2558
2559 self.removeundo(repo)
2560 return imported
2561
2562
2563 def fixkeepchangesopts(ui, opts):
2564 if (
2565 not ui.configbool(b'mq', b'keepchanges')
2566 or opts.get(b'force')
2567 or opts.get(b'exact')
2568 ):
2569 return opts
2570 opts = dict(opts)
2571 opts[b'keep_changes'] = True
2572 return opts
2573
2574
2575 @command(
2576 b"qdelete|qremove|qrm",
2577 [
2578 (b'k', b'keep', None, _(b'keep patch file')),
2579 (
2580 b'r',
2581 b'rev',
2582 [],
2583 _(b'stop managing a revision (DEPRECATED)'),
2584 _(b'REV'),
2585 ),
2586 ],
2587 _(b'hg qdelete [-k] [PATCH]...'),
2588 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
2589 )
2590 def delete(ui, repo, *patches, **opts):
2591 """remove patches from queue
2592
2593 The patches must not be applied, and at least one patch is required. Exact
2594 patch identifiers must be given. With -k/--keep, the patch files are
2595 preserved in the patch directory.
2596
2597 To stop managing a patch and move it into permanent history,
2598 use the :hg:`qfinish` command."""
2599 q = repo.mq
2600 q.delete(repo, patches, pycompat.byteskwargs(opts))
2601 q.savedirty()
2602 return 0
2603
2604
2605 @command(
2606 b"qapplied",
2607 [(b'1', b'last', None, _(b'show only the preceding applied patch'))]
2608 + seriesopts,
2609 _(b'hg qapplied [-1] [-s] [PATCH]'),
2610 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
2611 )
2612 def applied(ui, repo, patch=None, **opts):
2613 """print the patches already applied
2614
2615 Returns 0 on success."""
2616
2617 q = repo.mq
2618 opts = pycompat.byteskwargs(opts)
2619
2620 if patch:
2621 if patch not in q.series:
2622 raise error.Abort(_(b"patch %s is not in series file") % patch)
2623 end = q.series.index(patch) + 1
2624 else:
2625 end = q.seriesend(True)
2626
2627 if opts.get(b'last') and not end:
2628 ui.write(_(b"no patches applied\n"))
2629 return 1
2630 elif opts.get(b'last') and end == 1:
2631 ui.write(_(b"only one patch applied\n"))
2632 return 1
2633 elif opts.get(b'last'):
2634 start = end - 2
2635 end = 1
2636 else:
2637 start = 0
2638
2639 q.qseries(
2640 repo, length=end, start=start, status=b'A', summary=opts.get(b'summary')
2641 )
2642
2643
2644 @command(
2645 b"qunapplied",
2646 [(b'1', b'first', None, _(b'show only the first patch'))] + seriesopts,
2647 _(b'hg qunapplied [-1] [-s] [PATCH]'),
2648 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
2649 )
2650 def unapplied(ui, repo, patch=None, **opts):
2651 """print the patches not yet applied
2652
2653 Returns 0 on success."""
2654
2655 q = repo.mq
2656 opts = pycompat.byteskwargs(opts)
2657 if patch:
2658 if patch not in q.series:
2659 raise error.Abort(_(b"patch %s is not in series file") % patch)
2660 start = q.series.index(patch) + 1
2661 else:
2662 start = q.seriesend(True)
2663
2664 if start == len(q.series) and opts.get(b'first'):
2665 ui.write(_(b"all patches applied\n"))
2666 return 1
2667
2668 if opts.get(b'first'):
2669 length = 1
2670 else:
2671 length = None
2672 q.qseries(
2673 repo,
2674 start=start,
2675 length=length,
2676 status=b'U',
2677 summary=opts.get(b'summary'),
2678 )
2679
2680
2681 @command(
2682 b"qimport",
2683 [
2684 (b'e', b'existing', None, _(b'import file in patch directory')),
2685 (b'n', b'name', b'', _(b'name of patch file'), _(b'NAME')),
2686 (b'f', b'force', None, _(b'overwrite existing files')),
2687 (
2688 b'r',
2689 b'rev',
2690 [],
2691 _(b'place existing revisions under mq control'),
2692 _(b'REV'),
2693 ),
2694 (b'g', b'git', None, _(b'use git extended diff format')),
2695 (b'P', b'push', None, _(b'qpush after importing')),
2696 ],
2697 _(b'hg qimport [-e] [-n NAME] [-f] [-g] [-P] [-r REV]... [FILE]...'),
2698 helpcategory=command.CATEGORY_IMPORT_EXPORT,
2699 )
2700 def qimport(ui, repo, *filename, **opts):
2701 """import a patch or existing changeset
2702
2703 The patch is inserted into the series after the last applied
2704 patch. If no patches have been applied, qimport prepends the patch
2705 to the series.
2706
2707 The patch will have the same name as its source file unless you
2708 give it a new one with -n/--name.
2709
2710 You can register an existing patch inside the patch directory with
2711 the -e/--existing flag.
2712
2713 With -f/--force, an existing patch of the same name will be
2714 overwritten.
2715
2716 An existing changeset may be placed under mq control with -r/--rev
2717 (e.g. qimport --rev . -n patch will place the current revision
2718 under mq control). With -g/--git, patches imported with --rev will
2719 use the git diff format. See the diffs help topic for information
2720 on why this is important for preserving rename/copy information
2721 and permission changes. Use :hg:`qfinish` to remove changesets
2722 from mq control.
2723
2724 To import a patch from standard input, pass - as the patch file.
2725 When importing from standard input, a patch name must be specified
2726 using the --name flag.
2727
2728 To import an existing patch while renaming it::
2729
2730 hg qimport -e existing-patch -n new-name
2731
2732 Returns 0 if import succeeded.
2733 """
2734 opts = pycompat.byteskwargs(opts)
2735 with repo.lock(): # cause this may move phase
2736 q = repo.mq
2737 try:
2738 imported = q.qimport(
2739 repo,
2740 filename,
2741 patchname=opts.get(b'name'),
2742 existing=opts.get(b'existing'),
2743 force=opts.get(b'force'),
2744 rev=opts.get(b'rev'),
2745 git=opts.get(b'git'),
2746 )
2747 finally:
2748 q.savedirty()
2749
2750 if imported and opts.get(b'push') and not opts.get(b'rev'):
2751 return q.push(repo, imported[-1])
2752 return 0
2753
2754
2755 def qinit(ui, repo, create):
2756 """initialize a new queue repository
2757
2758 This command also creates a series file for ordering patches, and
2759 an mq-specific .hgignore file in the queue repository, to exclude
2760 the status and guards files (these contain mostly transient state).
2761
2762 Returns 0 if initialization succeeded."""
2763 q = repo.mq
2764 r = q.init(repo, create)
2765 q.savedirty()
2766 if r:
2767 with r.wlock(), r.dirstate.changing_files(r):
2768 if not os.path.exists(r.wjoin(b'.hgignore')):
2769 fp = r.wvfs(b'.hgignore', b'w')
2770 fp.write(b'^\\.hg\n')
2771 fp.write(b'^\\.mq\n')
2772 fp.write(b'syntax: glob\n')
2773 fp.write(b'status\n')
2774 fp.write(b'guards\n')
2775 fp.close()
2776 if not os.path.exists(r.wjoin(b'series')):
2777 r.wvfs(b'series', b'w').close()
2778 r[None].add([b'.hgignore', b'series'])
2779 commands.add(ui, r)
2780 return 0
2781
2782
2783 @command(
2784 b"qinit",
2785 [(b'c', b'create-repo', None, _(b'create queue repository'))],
2786 _(b'hg qinit [-c]'),
2787 helpcategory=command.CATEGORY_REPO_CREATION,
2788 helpbasic=True,
2789 )
2790 def init(ui, repo, **opts):
2791 """init a new queue repository (DEPRECATED)
2792
2793 The queue repository is unversioned by default. If
2794 -c/--create-repo is specified, qinit will create a separate nested
2795 repository for patches (qinit -c may also be run later to convert
2796 an unversioned patch repository into a versioned one). You can use
2797 qcommit to commit changes to this queue repository.
2798
2799 This command is deprecated. Without -c, it's implied by other relevant
2800 commands. With -c, use :hg:`init --mq` instead."""
2801 return qinit(ui, repo, create=opts.get('create_repo'))
2802
2803
2804 @command(
2805 b"qclone",
2806 [
2807 (b'', b'pull', None, _(b'use pull protocol to copy metadata')),
2808 (
2809 b'U',
2810 b'noupdate',
2811 None,
2812 _(b'do not update the new working directories'),
2813 ),
2814 (
2815 b'',
2816 b'uncompressed',
2817 None,
2818 _(b'use uncompressed transfer (fast over LAN)'),
2819 ),
2820 (
2821 b'p',
2822 b'patches',
2823 b'',
2824 _(b'location of source patch repository'),
2825 _(b'REPO'),
2826 ),
2827 ]
2828 + cmdutil.remoteopts,
2829 _(b'hg qclone [OPTION]... SOURCE [DEST]'),
2830 helpcategory=command.CATEGORY_REPO_CREATION,
2831 norepo=True,
2832 )
2833 def clone(ui, source, dest=None, **opts):
2834 """clone main and patch repository at same time
2835
2836 If source is local, destination will have no patches applied. If
2837 source is remote, this command can not check if patches are
2838 applied in source, so cannot guarantee that patches are not
2839 applied in destination. If you clone remote repository, be sure
2840 before that it has no patches applied.
2841
2842 Source patch repository is looked for in <src>/.hg/patches by
2843 default. Use -p <url> to change.
2844
2845 The patch directory must be a nested Mercurial repository, as
2846 would be created by :hg:`init --mq`.
2847
2848 Return 0 on success.
2849 """
2850 opts = pycompat.byteskwargs(opts)
2851
2852 def patchdir(repo):
2853 """compute a patch repo url from a repo object"""
2854 url = repo.url()
2855 if url.endswith(b'/'):
2856 url = url[:-1]
2857 return url + b'/.hg/patches'
2858
2859 # main repo (destination and sources)
2860 if dest is None:
2861 dest = clone_impl.default_dest(source)
2862 source_path = urlutil.get_clone_path_obj(ui, source)
2863 sr = repo_factory.peer(ui, opts, source_path)
2864
2865 # patches repo (source only)
2866 if opts.get(b'patches'):
2867 patches_path = urlutil.get_clone_path_obj(ui, opts.get(b'patches'))
2868 else:
2869 # XXX path: we should turn this into a path object
2870 patches_path = patchdir(sr)
2871 try:
2872 repo_factory.peer(ui, opts, patches_path)
2873 except error.RepoError:
2874 raise error.Abort(
2875 _(b'versioned patch repository not found (see init --mq)')
2876 )
2877 qbase, destrev = None, None
2878 if sr.local():
2879 repo = sr.local()
2880 if repo.mq.applied and repo[qbase].phase() != phases.secret:
2881 qbase = repo.mq.applied[0].node
2882 if not repo_factory.is_local(dest):
2883 heads = set(repo.heads())
2884 destrev = list(heads.difference(repo.heads(qbase)))
2885 destrev.append(repo.changelog.parents(qbase)[0])
2886 elif sr.capable(b'lookup'):
2887 try:
2888 qbase = sr.lookup(b'qbase')
2889 except error.RepoError:
2890 pass
2891
2892 ui.note(_(b'cloning main repository\n'))
2893 sr, dr = clone_impl.clone(
2894 ui,
2895 opts,
2896 sr.url(),
2897 dest,
2898 pull=opts.get(b'pull'),
2899 revs=destrev,
2900 update=False,
2901 stream=opts.get(b'uncompressed'),
2902 )
2903
2904 ui.note(_(b'cloning patch repository\n'))
2905 clone_impl.clone(
2906 ui,
2907 opts,
2908 opts.get(b'patches') or patchdir(sr),
2909 patchdir(dr),
2910 pull=opts.get(b'pull'),
2911 update=not opts.get(b'noupdate'),
2912 stream=opts.get(b'uncompressed'),
2913 )
2914
2915 if dr.local():
2916 repo = dr.local()
2917 if qbase:
2918 ui.note(
2919 _(
2920 b'stripping applied patches from destination '
2921 b'repository\n'
2922 )
2923 )
2924 strip(ui, repo, [qbase], update=False, backup=None)
2925 if not opts.get(b'noupdate'):
2926 ui.note(_(b'updating destination repository\n'))
2927 up_impl.update(repo, repo.changelog.tip())
2928
2929
2930 @command(
2931 b"qcommit|qci",
2932 commands.table[b"commit|ci"][1],
2933 _(b'hg qcommit [OPTION]... [FILE]...'),
2934 helpcategory=command.CATEGORY_COMMITTING,
2935 inferrepo=True,
2936 )
2937 def commit(ui, repo, *pats, **opts):
2938 """commit changes in the queue repository (DEPRECATED)
2939
2940 This command is deprecated; use :hg:`commit --mq` instead."""
2941 q = repo.mq
2942 r = q.qrepo()
2943 if not r:
2944 raise error.Abort(b'no queue repository')
2945 commands.commit(r.ui, r, *pats, **opts)
2946
2947
2948 @command(
2949 b"qseries",
2950 [
2951 (b'm', b'missing', None, _(b'print patches not in series')),
2952 ]
2953 + seriesopts,
2954 _(b'hg qseries [-ms]'),
2955 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
2956 )
2957 def series(ui, repo, **opts):
2958 """print the entire series file
2959
2960 Returns 0 on success."""
2961 repo.mq.qseries(
2962 repo, missing=opts.get('missing'), summary=opts.get('summary')
2963 )
2964 return 0
2965
2966
2967 @command(
2968 b"qtop",
2969 seriesopts,
2970 _(b'hg qtop [-s]'),
2971 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
2972 )
2973 def top(ui, repo, **opts):
2974 """print the name of the current patch
2975
2976 Returns 0 on success."""
2977 q = repo.mq
2978 if q.applied:
2979 t = q.seriesend(True)
2980 else:
2981 t = 0
2982
2983 if t:
2984 q.qseries(
2985 repo,
2986 start=t - 1,
2987 length=1,
2988 status=b'A',
2989 summary=opts.get('summary'),
2990 )
2991 else:
2992 ui.write(_(b"no patches applied\n"))
2993 return 1
2994
2995
2996 @command(
2997 b"qnext",
2998 seriesopts,
2999 _(b'hg qnext [-s]'),
3000 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
3001 )
3002 def next(ui, repo, **opts):
3003 """print the name of the next pushable patch
3004
3005 Returns 0 on success."""
3006 q = repo.mq
3007 end = q.seriesend()
3008 if end == len(q.series):
3009 ui.write(_(b"all patches applied\n"))
3010 return 1
3011 q.qseries(repo, start=end, length=1, summary=opts.get('summary'))
3012
3013
3014 @command(
3015 b"qprev",
3016 seriesopts,
3017 _(b'hg qprev [-s]'),
3018 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
3019 )
3020 def prev(ui, repo, **opts):
3021 """print the name of the preceding applied patch
3022
3023 Returns 0 on success."""
3024 q = repo.mq
3025 l = len(q.applied)
3026 if l == 1:
3027 ui.write(_(b"only one patch applied\n"))
3028 return 1
3029 if not l:
3030 ui.write(_(b"no patches applied\n"))
3031 return 1
3032 idx = q.series.index(q.applied[-2].name)
3033 q.qseries(
3034 repo, start=idx, length=1, status=b'A', summary=opts.get('summary')
3035 )
3036
3037
3038 def setupheaderopts(ui, opts):
3039 if not opts.get(b'user') and opts.get(b'currentuser'):
3040 opts[b'user'] = ui.username()
3041 if not opts.get(b'date') and opts.get(b'currentdate'):
3042 opts[b'date'] = b"%d %d" % dateutil.makedate()
3043
3044
3045 @command(
3046 b"qnew",
3047 [
3048 (b'e', b'edit', None, _(b'invoke editor on commit messages')),
3049 (b'f', b'force', None, _(b'import uncommitted changes (DEPRECATED)')),
3050 (b'g', b'git', None, _(b'use git extended diff format')),
3051 (b'U', b'currentuser', None, _(b'add "From: <current user>" to patch')),
3052 (b'u', b'user', b'', _(b'add "From: <USER>" to patch'), _(b'USER')),
3053 (b'D', b'currentdate', None, _(b'add "Date: <current date>" to patch')),
3054 (b'd', b'date', b'', _(b'add "Date: <DATE>" to patch'), _(b'DATE')),
3055 ]
3056 + cmdutil.walkopts
3057 + cmdutil.commitopts,
3058 _(b'hg qnew [-e] [-m TEXT] [-l FILE] PATCH [FILE]...'),
3059 helpcategory=command.CATEGORY_COMMITTING,
3060 helpbasic=True,
3061 inferrepo=True,
3062 )
3063 def new(ui, repo, patch, *args, **opts):
3064 """create a new patch
3065
3066 qnew creates a new patch on top of the currently-applied patch (if
3067 any). The patch will be initialized with any outstanding changes
3068 in the working directory. You may also use -I/--include,
3069 -X/--exclude, and/or a list of files after the patch name to add
3070 only changes to matching files to the new patch, leaving the rest
3071 as uncommitted modifications.
3072
3073 -u/--user and -d/--date can be used to set the (given) user and
3074 date, respectively. -U/--currentuser and -D/--currentdate set user
3075 to current user and date to current date.
3076
3077 -e/--edit, -m/--message or -l/--logfile set the patch header as
3078 well as the commit message. If none is specified, the header is
3079 empty and the commit message is '[mq]: PATCH'.
3080
3081 Use the -g/--git option to keep the patch in the git extended diff
3082 format. Read the diffs help topic for more information on why this
3083 is important for preserving permission changes and copy/rename
3084 information.
3085
3086 Returns 0 on successful creation of a new patch.
3087 """
3088 opts = pycompat.byteskwargs(opts)
3089 msg = cmdutil.logmessage(ui, opts)
3090 q = repo.mq
3091 opts[b'msg'] = msg
3092 setupheaderopts(ui, opts)
3093 q.new(repo, patch, *args, **pycompat.strkwargs(opts))
3094 q.savedirty()
3095 return 0
3096
3097
3098 @command(
3099 b"qrefresh",
3100 [
3101 (b'e', b'edit', None, _(b'invoke editor on commit messages')),
3102 (b'g', b'git', None, _(b'use git extended diff format')),
3103 (
3104 b's',
3105 b'short',
3106 None,
3107 _(b'refresh only files already in the patch and specified files'),
3108 ),
3109 (
3110 b'U',
3111 b'currentuser',
3112 None,
3113 _(b'add/update author field in patch with current user'),
3114 ),
3115 (
3116 b'u',
3117 b'user',
3118 b'',
3119 _(b'add/update author field in patch with given user'),
3120 _(b'USER'),
3121 ),
3122 (
3123 b'D',
3124 b'currentdate',
3125 None,
3126 _(b'add/update date field in patch with current date'),
3127 ),
3128 (
3129 b'd',
3130 b'date',
3131 b'',
3132 _(b'add/update date field in patch with given date'),
3133 _(b'DATE'),
3134 ),
3135 ]
3136 + cmdutil.walkopts
3137 + cmdutil.commitopts,
3138 _(b'hg qrefresh [-I] [-X] [-e] [-m TEXT] [-l FILE] [-s] [FILE]...'),
3139 helpcategory=command.CATEGORY_COMMITTING,
3140 helpbasic=True,
3141 inferrepo=True,
3142 )
3143 def refresh(ui, repo, *pats, **opts):
3144 """update the current patch
3145
3146 If any file patterns are provided, the refreshed patch will
3147 contain only the modifications that match those patterns; the
3148 remaining modifications will remain in the working directory.
3149
3150 If -s/--short is specified, files currently included in the patch
3151 will be refreshed just like matched files and remain in the patch.
3152
3153 If -e/--edit is specified, Mercurial will start your configured editor for
3154 you to enter a message. In case qrefresh fails, you will find a backup of
3155 your message in ``.hg/last-message.txt``.
3156
3157 hg add/remove/copy/rename work as usual, though you might want to
3158 use git-style patches (-g/--git or [diff] git=1) to track copies
3159 and renames. See the diffs help topic for more information on the
3160 git diff format.
3161
3162 Returns 0 on success.
3163 """
3164 opts = pycompat.byteskwargs(opts)
3165 q = repo.mq
3166 message = cmdutil.logmessage(ui, opts)
3167 setupheaderopts(ui, opts)
3168 with repo.wlock():
3169 ret = q.refresh(repo, pats, msg=message, **pycompat.strkwargs(opts))
3170 q.savedirty()
3171 return ret
3172
3173
3174 @command(
3175 b"qdiff",
3176 cmdutil.diffopts + cmdutil.diffopts2 + cmdutil.walkopts,
3177 _(b'hg qdiff [OPTION]... [FILE]...'),
3178 helpcategory=command.CATEGORY_FILE_CONTENTS,
3179 helpbasic=True,
3180 inferrepo=True,
3181 )
3182 def diff(ui, repo, *pats, **opts):
3183 """diff of the current patch and subsequent modifications
3184
3185 Shows a diff which includes the current patch as well as any
3186 changes which have been made in the working directory since the
3187 last refresh (thus showing what the current patch would become
3188 after a qrefresh).
3189
3190 Use :hg:`diff` if you only want to see the changes made since the
3191 last qrefresh, or :hg:`export qtip` if you want to see changes
3192 made by the current patch without including changes made since the
3193 qrefresh.
3194
3195 Returns 0 on success.
3196 """
3197 ui.pager(b'qdiff')
3198 repo.mq.diff(repo, pats, pycompat.byteskwargs(opts))
3199 return 0
3200
3201
3202 @command(
3203 b'qfold',
3204 [
3205 (b'e', b'edit', None, _(b'invoke editor on commit messages')),
3206 (b'k', b'keep', None, _(b'keep folded patch files')),
3207 ]
3208 + cmdutil.commitopts,
3209 _(b'hg qfold [-e] [-k] [-m TEXT] [-l FILE] PATCH...'),
3210 helpcategory=command.CATEGORY_CHANGE_MANAGEMENT,
3211 )
3212 def fold(ui, repo, *files, **opts):
3213 """fold the named patches into the current patch
3214
3215 Patches must not yet be applied. Each patch will be successively
3216 applied to the current patch in the order given. If all the
3217 patches apply successfully, the current patch will be refreshed
3218 with the new cumulative patch, and the folded patches will be
3219 deleted. With -k/--keep, the folded patch files will not be
3220 removed afterwards.
3221
3222 The header for each folded patch will be concatenated with the
3223 current patch header, separated by a line of ``* * *``.
3224
3225 Returns 0 on success."""
3226 opts = pycompat.byteskwargs(opts)
3227 q = repo.mq
3228 if not files:
3229 raise error.Abort(_(b'qfold requires at least one patch name'))
3230 if not q.checktoppatch(repo)[0]:
3231 raise error.Abort(_(b'no patches applied'))
3232
3233 with repo.wlock():
3234 q.checklocalchanges(repo)
3235
3236 message = cmdutil.logmessage(ui, opts)
3237
3238 parent = q.lookup(b'qtip')
3239 patches = []
3240 messages = []
3241 for f in files:
3242 p = q.lookup(f)
3243 if p in patches or p == parent:
3244 ui.warn(_(b'skipping already folded patch %s\n') % p)
3245 if q.isapplied(p):
3246 raise error.Abort(
3247 _(b'qfold cannot fold already applied patch %s') % p
3248 )
3249 patches.append(p)
3250
3251 for p in patches:
3252 if not message:
3253 ph = patchheader(q.join(p), q.plainmode)
3254 if ph.message:
3255 messages.append(ph.message)
3256 pf = q.join(p)
3257 (patchsuccess, files, fuzz) = q.patch(repo, pf)
3258 if not patchsuccess:
3259 raise error.Abort(_(b'error folding patch %s') % p)
3260
3261 if not message:
3262 ph = patchheader(q.join(parent), q.plainmode)
3263 message = ph.message
3264 for msg in messages:
3265 if msg:
3266 if message:
3267 message.append(b'* * *')
3268 message.extend(msg)
3269 message = b'\n'.join(message)
3270
3271 diffopts = q.patchopts(q.diffopts(), *patches)
3272 q.refresh(
3273 repo,
3274 msg=message,
3275 git=diffopts.git,
3276 edit=opts.get(b'edit'),
3277 editform=b'mq.qfold',
3278 )
3279 q.delete(repo, patches, opts)
3280 q.savedirty()
3281
3282
3283 @command(
3284 b"qgoto",
3285 [
3286 (
3287 b'',
3288 b'keep-changes',
3289 None,
3290 _(b'tolerate non-conflicting local changes'),
3291 ),
3292 (b'f', b'force', None, _(b'overwrite any local changes')),
3293 (b'', b'no-backup', None, _(b'do not save backup copies of files')),
3294 ],
3295 _(b'hg qgoto [OPTION]... PATCH'),
3296 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
3297 )
3298 def goto(ui, repo, patch, **opts):
3299 """push or pop patches until named patch is at top of stack
3300
3301 Returns 0 on success."""
3302 opts = pycompat.byteskwargs(opts)
3303 opts = fixkeepchangesopts(ui, opts)
3304 q = repo.mq
3305 patch = q.lookup(patch)
3306 nobackup = opts.get(b'no_backup')
3307 keepchanges = opts.get(b'keep_changes')
3308 if q.isapplied(patch):
3309 ret = q.pop(
3310 repo,
3311 patch,
3312 force=opts.get(b'force'),
3313 nobackup=nobackup,
3314 keepchanges=keepchanges,
3315 )
3316 else:
3317 ret = q.push(
3318 repo,
3319 patch,
3320 force=opts.get(b'force'),
3321 nobackup=nobackup,
3322 keepchanges=keepchanges,
3323 )
3324 q.savedirty()
3325 return ret
3326
3327
3328 @command(
3329 b"qguard",
3330 [
3331 (b'l', b'list', None, _(b'list all patches and guards')),
3332 (b'n', b'none', None, _(b'drop all guards')),
3333 ],
3334 _(b'hg qguard [-l] [-n] [PATCH] [-- [+GUARD]... [-GUARD]...]'),
3335 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
3336 )
3337 def guard(ui, repo, *args, **opts):
3338 """set or print guards for a patch
3339
3340 Guards control whether a patch can be pushed. A patch with no
3341 guards is always pushed. A patch with a positive guard ("+foo") is
3342 pushed only if the :hg:`qselect` command has activated it. A patch with
3343 a negative guard ("-foo") is never pushed if the :hg:`qselect` command
3344 has activated it.
3345
3346 With no arguments, print the currently active guards.
3347 With arguments, set guards for the named patch.
3348
3349 .. note::
3350
3351 Specifying negative guards now requires '--'.
3352
3353 To set guards on another patch::
3354
3355 hg qguard other.patch -- +2.6.17 -stable
3356
3357 Returns 0 on success.
3358 """
3359
3360 def status(idx):
3361 guards = q.seriesguards[idx] or [b'unguarded']
3362 if q.series[idx] in applied:
3363 state = b'applied'
3364 elif q.pushable(idx)[0]:
3365 state = b'unapplied'
3366 else:
3367 state = b'guarded'
3368 label = b'qguard.patch qguard.%s qseries.%s' % (state, state)
3369 ui.write(b'%s: ' % ui.label(q.series[idx], label))
3370
3371 for i, guard in enumerate(guards):
3372 if guard.startswith(b'+'):
3373 ui.write(guard, label=b'qguard.positive')
3374 elif guard.startswith(b'-'):
3375 ui.write(guard, label=b'qguard.negative')
3376 else:
3377 ui.write(guard, label=b'qguard.unguarded')
3378 if i != len(guards) - 1:
3379 ui.write(b' ')
3380 ui.write(b'\n')
3381
3382 q = repo.mq
3383 applied = {p.name for p in q.applied}
3384 patch = None
3385 args = list(args)
3386 if opts.get('list'):
3387 if args or opts.get('none'):
3388 raise error.Abort(
3389 _(b'cannot mix -l/--list with options or arguments')
3390 )
3391 for i in range(len(q.series)):
3392 status(i)
3393 return
3394 if not args or args[0][0:1] in b'-+':
3395 if not q.applied:
3396 raise error.Abort(_(b'no patches applied'))
3397 patch = q.applied[-1].name
3398 if patch is None and args[0][0:1] not in b'-+':
3399 patch = args.pop(0)
3400 if patch is None:
3401 raise error.Abort(_(b'no patch to work with'))
3402 if args or opts.get('none'):
3403 idx = q.findseries(patch)
3404 if idx is None:
3405 raise error.Abort(_(b'no patch named %s') % patch)
3406 q.setguards(idx, args)
3407 q.savedirty()
3408 else:
3409 status(q.series.index(q.lookup(patch)))
3410
3411
3412 @command(
3413 b"qheader",
3414 [],
3415 _(b'hg qheader [PATCH]'),
3416 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
3417 )
3418 def header(ui, repo, patch=None):
3419 """print the header of the topmost or specified patch
3420
3421 Returns 0 on success."""
3422 q = repo.mq
3423
3424 if patch:
3425 patch = q.lookup(patch)
3426 else:
3427 if not q.applied:
3428 ui.write(_(b'no patches applied\n'))
3429 return 1
3430 patch = q.lookup(b'qtip')
3431 ph = patchheader(q.join(patch), q.plainmode)
3432
3433 ui.write(b'\n'.join(ph.message) + b'\n')
3434
3435
3436 def lastsavename(path):
3437 (directory, base) = os.path.split(path)
3438 names = os.listdir(directory)
3439 namere = re.compile(b"%s.([0-9]+)" % base)
3440 maxindex = None
3441 maxname = None
3442 for f in names:
3443 m = namere.match(f)
3444 if m:
3445 index = int(m.group(1))
3446 if maxindex is None or index > maxindex:
3447 maxindex = index
3448 maxname = f
3449 if maxname:
3450 return (os.path.join(directory, maxname), maxindex)
3451 return (None, None)
3452
3453
3454 def savename(path):
3455 (last, index) = lastsavename(path)
3456 if last is None:
3457 index = 0
3458 newpath = path + b".%d" % (index + 1)
3459 return newpath
3460
3461
3462 @command(
3463 b"qpush",
3464 [
3465 (
3466 b'',
3467 b'keep-changes',
3468 None,
3469 _(b'tolerate non-conflicting local changes'),
3470 ),
3471 (b'f', b'force', None, _(b'apply on top of local changes')),
3472 (
3473 b'e',
3474 b'exact',
3475 None,
3476 _(b'apply the target patch to its recorded parent'),
3477 ),
3478 (b'l', b'list', None, _(b'list patch name in commit text')),
3479 (b'a', b'all', None, _(b'apply all patches')),
3480 (b'm', b'merge', None, _(b'merge from another queue (DEPRECATED)')),
3481 (b'n', b'name', b'', _(b'merge queue name (DEPRECATED)'), _(b'NAME')),
3482 (
3483 b'',
3484 b'move',
3485 None,
3486 _(b'reorder patch series and apply only the patch'),
3487 ),
3488 (b'', b'no-backup', None, _(b'do not save backup copies of files')),
3489 ],
3490 _(b'hg qpush [-f] [-l] [-a] [--move] [PATCH | INDEX]'),
3491 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
3492 helpbasic=True,
3493 )
3494 def push(ui, repo, patch=None, **opts):
3495 """push the next patch onto the stack
3496
3497 By default, abort if the working directory contains uncommitted
3498 changes. With --keep-changes, abort only if the uncommitted files
3499 overlap with patched files. With -f/--force, backup and patch over
3500 uncommitted changes.
3501
3502 Return 0 on success.
3503 """
3504 q = repo.mq
3505 mergeq = None
3506
3507 opts = pycompat.byteskwargs(opts)
3508 opts = fixkeepchangesopts(ui, opts)
3509 if opts.get(b'merge'):
3510 if opts.get(b'name'):
3511 newpath = repo.vfs.join(opts.get(b'name'))
3512 else:
3513 newpath, i = lastsavename(q.path)
3514 if not newpath:
3515 ui.warn(_(b"no saved queues found, please use -n\n"))
3516 return 1
3517 mergeq = queue(ui, repo.baseui, repo.path, newpath)
3518 ui.warn(_(b"merging with queue at: %s\n") % mergeq.path)
3519 ret = q.push(
3520 repo,
3521 patch,
3522 force=opts.get(b'force'),
3523 list=opts.get(b'list'),
3524 mergeq=mergeq,
3525 all=opts.get(b'all'),
3526 move=opts.get(b'move'),
3527 exact=opts.get(b'exact'),
3528 nobackup=opts.get(b'no_backup'),
3529 keepchanges=opts.get(b'keep_changes'),
3530 )
3531 return ret
3532
3533
3534 @command(
3535 b"qpop",
3536 [
3537 (b'a', b'all', None, _(b'pop all patches')),
3538 (b'n', b'name', b'', _(b'queue name to pop (DEPRECATED)'), _(b'NAME')),
3539 (
3540 b'',
3541 b'keep-changes',
3542 None,
3543 _(b'tolerate non-conflicting local changes'),
3544 ),
3545 (b'f', b'force', None, _(b'forget any local changes to patched files')),
3546 (b'', b'no-backup', None, _(b'do not save backup copies of files')),
3547 ],
3548 _(b'hg qpop [-a] [-f] [PATCH | INDEX]'),
3549 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
3550 helpbasic=True,
3551 )
3552 def pop(ui, repo, patch=None, **opts):
3553 """pop the current patch off the stack
3554
3555 Without argument, pops off the top of the patch stack. If given a
3556 patch name, keeps popping off patches until the named patch is at
3557 the top of the stack.
3558
3559 By default, abort if the working directory contains uncommitted
3560 changes. With --keep-changes, abort only if the uncommitted files
3561 overlap with patched files. With -f/--force, backup and discard
3562 changes made to such files.
3563
3564 Return 0 on success.
3565 """
3566 opts = pycompat.byteskwargs(opts)
3567 opts = fixkeepchangesopts(ui, opts)
3568 localupdate = True
3569 if opts.get(b'name'):
3570 q = queue(ui, repo.baseui, repo.path, repo.vfs.join(opts.get(b'name')))
3571 ui.warn(_(b'using patch queue: %s\n') % q.path)
3572 localupdate = False
3573 else:
3574 q = repo.mq
3575 ret = q.pop(
3576 repo,
3577 patch,
3578 force=opts.get(b'force'),
3579 update=localupdate,
3580 all=opts.get(b'all'),
3581 nobackup=opts.get(b'no_backup'),
3582 keepchanges=opts.get(b'keep_changes'),
3583 )
3584 q.savedirty()
3585 return ret
3586
3587
3588 @command(
3589 b"qrename|qmv",
3590 [],
3591 _(b'hg qrename PATCH1 [PATCH2]'),
3592 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
3593 )
3594 def rename(ui, repo, patch, name=None, **opts):
3595 """rename a patch
3596
3597 With one argument, renames the current patch to PATCH1.
3598 With two arguments, renames PATCH1 to PATCH2.
3599
3600 Returns 0 on success."""
3601 q = repo.mq
3602 if not name:
3603 name = patch
3604 patch = None
3605
3606 if patch:
3607 patch = q.lookup(patch)
3608 else:
3609 if not q.applied:
3610 ui.write(_(b'no patches applied\n'))
3611 return
3612 patch = q.lookup(b'qtip')
3613 absdest = q.join(name)
3614 if os.path.isdir(absdest):
3615 name = normname(os.path.join(name, os.path.basename(patch)))
3616 absdest = q.join(name)
3617 q.checkpatchname(name)
3618
3619 ui.note(_(b'renaming %s to %s\n') % (patch, name))
3620 i = q.findseries(patch)
3621 guards = q.guard_re.findall(q.fullseries[i])
3622 q.fullseries[i] = name + b''.join([b' #' + g for g in guards])
3623 q.parseseries()
3624 q.seriesdirty = True
3625
3626 info = q.isapplied(patch)
3627 if info:
3628 q.applied[info[0]] = statusentry(info[1], name)
3629 q.applieddirty = True
3630
3631 destdir = os.path.dirname(absdest)
3632 if not os.path.isdir(destdir):
3633 os.makedirs(destdir)
3634 util.rename(q.join(patch), absdest)
3635 r = q.qrepo()
3636 if r and patch in r.dirstate:
3637 with r.wlock(), r.dirstate.changing_files(r):
3638 wctx = r[None]
3639 if r.dirstate.get_entry(patch).added:
3640 r.dirstate.set_untracked(patch)
3641 r.dirstate.set_tracked(name)
3642 else:
3643 wctx.copy(patch, name)
3644 wctx.forget([patch])
3645
3646 q.savedirty()
3647
3648
3649 @command(
3650 b"qrestore",
3651 [
3652 (b'd', b'delete', None, _(b'delete save entry')),
3653 (b'u', b'update', None, _(b'update queue working directory')),
3654 ],
3655 _(b'hg qrestore [-d] [-u] REV'),
3656 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
3657 )
3658 def restore(ui, repo, rev, **opts):
3659 """restore the queue state saved by a revision (DEPRECATED)
3660
3661 This command is deprecated, use :hg:`rebase` instead."""
3662 rev = repo.lookup(rev)
3663 q = repo.mq
3664 q.restore(repo, rev, delete=opts.get('delete'), qupdate=opts.get('update'))
3665 q.savedirty()
3666 return 0
3667
3668
3669 @command(
3670 b"qsave",
3671 [
3672 (b'c', b'copy', None, _(b'copy patch directory')),
3673 (b'n', b'name', b'', _(b'copy directory name'), _(b'NAME')),
3674 (b'e', b'empty', None, _(b'clear queue status file')),
3675 (b'f', b'force', None, _(b'force copy')),
3676 ]
3677 + cmdutil.commitopts,
3678 _(b'hg qsave [-m TEXT] [-l FILE] [-c] [-n NAME] [-e] [-f]'),
3679 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
3680 )
3681 def save(ui, repo, **opts):
3682 """save current queue state (DEPRECATED)
3683
3684 This command is deprecated, use :hg:`rebase` instead."""
3685 q = repo.mq
3686 opts = pycompat.byteskwargs(opts)
3687 message = cmdutil.logmessage(ui, opts)
3688 ret = q.save(repo, msg=message)
3689 if ret:
3690 return ret
3691 q.savedirty() # save to .hg/patches before copying
3692 if opts.get(b'copy'):
3693 path = q.path
3694 if opts.get(b'name'):
3695 newpath = os.path.join(q.basepath, opts.get(b'name'))
3696 if os.path.exists(newpath):
3697 if not os.path.isdir(newpath):
3698 raise error.Abort(
3699 _(b'destination %s exists and is not a directory')
3700 % newpath
3701 )
3702 if not opts.get(b'force'):
3703 raise error.Abort(
3704 _(b'destination %s exists, use -f to force') % newpath
3705 )
3706 else:
3707 newpath = savename(path)
3708 ui.warn(_(b"copy %s to %s\n") % (path, newpath))
3709 util.copyfiles(path, newpath)
3710 if opts.get(b'empty'):
3711 del q.applied[:]
3712 q.applieddirty = True
3713 q.savedirty()
3714 return 0
3715
3716
3717 @command(
3718 b"qselect",
3719 [
3720 (b'n', b'none', None, _(b'disable all guards')),
3721 (b's', b'series', None, _(b'list all guards in series file')),
3722 (b'', b'pop', None, _(b'pop to before first guarded applied patch')),
3723 (b'', b'reapply', None, _(b'pop, then reapply patches')),
3724 ],
3725 _(b'hg qselect [OPTION]... [GUARD]...'),
3726 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
3727 )
3728 def select(ui, repo, *args, **opts):
3729 """set or print guarded patches to push
3730
3731 Use the :hg:`qguard` command to set or print guards on patch, then use
3732 qselect to tell mq which guards to use. A patch will be pushed if
3733 it has no guards or any positive guards match the currently
3734 selected guard, but will not be pushed if any negative guards
3735 match the current guard. For example::
3736
3737 qguard foo.patch -- -stable (negative guard)
3738 qguard bar.patch +stable (positive guard)
3739 qselect stable
3740
3741 This activates the "stable" guard. mq will skip foo.patch (because
3742 it has a negative match) but push bar.patch (because it has a
3743 positive match).
3744
3745 With no arguments, prints the currently active guards.
3746 With one argument, sets the active guard.
3747
3748 Use -n/--none to deactivate guards (no other arguments needed).
3749 When no guards are active, patches with positive guards are
3750 skipped and patches with negative guards are pushed.
3751
3752 qselect can change the guards on applied patches. It does not pop
3753 guarded patches by default. Use --pop to pop back to the last
3754 applied patch that is not guarded. Use --reapply (which implies
3755 --pop) to push back to the current patch afterwards, but skip
3756 guarded patches.
3757
3758 Use -s/--series to print a list of all guards in the series file
3759 (no other arguments needed). Use -v for more information.
3760
3761 Returns 0 on success."""
3762
3763 q = repo.mq
3764 opts = pycompat.byteskwargs(opts)
3765 guards = q.active()
3766 pushable = lambda i: q.pushable(q.applied[i].name)[0]
3767 if args or opts.get(b'none'):
3768 old_unapplied = q.unapplied(repo)
3769 old_guarded = [i for i in range(len(q.applied)) if not pushable(i)]
3770 q.setactive(args)
3771 q.savedirty()
3772 if not args:
3773 ui.status(_(b'guards deactivated\n'))
3774 if not opts.get(b'pop') and not opts.get(b'reapply'):
3775 unapplied = q.unapplied(repo)
3776 guarded = [i for i in range(len(q.applied)) if not pushable(i)]
3777 if len(unapplied) != len(old_unapplied):
3778 ui.status(
3779 _(
3780 b'number of unguarded, unapplied patches has '
3781 b'changed from %d to %d\n'
3782 )
3783 % (len(old_unapplied), len(unapplied))
3784 )
3785 if len(guarded) != len(old_guarded):
3786 ui.status(
3787 _(
3788 b'number of guarded, applied patches has changed '
3789 b'from %d to %d\n'
3790 )
3791 % (len(old_guarded), len(guarded))
3792 )
3793 elif opts.get(b'series'):
3794 guards = {}
3795 noguards = 0
3796 for gs in q.seriesguards:
3797 if not gs:
3798 noguards += 1
3799 for g in gs:
3800 guards.setdefault(g, 0)
3801 guards[g] += 1
3802 if ui.verbose:
3803 guards[b'NONE'] = noguards
3804 guards = list(guards.items())
3805 guards.sort(key=lambda x: x[0][1:])
3806 if guards:
3807 ui.note(_(b'guards in series file:\n'))
3808 for guard, count in guards:
3809 ui.note(b'%2d ' % count)
3810 ui.write(guard, b'\n')
3811 else:
3812 ui.note(_(b'no guards in series file\n'))
3813 else:
3814 if guards:
3815 ui.note(_(b'active guards:\n'))
3816 for g in guards:
3817 ui.write(g, b'\n')
3818 else:
3819 ui.write(_(b'no active guards\n'))
3820 reapply = opts.get(b'reapply') and q.applied and q.applied[-1].name
3821 popped = False
3822 if opts.get(b'pop') or opts.get(b'reapply'):
3823 for i in range(len(q.applied)):
3824 if not pushable(i):
3825 ui.status(_(b'popping guarded patches\n'))
3826 popped = True
3827 if i == 0:
3828 q.pop(repo, all=True)
3829 else:
3830 q.pop(repo, q.applied[i - 1].name)
3831 break
3832 if popped:
3833 try:
3834 if reapply:
3835 ui.status(_(b'reapplying unguarded patches\n'))
3836 q.push(repo, reapply)
3837 finally:
3838 q.savedirty()
3839
3840
3841 @command(
3842 b"qfinish",
3843 [(b'a', b'applied', None, _(b'finish all applied changesets'))],
3844 _(b'hg qfinish [-a] [REV]...'),
3845 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
3846 )
3847 def finish(ui, repo, *revrange, **opts):
3848 """move applied patches into repository history
3849
3850 Finishes the specified revisions (corresponding to applied
3851 patches) by moving them out of mq control into regular repository
3852 history.
3853
3854 Accepts a revision range or the -a/--applied option. If --applied
3855 is specified, all applied mq revisions are removed from mq
3856 control. Otherwise, the given revisions must be at the base of the
3857 stack of applied patches.
3858
3859 This can be especially useful if your changes have been applied to
3860 an upstream repository, or if you are about to push your changes
3861 to upstream.
3862
3863 Returns 0 on success.
3864 """
3865 if not opts.get('applied') and not revrange:
3866 raise error.Abort(_(b'no revisions specified'))
3867 elif opts.get('applied'):
3868 revrange = (b'qbase::qtip',) + revrange
3869
3870 q = repo.mq
3871 if not q.applied:
3872 ui.status(_(b'no patches applied\n'))
3873 return 0
3874
3875 revs = logcmdutil.revrange(repo, revrange)
3876 if repo[b'.'].rev() in revs and repo[None].files():
3877 ui.warn(_(b'warning: uncommitted changes in the working directory\n'))
3878 # queue.finish may changes phases but leave the responsibility to lock the
3879 # repo to the caller to avoid deadlock with wlock. This command code is
3880 # responsibility for this locking.
3881 with repo.lock():
3882 q.finish(repo, revs)
3883 q.savedirty()
3884 return 0
3885
3886
3887 @command(
3888 b"qqueue",
3889 [
3890 (b'l', b'list', False, _(b'list all available queues')),
3891 (b'', b'active', False, _(b'print name of active queue')),
3892 (b'c', b'create', False, _(b'create new queue')),
3893 (b'', b'rename', False, _(b'rename active queue')),
3894 (b'', b'delete', False, _(b'delete reference to queue')),
3895 (b'', b'purge', False, _(b'delete queue, and remove patch dir')),
3896 ],
3897 _(b'[OPTION] [QUEUE]'),
3898 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
3899 )
3900 def qqueue(ui, repo, name=None, **opts):
3901 """manage multiple patch queues
3902
3903 Supports switching between different patch queues, as well as creating
3904 new patch queues and deleting existing ones.
3905
3906 Omitting a queue name or specifying -l/--list will show you the registered
3907 queues - by default the "normal" patches queue is registered. The currently
3908 active queue will be marked with "(active)". Specifying --active will print
3909 only the name of the active queue.
3910
3911 To create a new queue, use -c/--create. The queue is automatically made
3912 active, except in the case where there are applied patches from the
3913 currently active queue in the repository. Then the queue will only be
3914 created and switching will fail.
3915
3916 To delete an existing queue, use --delete. You cannot delete the currently
3917 active queue.
3918
3919 Returns 0 on success.
3920 """
3921 q = repo.mq
3922 _defaultqueue = b'patches'
3923 _allqueues = b'patches.queues'
3924 _activequeue = b'patches.queue'
3925
3926 def _getcurrent():
3927 cur = os.path.basename(q.path)
3928 if cur.startswith(b'patches-'):
3929 cur = cur[8:]
3930 return cur
3931
3932 def _noqueues():
3933 try:
3934 fh = repo.vfs(_allqueues, b'r')
3935 fh.close()
3936 except OSError:
3937 return True
3938
3939 return False
3940
3941 def _getqueues():
3942 current = _getcurrent()
3943
3944 try:
3945 fh = repo.vfs(_allqueues, b'r')
3946 queues = [queue.strip() for queue in fh if queue.strip()]
3947 fh.close()
3948 if current not in queues:
3949 queues.append(current)
3950 except OSError:
3951 queues = [_defaultqueue]
3952
3953 return sorted(queues)
3954
3955 def _setactive(name):
3956 if q.applied:
3957 raise error.Abort(
3958 _(
3959 b'new queue created, but cannot make active '
3960 b'as patches are applied'
3961 )
3962 )
3963 _setactivenocheck(name)
3964
3965 def _setactivenocheck(name):
3966 fh = repo.vfs(_activequeue, b'w')
3967 if name != b'patches':
3968 fh.write(name)
3969 fh.close()
3970
3971 def _addqueue(name):
3972 fh = repo.vfs(_allqueues, b'a')
3973 fh.write(b'%s\n' % (name,))
3974 fh.close()
3975
3976 def _queuedir(name):
3977 if name == b'patches':
3978 return repo.vfs.join(b'patches')
3979 else:
3980 return repo.vfs.join(b'patches-' + name)
3981
3982 def _validname(name):
3983 for n in name:
3984 if n in b':\\/.':
3985 return False
3986 return True
3987
3988 def _delete(name):
3989 if name not in existing:
3990 raise error.Abort(_(b'cannot delete queue that does not exist'))
3991
3992 current = _getcurrent()
3993
3994 if name == current:
3995 raise error.Abort(_(b'cannot delete currently active queue'))
3996
3997 fh = repo.vfs(b'patches.queues.new', b'w')
3998 for queue in existing:
3999 if queue == name:
4000 continue
4001 fh.write(b'%s\n' % (queue,))
4002 fh.close()
4003 repo.vfs.rename(b'patches.queues.new', _allqueues)
4004
4005 opts = pycompat.byteskwargs(opts)
4006 if not name or opts.get(b'list') or opts.get(b'active'):
4007 current = _getcurrent()
4008 if opts.get(b'active'):
4009 ui.write(b'%s\n' % (current,))
4010 return
4011 for queue in _getqueues():
4012 ui.write(b'%s' % (queue,))
4013 if queue == current and not ui.quiet:
4014 ui.write(_(b' (active)\n'))
4015 else:
4016 ui.write(b'\n')
4017 return
4018
4019 if not _validname(name):
4020 raise error.Abort(
4021 _(b'invalid queue name, may not contain the characters ":\\/."')
4022 )
4023
4024 with repo.wlock():
4025 existing = _getqueues()
4026
4027 if opts.get(b'create'):
4028 if name in existing:
4029 raise error.Abort(_(b'queue "%s" already exists') % name)
4030 if _noqueues():
4031 _addqueue(_defaultqueue)
4032 _addqueue(name)
4033 _setactive(name)
4034 elif opts.get(b'rename'):
4035 current = _getcurrent()
4036 if name == current:
4037 raise error.Abort(
4038 _(b'can\'t rename "%s" to its current name') % name
4039 )
4040 if name in existing:
4041 raise error.Abort(_(b'queue "%s" already exists') % name)
4042
4043 olddir = _queuedir(current)
4044 newdir = _queuedir(name)
4045
4046 if os.path.exists(newdir):
4047 raise error.Abort(
4048 _(b'non-queue directory "%s" already exists') % newdir
4049 )
4050
4051 fh = repo.vfs(b'patches.queues.new', b'w')
4052 for queue in existing:
4053 if queue == current:
4054 fh.write(b'%s\n' % (name,))
4055 if os.path.exists(olddir):
4056 util.rename(olddir, newdir)
4057 else:
4058 fh.write(b'%s\n' % (queue,))
4059 fh.close()
4060 repo.vfs.rename(b'patches.queues.new', _allqueues)
4061 _setactivenocheck(name)
4062 elif opts.get(b'delete'):
4063 _delete(name)
4064 elif opts.get(b'purge'):
4065 if name in existing:
4066 _delete(name)
4067 qdir = _queuedir(name)
4068 if os.path.exists(qdir):
4069 shutil.rmtree(qdir)
4070 else:
4071 if name not in existing:
4072 raise error.Abort(_(b'use --create to create a new queue'))
4073 _setactive(name)
4074
4075
4076 def mqphasedefaults(repo, roots):
4077 """callback used to set mq changeset as secret when no phase data exists"""
4078 if repo.mq.applied:
4079 if repo.ui.configbool(b'mq', b'secret'):
4080 mqphase = phases.secret
4081 else:
4082 mqphase = phases.draft
4083 qbase = repo[repo.mq.applied[0].node]
4084 roots[mqphase].add(qbase.rev())
4085 return roots
4086
4087
4088 def reposetup(ui, repo):
4089 class mqrepo(repo.__class__):
4090 @localrepo.unfilteredpropertycache
4091 def mq(self):
4092 return queue(self.ui, self.baseui, self.path)
4093
4094 def invalidateall(self):
4095 super().invalidateall()
4096 if localrepo.hasunfilteredcache(self, 'mq'):
4097 # recreate mq in case queue path was changed
4098 delattr(self.unfiltered(), 'mq')
4099
4100 def abortifwdirpatched(self, errmsg, force=False):
4101 if self.mq.applied and self.mq.checkapplied and not force:
4102 parents = self.dirstate.parents()
4103 patches = [s.node for s in self.mq.applied]
4104 if any(p in patches for p in parents):
4105 raise error.Abort(errmsg)
4106
4107 def commit(
4108 self,
4109 text=b"",
4110 user=None,
4111 date=None,
4112 match=None,
4113 force=False,
4114 editor=False,
4115 extra=None,
4116 ):
4117 if extra is None:
4118 extra = {}
4119 self.abortifwdirpatched(
4120 _(b'cannot commit over an applied mq patch'), force
4121 )
4122
4123 return super().commit(text, user, date, match, force, editor, extra)
4124
4125 def checkpush(self, pushop):
4126 if self.mq.applied and self.mq.checkapplied and not pushop.force:
4127 outapplied = [e.node for e in self.mq.applied]
4128 if pushop.revs:
4129 # Assume applied patches have no non-patch descendants and
4130 # are not on remote already. Filtering any changeset not
4131 # pushed.
4132 heads = set(pushop.revs)
4133 for node in reversed(outapplied):
4134 if node in heads:
4135 break
4136 else:
4137 outapplied.pop()
4138 # looking for pushed and shared changeset
4139 for node in outapplied:
4140 if self[node].phase() < phases.secret:
4141 raise error.Abort(_(b'source has mq patches applied'))
4142 # no non-secret patches pushed
4143 super().checkpush(pushop)
4144
4145 def _findtags(self):
4146 '''augment tags from base class with patch tags'''
4147 result = super()._findtags()
4148
4149 q = self.mq
4150 if not q.applied:
4151 return result
4152
4153 mqtags = [(patch.node, patch.name) for patch in q.applied]
4154
4155 try:
4156 # for now ignore filtering business
4157 self.unfiltered().changelog.rev(mqtags[-1][0])
4158 except error.LookupError:
4159 self.ui.warn(
4160 _(b'mq status file refers to unknown node %s\n')
4161 % short(mqtags[-1][0])
4162 )
4163 return result
4164
4165 # do not add fake tags for filtered revisions
4166 included = self.changelog.hasnode
4167 mqtags = [mqt for mqt in mqtags if included(mqt[0])]
4168 if not mqtags:
4169 return result
4170
4171 mqtags.append((mqtags[-1][0], b'qtip'))
4172 mqtags.append((mqtags[0][0], b'qbase'))
4173 mqtags.append((self.changelog.parents(mqtags[0][0])[0], b'qparent'))
4174 tags = result[0]
4175 for patch in mqtags:
4176 if patch[1] in tags:
4177 self.ui.warn(
4178 _(b'tag %s overrides mq patch of the same name\n')
4179 % patch[1]
4180 )
4181 else:
4182 tags[patch[1]] = patch[0]
4183
4184 return result
4185
4186 if repo.local():
4187 repo.__class__ = mqrepo
4188
4189 repo._phasedefaults.append(mqphasedefaults)
4190
4191
4192 def mqimport(orig, ui, repo, *args, **kwargs):
4193 if hasattr(repo, 'abortifwdirpatched') and not kwargs.get(
4194 'no_commit', False
4195 ):
4196 repo.abortifwdirpatched(
4197 _(b'cannot import over an applied patch'), kwargs.get('force')
4198 )
4199 return orig(ui, repo, *args, **kwargs)
4200
4201
4202 def mqinit(orig, ui, *args, **kwargs):
4203 mq = kwargs.pop('mq', None)
4204
4205 if not mq:
4206 return orig(ui, *args, **kwargs)
4207
4208 if args:
4209 repopath = args[0]
4210 if not repo_factory.is_local(repopath):
4211 raise error.Abort(
4212 _(b'only a local queue repository may be initialized')
4213 )
4214 else:
4215 repopath = repo_utils.find_repo(encoding.getcwd())
4216 if not repopath:
4217 raise error.Abort(
4218 _(b'there is no Mercurial repository here (.hg not found)')
4219 )
4220 repo = repo_factory.repository(ui, repopath)
4221 return qinit(ui, repo, True)
4222
4223
4224 def mqcommand(orig, ui, repo, *args, **kwargs):
4225 """Add --mq option to operate on patch repository instead of main"""
4226
4227 # some commands do not like getting unknown options
4228 mq = kwargs.pop('mq', None)
4229
4230 if not mq:
4231 return orig(ui, repo, *args, **kwargs)
4232
4233 q = repo.mq
4234 r = q.qrepo()
4235 if not r:
4236 raise error.Abort(_(b'no queue repository'))
4237 return orig(r.ui, r, *args, **kwargs)
4238
4239
4240 def summaryhook(ui, repo):
4241 q = repo.mq
4242 m = []
4243 a, u = len(q.applied), len(q.unapplied(repo))
4244 if a:
4245 m.append(ui.label(_(b"%d applied"), b'qseries.applied') % a)
4246 if u:
4247 m.append(ui.label(_(b"%d unapplied"), b'qseries.unapplied') % u)
4248 if m:
4249 # i18n: column positioning for "hg summary"
4250 ui.write(_(b"mq: %s\n") % b', '.join(m))
4251 else:
4252 # i18n: column positioning for "hg summary"
4253 ui.note(_(b"mq: (empty queue)\n"))
4254
4255
4256 revsetpredicate = registrar.revsetpredicate()
4257
4258
4259 @revsetpredicate(b'mq()')
4260 def revsetmq(repo, subset, x):
4261 """Changesets managed by MQ."""
4262 revsetlang.getargs(x, 0, 0, _(b"mq takes no arguments"))
4263 applied = {repo[r.node].rev() for r in repo.mq.applied}
4264 return smartset.baseset([r for r in subset if r in applied])
4265
4266
4267 # tell hggettext to extract docstrings from these functions:
4268 i18nfunctions = [revsetmq]
4269
4270
4271 def extsetup(ui):
4272 # Ensure mq wrappers are called first, regardless of extension load order by
4273 # NOT wrapping in uisetup() and instead deferring to init stage two here.
4274 mqopt = [(b'', b'mq', None, _(b"operate on patch repository"))]
4275
4276 extensions.wrapcommand(commands.table, b'import', mqimport)
4277 cmdutil.summaryhooks.add(b'mq', summaryhook)
4278
4279 entry = extensions.wrapcommand(commands.table, b'init', mqinit)
4280 entry[1].extend(mqopt)
4281
4282 def dotable(cmdtable):
4283 for cmd, entry in cmdtable.items():
4284 cmd = cmd_finder.parse_aliases(cmd)[0]
4285 func = entry[0]
4286 if func.norepo:
4287 continue
4288 entry = extensions.wrapcommand(cmdtable, cmd, mqcommand)
4289 entry[1].extend(mqopt)
4290
4291 dotable(commands.table)
4292
4293 thismodule = sys.modules["hgext.mq"]
4294 for extname, extmodule in extensions.extensions():
4295 if extmodule != thismodule:
4296 dotable(getattr(extmodule, 'cmdtable', {}))
4297
4298
4299 colortable = {
4300 b'qguard.negative': b'red',
4301 b'qguard.positive': b'yellow',
4302 b'qguard.unguarded': b'green',
4303 b'qseries.applied': b'blue bold underline',
4304 b'qseries.guarded': b'black bold',
4305 b'qseries.missing': b'red bold',
4306 b'qseries.unapplied': b'black bold',
4307 }