##// END OF EJS Templates
cmdutil: fix an uninitialize variable usage in clearunfinished()...
Matt Harbison -
r47731:d9531094 default
parent child Browse files
Show More
@@ -1,3926 +1,3926 b''
1 # cmdutil.py - help for command processing in mercurial
1 # cmdutil.py - help for command processing in mercurial
2 #
2 #
3 # Copyright 2005-2007 Olivia Mackall <olivia@selenic.com>
3 # Copyright 2005-2007 Olivia Mackall <olivia@selenic.com>
4 #
4 #
5 # This software may be used and distributed according to the terms of the
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.
6 # GNU General Public License version 2 or any later version.
7
7
8 from __future__ import absolute_import
8 from __future__ import absolute_import
9
9
10 import copy as copymod
10 import copy as copymod
11 import errno
11 import errno
12 import os
12 import os
13 import re
13 import re
14
14
15 from .i18n import _
15 from .i18n import _
16 from .node import (
16 from .node import (
17 hex,
17 hex,
18 nullid,
18 nullid,
19 nullrev,
19 nullrev,
20 short,
20 short,
21 )
21 )
22 from .pycompat import (
22 from .pycompat import (
23 getattr,
23 getattr,
24 open,
24 open,
25 setattr,
25 setattr,
26 )
26 )
27 from .thirdparty import attr
27 from .thirdparty import attr
28
28
29 from . import (
29 from . import (
30 bookmarks,
30 bookmarks,
31 changelog,
31 changelog,
32 copies,
32 copies,
33 crecord as crecordmod,
33 crecord as crecordmod,
34 dirstateguard,
34 dirstateguard,
35 encoding,
35 encoding,
36 error,
36 error,
37 formatter,
37 formatter,
38 logcmdutil,
38 logcmdutil,
39 match as matchmod,
39 match as matchmod,
40 merge as mergemod,
40 merge as mergemod,
41 mergestate as mergestatemod,
41 mergestate as mergestatemod,
42 mergeutil,
42 mergeutil,
43 obsolete,
43 obsolete,
44 patch,
44 patch,
45 pathutil,
45 pathutil,
46 phases,
46 phases,
47 pycompat,
47 pycompat,
48 repair,
48 repair,
49 revlog,
49 revlog,
50 rewriteutil,
50 rewriteutil,
51 scmutil,
51 scmutil,
52 state as statemod,
52 state as statemod,
53 subrepoutil,
53 subrepoutil,
54 templatekw,
54 templatekw,
55 templater,
55 templater,
56 util,
56 util,
57 vfs as vfsmod,
57 vfs as vfsmod,
58 )
58 )
59
59
60 from .utils import (
60 from .utils import (
61 dateutil,
61 dateutil,
62 stringutil,
62 stringutil,
63 )
63 )
64
64
65 if pycompat.TYPE_CHECKING:
65 if pycompat.TYPE_CHECKING:
66 from typing import (
66 from typing import (
67 Any,
67 Any,
68 Dict,
68 Dict,
69 )
69 )
70
70
71 for t in (Any, Dict):
71 for t in (Any, Dict):
72 assert t
72 assert t
73
73
74 stringio = util.stringio
74 stringio = util.stringio
75
75
76 # templates of common command options
76 # templates of common command options
77
77
78 dryrunopts = [
78 dryrunopts = [
79 (b'n', b'dry-run', None, _(b'do not perform actions, just print output')),
79 (b'n', b'dry-run', None, _(b'do not perform actions, just print output')),
80 ]
80 ]
81
81
82 confirmopts = [
82 confirmopts = [
83 (b'', b'confirm', None, _(b'ask before applying actions')),
83 (b'', b'confirm', None, _(b'ask before applying actions')),
84 ]
84 ]
85
85
86 remoteopts = [
86 remoteopts = [
87 (b'e', b'ssh', b'', _(b'specify ssh command to use'), _(b'CMD')),
87 (b'e', b'ssh', b'', _(b'specify ssh command to use'), _(b'CMD')),
88 (
88 (
89 b'',
89 b'',
90 b'remotecmd',
90 b'remotecmd',
91 b'',
91 b'',
92 _(b'specify hg command to run on the remote side'),
92 _(b'specify hg command to run on the remote side'),
93 _(b'CMD'),
93 _(b'CMD'),
94 ),
94 ),
95 (
95 (
96 b'',
96 b'',
97 b'insecure',
97 b'insecure',
98 None,
98 None,
99 _(b'do not verify server certificate (ignoring web.cacerts config)'),
99 _(b'do not verify server certificate (ignoring web.cacerts config)'),
100 ),
100 ),
101 ]
101 ]
102
102
103 walkopts = [
103 walkopts = [
104 (
104 (
105 b'I',
105 b'I',
106 b'include',
106 b'include',
107 [],
107 [],
108 _(b'include names matching the given patterns'),
108 _(b'include names matching the given patterns'),
109 _(b'PATTERN'),
109 _(b'PATTERN'),
110 ),
110 ),
111 (
111 (
112 b'X',
112 b'X',
113 b'exclude',
113 b'exclude',
114 [],
114 [],
115 _(b'exclude names matching the given patterns'),
115 _(b'exclude names matching the given patterns'),
116 _(b'PATTERN'),
116 _(b'PATTERN'),
117 ),
117 ),
118 ]
118 ]
119
119
120 commitopts = [
120 commitopts = [
121 (b'm', b'message', b'', _(b'use text as commit message'), _(b'TEXT')),
121 (b'm', b'message', b'', _(b'use text as commit message'), _(b'TEXT')),
122 (b'l', b'logfile', b'', _(b'read commit message from file'), _(b'FILE')),
122 (b'l', b'logfile', b'', _(b'read commit message from file'), _(b'FILE')),
123 ]
123 ]
124
124
125 commitopts2 = [
125 commitopts2 = [
126 (
126 (
127 b'd',
127 b'd',
128 b'date',
128 b'date',
129 b'',
129 b'',
130 _(b'record the specified date as commit date'),
130 _(b'record the specified date as commit date'),
131 _(b'DATE'),
131 _(b'DATE'),
132 ),
132 ),
133 (
133 (
134 b'u',
134 b'u',
135 b'user',
135 b'user',
136 b'',
136 b'',
137 _(b'record the specified user as committer'),
137 _(b'record the specified user as committer'),
138 _(b'USER'),
138 _(b'USER'),
139 ),
139 ),
140 ]
140 ]
141
141
142 commitopts3 = [
142 commitopts3 = [
143 (b'D', b'currentdate', None, _(b'record the current date as commit date')),
143 (b'D', b'currentdate', None, _(b'record the current date as commit date')),
144 (b'U', b'currentuser', None, _(b'record the current user as committer')),
144 (b'U', b'currentuser', None, _(b'record the current user as committer')),
145 ]
145 ]
146
146
147 formatteropts = [
147 formatteropts = [
148 (b'T', b'template', b'', _(b'display with template'), _(b'TEMPLATE')),
148 (b'T', b'template', b'', _(b'display with template'), _(b'TEMPLATE')),
149 ]
149 ]
150
150
151 templateopts = [
151 templateopts = [
152 (
152 (
153 b'',
153 b'',
154 b'style',
154 b'style',
155 b'',
155 b'',
156 _(b'display using template map file (DEPRECATED)'),
156 _(b'display using template map file (DEPRECATED)'),
157 _(b'STYLE'),
157 _(b'STYLE'),
158 ),
158 ),
159 (b'T', b'template', b'', _(b'display with template'), _(b'TEMPLATE')),
159 (b'T', b'template', b'', _(b'display with template'), _(b'TEMPLATE')),
160 ]
160 ]
161
161
162 logopts = [
162 logopts = [
163 (b'p', b'patch', None, _(b'show patch')),
163 (b'p', b'patch', None, _(b'show patch')),
164 (b'g', b'git', None, _(b'use git extended diff format')),
164 (b'g', b'git', None, _(b'use git extended diff format')),
165 (b'l', b'limit', b'', _(b'limit number of changes displayed'), _(b'NUM')),
165 (b'l', b'limit', b'', _(b'limit number of changes displayed'), _(b'NUM')),
166 (b'M', b'no-merges', None, _(b'do not show merges')),
166 (b'M', b'no-merges', None, _(b'do not show merges')),
167 (b'', b'stat', None, _(b'output diffstat-style summary of changes')),
167 (b'', b'stat', None, _(b'output diffstat-style summary of changes')),
168 (b'G', b'graph', None, _(b"show the revision DAG")),
168 (b'G', b'graph', None, _(b"show the revision DAG")),
169 ] + templateopts
169 ] + templateopts
170
170
171 diffopts = [
171 diffopts = [
172 (b'a', b'text', None, _(b'treat all files as text')),
172 (b'a', b'text', None, _(b'treat all files as text')),
173 (
173 (
174 b'g',
174 b'g',
175 b'git',
175 b'git',
176 None,
176 None,
177 _(b'use git extended diff format (DEFAULT: diff.git)'),
177 _(b'use git extended diff format (DEFAULT: diff.git)'),
178 ),
178 ),
179 (b'', b'binary', None, _(b'generate binary diffs in git mode (default)')),
179 (b'', b'binary', None, _(b'generate binary diffs in git mode (default)')),
180 (b'', b'nodates', None, _(b'omit dates from diff headers')),
180 (b'', b'nodates', None, _(b'omit dates from diff headers')),
181 ]
181 ]
182
182
183 diffwsopts = [
183 diffwsopts = [
184 (
184 (
185 b'w',
185 b'w',
186 b'ignore-all-space',
186 b'ignore-all-space',
187 None,
187 None,
188 _(b'ignore white space when comparing lines'),
188 _(b'ignore white space when comparing lines'),
189 ),
189 ),
190 (
190 (
191 b'b',
191 b'b',
192 b'ignore-space-change',
192 b'ignore-space-change',
193 None,
193 None,
194 _(b'ignore changes in the amount of white space'),
194 _(b'ignore changes in the amount of white space'),
195 ),
195 ),
196 (
196 (
197 b'B',
197 b'B',
198 b'ignore-blank-lines',
198 b'ignore-blank-lines',
199 None,
199 None,
200 _(b'ignore changes whose lines are all blank'),
200 _(b'ignore changes whose lines are all blank'),
201 ),
201 ),
202 (
202 (
203 b'Z',
203 b'Z',
204 b'ignore-space-at-eol',
204 b'ignore-space-at-eol',
205 None,
205 None,
206 _(b'ignore changes in whitespace at EOL'),
206 _(b'ignore changes in whitespace at EOL'),
207 ),
207 ),
208 ]
208 ]
209
209
210 diffopts2 = (
210 diffopts2 = (
211 [
211 [
212 (b'', b'noprefix', None, _(b'omit a/ and b/ prefixes from filenames')),
212 (b'', b'noprefix', None, _(b'omit a/ and b/ prefixes from filenames')),
213 (
213 (
214 b'p',
214 b'p',
215 b'show-function',
215 b'show-function',
216 None,
216 None,
217 _(
217 _(
218 b'show which function each change is in (DEFAULT: diff.showfunc)'
218 b'show which function each change is in (DEFAULT: diff.showfunc)'
219 ),
219 ),
220 ),
220 ),
221 (b'', b'reverse', None, _(b'produce a diff that undoes the changes')),
221 (b'', b'reverse', None, _(b'produce a diff that undoes the changes')),
222 ]
222 ]
223 + diffwsopts
223 + diffwsopts
224 + [
224 + [
225 (
225 (
226 b'U',
226 b'U',
227 b'unified',
227 b'unified',
228 b'',
228 b'',
229 _(b'number of lines of context to show'),
229 _(b'number of lines of context to show'),
230 _(b'NUM'),
230 _(b'NUM'),
231 ),
231 ),
232 (b'', b'stat', None, _(b'output diffstat-style summary of changes')),
232 (b'', b'stat', None, _(b'output diffstat-style summary of changes')),
233 (
233 (
234 b'',
234 b'',
235 b'root',
235 b'root',
236 b'',
236 b'',
237 _(b'produce diffs relative to subdirectory'),
237 _(b'produce diffs relative to subdirectory'),
238 _(b'DIR'),
238 _(b'DIR'),
239 ),
239 ),
240 ]
240 ]
241 )
241 )
242
242
243 mergetoolopts = [
243 mergetoolopts = [
244 (b't', b'tool', b'', _(b'specify merge tool'), _(b'TOOL')),
244 (b't', b'tool', b'', _(b'specify merge tool'), _(b'TOOL')),
245 ]
245 ]
246
246
247 similarityopts = [
247 similarityopts = [
248 (
248 (
249 b's',
249 b's',
250 b'similarity',
250 b'similarity',
251 b'',
251 b'',
252 _(b'guess renamed files by similarity (0<=s<=100)'),
252 _(b'guess renamed files by similarity (0<=s<=100)'),
253 _(b'SIMILARITY'),
253 _(b'SIMILARITY'),
254 )
254 )
255 ]
255 ]
256
256
257 subrepoopts = [(b'S', b'subrepos', None, _(b'recurse into subrepositories'))]
257 subrepoopts = [(b'S', b'subrepos', None, _(b'recurse into subrepositories'))]
258
258
259 debugrevlogopts = [
259 debugrevlogopts = [
260 (b'c', b'changelog', False, _(b'open changelog')),
260 (b'c', b'changelog', False, _(b'open changelog')),
261 (b'm', b'manifest', False, _(b'open manifest')),
261 (b'm', b'manifest', False, _(b'open manifest')),
262 (b'', b'dir', b'', _(b'open directory manifest')),
262 (b'', b'dir', b'', _(b'open directory manifest')),
263 ]
263 ]
264
264
265 # special string such that everything below this line will be ingored in the
265 # special string such that everything below this line will be ingored in the
266 # editor text
266 # editor text
267 _linebelow = b"^HG: ------------------------ >8 ------------------------$"
267 _linebelow = b"^HG: ------------------------ >8 ------------------------$"
268
268
269
269
270 def check_at_most_one_arg(opts, *args):
270 def check_at_most_one_arg(opts, *args):
271 """abort if more than one of the arguments are in opts
271 """abort if more than one of the arguments are in opts
272
272
273 Returns the unique argument or None if none of them were specified.
273 Returns the unique argument or None if none of them were specified.
274 """
274 """
275
275
276 def to_display(name):
276 def to_display(name):
277 return pycompat.sysbytes(name).replace(b'_', b'-')
277 return pycompat.sysbytes(name).replace(b'_', b'-')
278
278
279 previous = None
279 previous = None
280 for x in args:
280 for x in args:
281 if opts.get(x):
281 if opts.get(x):
282 if previous:
282 if previous:
283 raise error.InputError(
283 raise error.InputError(
284 _(b'cannot specify both --%s and --%s')
284 _(b'cannot specify both --%s and --%s')
285 % (to_display(previous), to_display(x))
285 % (to_display(previous), to_display(x))
286 )
286 )
287 previous = x
287 previous = x
288 return previous
288 return previous
289
289
290
290
291 def check_incompatible_arguments(opts, first, others):
291 def check_incompatible_arguments(opts, first, others):
292 """abort if the first argument is given along with any of the others
292 """abort if the first argument is given along with any of the others
293
293
294 Unlike check_at_most_one_arg(), `others` are not mutually exclusive
294 Unlike check_at_most_one_arg(), `others` are not mutually exclusive
295 among themselves, and they're passed as a single collection.
295 among themselves, and they're passed as a single collection.
296 """
296 """
297 for other in others:
297 for other in others:
298 check_at_most_one_arg(opts, first, other)
298 check_at_most_one_arg(opts, first, other)
299
299
300
300
301 def resolvecommitoptions(ui, opts):
301 def resolvecommitoptions(ui, opts):
302 """modify commit options dict to handle related options
302 """modify commit options dict to handle related options
303
303
304 The return value indicates that ``rewrite.update-timestamp`` is the reason
304 The return value indicates that ``rewrite.update-timestamp`` is the reason
305 the ``date`` option is set.
305 the ``date`` option is set.
306 """
306 """
307 check_at_most_one_arg(opts, b'date', b'currentdate')
307 check_at_most_one_arg(opts, b'date', b'currentdate')
308 check_at_most_one_arg(opts, b'user', b'currentuser')
308 check_at_most_one_arg(opts, b'user', b'currentuser')
309
309
310 datemaydiffer = False # date-only change should be ignored?
310 datemaydiffer = False # date-only change should be ignored?
311
311
312 if opts.get(b'currentdate'):
312 if opts.get(b'currentdate'):
313 opts[b'date'] = b'%d %d' % dateutil.makedate()
313 opts[b'date'] = b'%d %d' % dateutil.makedate()
314 elif (
314 elif (
315 not opts.get(b'date')
315 not opts.get(b'date')
316 and ui.configbool(b'rewrite', b'update-timestamp')
316 and ui.configbool(b'rewrite', b'update-timestamp')
317 and opts.get(b'currentdate') is None
317 and opts.get(b'currentdate') is None
318 ):
318 ):
319 opts[b'date'] = b'%d %d' % dateutil.makedate()
319 opts[b'date'] = b'%d %d' % dateutil.makedate()
320 datemaydiffer = True
320 datemaydiffer = True
321
321
322 if opts.get(b'currentuser'):
322 if opts.get(b'currentuser'):
323 opts[b'user'] = ui.username()
323 opts[b'user'] = ui.username()
324
324
325 return datemaydiffer
325 return datemaydiffer
326
326
327
327
328 def checknotesize(ui, opts):
328 def checknotesize(ui, opts):
329 """ make sure note is of valid format """
329 """ make sure note is of valid format """
330
330
331 note = opts.get(b'note')
331 note = opts.get(b'note')
332 if not note:
332 if not note:
333 return
333 return
334
334
335 if len(note) > 255:
335 if len(note) > 255:
336 raise error.InputError(_(b"cannot store a note of more than 255 bytes"))
336 raise error.InputError(_(b"cannot store a note of more than 255 bytes"))
337 if b'\n' in note:
337 if b'\n' in note:
338 raise error.InputError(_(b"note cannot contain a newline"))
338 raise error.InputError(_(b"note cannot contain a newline"))
339
339
340
340
341 def ishunk(x):
341 def ishunk(x):
342 hunkclasses = (crecordmod.uihunk, patch.recordhunk)
342 hunkclasses = (crecordmod.uihunk, patch.recordhunk)
343 return isinstance(x, hunkclasses)
343 return isinstance(x, hunkclasses)
344
344
345
345
346 def newandmodified(chunks, originalchunks):
346 def newandmodified(chunks, originalchunks):
347 newlyaddedandmodifiedfiles = set()
347 newlyaddedandmodifiedfiles = set()
348 alsorestore = set()
348 alsorestore = set()
349 for chunk in chunks:
349 for chunk in chunks:
350 if (
350 if (
351 ishunk(chunk)
351 ishunk(chunk)
352 and chunk.header.isnewfile()
352 and chunk.header.isnewfile()
353 and chunk not in originalchunks
353 and chunk not in originalchunks
354 ):
354 ):
355 newlyaddedandmodifiedfiles.add(chunk.header.filename())
355 newlyaddedandmodifiedfiles.add(chunk.header.filename())
356 alsorestore.update(
356 alsorestore.update(
357 set(chunk.header.files()) - {chunk.header.filename()}
357 set(chunk.header.files()) - {chunk.header.filename()}
358 )
358 )
359 return newlyaddedandmodifiedfiles, alsorestore
359 return newlyaddedandmodifiedfiles, alsorestore
360
360
361
361
362 def parsealiases(cmd):
362 def parsealiases(cmd):
363 base_aliases = cmd.split(b"|")
363 base_aliases = cmd.split(b"|")
364 all_aliases = set(base_aliases)
364 all_aliases = set(base_aliases)
365 extra_aliases = []
365 extra_aliases = []
366 for alias in base_aliases:
366 for alias in base_aliases:
367 if b'-' in alias:
367 if b'-' in alias:
368 folded_alias = alias.replace(b'-', b'')
368 folded_alias = alias.replace(b'-', b'')
369 if folded_alias not in all_aliases:
369 if folded_alias not in all_aliases:
370 all_aliases.add(folded_alias)
370 all_aliases.add(folded_alias)
371 extra_aliases.append(folded_alias)
371 extra_aliases.append(folded_alias)
372 base_aliases.extend(extra_aliases)
372 base_aliases.extend(extra_aliases)
373 return base_aliases
373 return base_aliases
374
374
375
375
376 def setupwrapcolorwrite(ui):
376 def setupwrapcolorwrite(ui):
377 # wrap ui.write so diff output can be labeled/colorized
377 # wrap ui.write so diff output can be labeled/colorized
378 def wrapwrite(orig, *args, **kw):
378 def wrapwrite(orig, *args, **kw):
379 label = kw.pop('label', b'')
379 label = kw.pop('label', b'')
380 for chunk, l in patch.difflabel(lambda: args):
380 for chunk, l in patch.difflabel(lambda: args):
381 orig(chunk, label=label + l)
381 orig(chunk, label=label + l)
382
382
383 oldwrite = ui.write
383 oldwrite = ui.write
384
384
385 def wrap(*args, **kwargs):
385 def wrap(*args, **kwargs):
386 return wrapwrite(oldwrite, *args, **kwargs)
386 return wrapwrite(oldwrite, *args, **kwargs)
387
387
388 setattr(ui, 'write', wrap)
388 setattr(ui, 'write', wrap)
389 return oldwrite
389 return oldwrite
390
390
391
391
392 def filterchunks(ui, originalhunks, usecurses, testfile, match, operation=None):
392 def filterchunks(ui, originalhunks, usecurses, testfile, match, operation=None):
393 try:
393 try:
394 if usecurses:
394 if usecurses:
395 if testfile:
395 if testfile:
396 recordfn = crecordmod.testdecorator(
396 recordfn = crecordmod.testdecorator(
397 testfile, crecordmod.testchunkselector
397 testfile, crecordmod.testchunkselector
398 )
398 )
399 else:
399 else:
400 recordfn = crecordmod.chunkselector
400 recordfn = crecordmod.chunkselector
401
401
402 return crecordmod.filterpatch(
402 return crecordmod.filterpatch(
403 ui, originalhunks, recordfn, operation
403 ui, originalhunks, recordfn, operation
404 )
404 )
405 except crecordmod.fallbackerror as e:
405 except crecordmod.fallbackerror as e:
406 ui.warn(b'%s\n' % e)
406 ui.warn(b'%s\n' % e)
407 ui.warn(_(b'falling back to text mode\n'))
407 ui.warn(_(b'falling back to text mode\n'))
408
408
409 return patch.filterpatch(ui, originalhunks, match, operation)
409 return patch.filterpatch(ui, originalhunks, match, operation)
410
410
411
411
412 def recordfilter(ui, originalhunks, match, operation=None):
412 def recordfilter(ui, originalhunks, match, operation=None):
413 """Prompts the user to filter the originalhunks and return a list of
413 """Prompts the user to filter the originalhunks and return a list of
414 selected hunks.
414 selected hunks.
415 *operation* is used for to build ui messages to indicate the user what
415 *operation* is used for to build ui messages to indicate the user what
416 kind of filtering they are doing: reverting, committing, shelving, etc.
416 kind of filtering they are doing: reverting, committing, shelving, etc.
417 (see patch.filterpatch).
417 (see patch.filterpatch).
418 """
418 """
419 usecurses = crecordmod.checkcurses(ui)
419 usecurses = crecordmod.checkcurses(ui)
420 testfile = ui.config(b'experimental', b'crecordtest')
420 testfile = ui.config(b'experimental', b'crecordtest')
421 oldwrite = setupwrapcolorwrite(ui)
421 oldwrite = setupwrapcolorwrite(ui)
422 try:
422 try:
423 newchunks, newopts = filterchunks(
423 newchunks, newopts = filterchunks(
424 ui, originalhunks, usecurses, testfile, match, operation
424 ui, originalhunks, usecurses, testfile, match, operation
425 )
425 )
426 finally:
426 finally:
427 ui.write = oldwrite
427 ui.write = oldwrite
428 return newchunks, newopts
428 return newchunks, newopts
429
429
430
430
431 def dorecord(
431 def dorecord(
432 ui, repo, commitfunc, cmdsuggest, backupall, filterfn, *pats, **opts
432 ui, repo, commitfunc, cmdsuggest, backupall, filterfn, *pats, **opts
433 ):
433 ):
434 opts = pycompat.byteskwargs(opts)
434 opts = pycompat.byteskwargs(opts)
435 if not ui.interactive():
435 if not ui.interactive():
436 if cmdsuggest:
436 if cmdsuggest:
437 msg = _(b'running non-interactively, use %s instead') % cmdsuggest
437 msg = _(b'running non-interactively, use %s instead') % cmdsuggest
438 else:
438 else:
439 msg = _(b'running non-interactively')
439 msg = _(b'running non-interactively')
440 raise error.InputError(msg)
440 raise error.InputError(msg)
441
441
442 # make sure username is set before going interactive
442 # make sure username is set before going interactive
443 if not opts.get(b'user'):
443 if not opts.get(b'user'):
444 ui.username() # raise exception, username not provided
444 ui.username() # raise exception, username not provided
445
445
446 def recordfunc(ui, repo, message, match, opts):
446 def recordfunc(ui, repo, message, match, opts):
447 """This is generic record driver.
447 """This is generic record driver.
448
448
449 Its job is to interactively filter local changes, and
449 Its job is to interactively filter local changes, and
450 accordingly prepare working directory into a state in which the
450 accordingly prepare working directory into a state in which the
451 job can be delegated to a non-interactive commit command such as
451 job can be delegated to a non-interactive commit command such as
452 'commit' or 'qrefresh'.
452 'commit' or 'qrefresh'.
453
453
454 After the actual job is done by non-interactive command, the
454 After the actual job is done by non-interactive command, the
455 working directory is restored to its original state.
455 working directory is restored to its original state.
456
456
457 In the end we'll record interesting changes, and everything else
457 In the end we'll record interesting changes, and everything else
458 will be left in place, so the user can continue working.
458 will be left in place, so the user can continue working.
459 """
459 """
460 if not opts.get(b'interactive-unshelve'):
460 if not opts.get(b'interactive-unshelve'):
461 checkunfinished(repo, commit=True)
461 checkunfinished(repo, commit=True)
462 wctx = repo[None]
462 wctx = repo[None]
463 merge = len(wctx.parents()) > 1
463 merge = len(wctx.parents()) > 1
464 if merge:
464 if merge:
465 raise error.InputError(
465 raise error.InputError(
466 _(
466 _(
467 b'cannot partially commit a merge '
467 b'cannot partially commit a merge '
468 b'(use "hg commit" instead)'
468 b'(use "hg commit" instead)'
469 )
469 )
470 )
470 )
471
471
472 def fail(f, msg):
472 def fail(f, msg):
473 raise error.InputError(b'%s: %s' % (f, msg))
473 raise error.InputError(b'%s: %s' % (f, msg))
474
474
475 force = opts.get(b'force')
475 force = opts.get(b'force')
476 if not force:
476 if not force:
477 match = matchmod.badmatch(match, fail)
477 match = matchmod.badmatch(match, fail)
478
478
479 status = repo.status(match=match)
479 status = repo.status(match=match)
480
480
481 overrides = {(b'ui', b'commitsubrepos'): True}
481 overrides = {(b'ui', b'commitsubrepos'): True}
482
482
483 with repo.ui.configoverride(overrides, b'record'):
483 with repo.ui.configoverride(overrides, b'record'):
484 # subrepoutil.precommit() modifies the status
484 # subrepoutil.precommit() modifies the status
485 tmpstatus = scmutil.status(
485 tmpstatus = scmutil.status(
486 copymod.copy(status.modified),
486 copymod.copy(status.modified),
487 copymod.copy(status.added),
487 copymod.copy(status.added),
488 copymod.copy(status.removed),
488 copymod.copy(status.removed),
489 copymod.copy(status.deleted),
489 copymod.copy(status.deleted),
490 copymod.copy(status.unknown),
490 copymod.copy(status.unknown),
491 copymod.copy(status.ignored),
491 copymod.copy(status.ignored),
492 copymod.copy(status.clean), # pytype: disable=wrong-arg-count
492 copymod.copy(status.clean), # pytype: disable=wrong-arg-count
493 )
493 )
494
494
495 # Force allows -X subrepo to skip the subrepo.
495 # Force allows -X subrepo to skip the subrepo.
496 subs, commitsubs, newstate = subrepoutil.precommit(
496 subs, commitsubs, newstate = subrepoutil.precommit(
497 repo.ui, wctx, tmpstatus, match, force=True
497 repo.ui, wctx, tmpstatus, match, force=True
498 )
498 )
499 for s in subs:
499 for s in subs:
500 if s in commitsubs:
500 if s in commitsubs:
501 dirtyreason = wctx.sub(s).dirtyreason(True)
501 dirtyreason = wctx.sub(s).dirtyreason(True)
502 raise error.Abort(dirtyreason)
502 raise error.Abort(dirtyreason)
503
503
504 if not force:
504 if not force:
505 repo.checkcommitpatterns(wctx, match, status, fail)
505 repo.checkcommitpatterns(wctx, match, status, fail)
506 diffopts = patch.difffeatureopts(
506 diffopts = patch.difffeatureopts(
507 ui,
507 ui,
508 opts=opts,
508 opts=opts,
509 whitespace=True,
509 whitespace=True,
510 section=b'commands',
510 section=b'commands',
511 configprefix=b'commit.interactive.',
511 configprefix=b'commit.interactive.',
512 )
512 )
513 diffopts.nodates = True
513 diffopts.nodates = True
514 diffopts.git = True
514 diffopts.git = True
515 diffopts.showfunc = True
515 diffopts.showfunc = True
516 originaldiff = patch.diff(repo, changes=status, opts=diffopts)
516 originaldiff = patch.diff(repo, changes=status, opts=diffopts)
517 originalchunks = patch.parsepatch(originaldiff)
517 originalchunks = patch.parsepatch(originaldiff)
518 match = scmutil.match(repo[None], pats)
518 match = scmutil.match(repo[None], pats)
519
519
520 # 1. filter patch, since we are intending to apply subset of it
520 # 1. filter patch, since we are intending to apply subset of it
521 try:
521 try:
522 chunks, newopts = filterfn(ui, originalchunks, match)
522 chunks, newopts = filterfn(ui, originalchunks, match)
523 except error.PatchError as err:
523 except error.PatchError as err:
524 raise error.InputError(_(b'error parsing patch: %s') % err)
524 raise error.InputError(_(b'error parsing patch: %s') % err)
525 opts.update(newopts)
525 opts.update(newopts)
526
526
527 # We need to keep a backup of files that have been newly added and
527 # We need to keep a backup of files that have been newly added and
528 # modified during the recording process because there is a previous
528 # modified during the recording process because there is a previous
529 # version without the edit in the workdir. We also will need to restore
529 # version without the edit in the workdir. We also will need to restore
530 # files that were the sources of renames so that the patch application
530 # files that were the sources of renames so that the patch application
531 # works.
531 # works.
532 newlyaddedandmodifiedfiles, alsorestore = newandmodified(
532 newlyaddedandmodifiedfiles, alsorestore = newandmodified(
533 chunks, originalchunks
533 chunks, originalchunks
534 )
534 )
535 contenders = set()
535 contenders = set()
536 for h in chunks:
536 for h in chunks:
537 try:
537 try:
538 contenders.update(set(h.files()))
538 contenders.update(set(h.files()))
539 except AttributeError:
539 except AttributeError:
540 pass
540 pass
541
541
542 changed = status.modified + status.added + status.removed
542 changed = status.modified + status.added + status.removed
543 newfiles = [f for f in changed if f in contenders]
543 newfiles = [f for f in changed if f in contenders]
544 if not newfiles:
544 if not newfiles:
545 ui.status(_(b'no changes to record\n'))
545 ui.status(_(b'no changes to record\n'))
546 return 0
546 return 0
547
547
548 modified = set(status.modified)
548 modified = set(status.modified)
549
549
550 # 2. backup changed files, so we can restore them in the end
550 # 2. backup changed files, so we can restore them in the end
551
551
552 if backupall:
552 if backupall:
553 tobackup = changed
553 tobackup = changed
554 else:
554 else:
555 tobackup = [
555 tobackup = [
556 f
556 f
557 for f in newfiles
557 for f in newfiles
558 if f in modified or f in newlyaddedandmodifiedfiles
558 if f in modified or f in newlyaddedandmodifiedfiles
559 ]
559 ]
560 backups = {}
560 backups = {}
561 if tobackup:
561 if tobackup:
562 backupdir = repo.vfs.join(b'record-backups')
562 backupdir = repo.vfs.join(b'record-backups')
563 try:
563 try:
564 os.mkdir(backupdir)
564 os.mkdir(backupdir)
565 except OSError as err:
565 except OSError as err:
566 if err.errno != errno.EEXIST:
566 if err.errno != errno.EEXIST:
567 raise
567 raise
568 try:
568 try:
569 # backup continues
569 # backup continues
570 for f in tobackup:
570 for f in tobackup:
571 fd, tmpname = pycompat.mkstemp(
571 fd, tmpname = pycompat.mkstemp(
572 prefix=os.path.basename(f) + b'.', dir=backupdir
572 prefix=os.path.basename(f) + b'.', dir=backupdir
573 )
573 )
574 os.close(fd)
574 os.close(fd)
575 ui.debug(b'backup %r as %r\n' % (f, tmpname))
575 ui.debug(b'backup %r as %r\n' % (f, tmpname))
576 util.copyfile(repo.wjoin(f), tmpname, copystat=True)
576 util.copyfile(repo.wjoin(f), tmpname, copystat=True)
577 backups[f] = tmpname
577 backups[f] = tmpname
578
578
579 fp = stringio()
579 fp = stringio()
580 for c in chunks:
580 for c in chunks:
581 fname = c.filename()
581 fname = c.filename()
582 if fname in backups:
582 if fname in backups:
583 c.write(fp)
583 c.write(fp)
584 dopatch = fp.tell()
584 dopatch = fp.tell()
585 fp.seek(0)
585 fp.seek(0)
586
586
587 # 2.5 optionally review / modify patch in text editor
587 # 2.5 optionally review / modify patch in text editor
588 if opts.get(b'review', False):
588 if opts.get(b'review', False):
589 patchtext = (
589 patchtext = (
590 crecordmod.diffhelptext
590 crecordmod.diffhelptext
591 + crecordmod.patchhelptext
591 + crecordmod.patchhelptext
592 + fp.read()
592 + fp.read()
593 )
593 )
594 reviewedpatch = ui.edit(
594 reviewedpatch = ui.edit(
595 patchtext, b"", action=b"diff", repopath=repo.path
595 patchtext, b"", action=b"diff", repopath=repo.path
596 )
596 )
597 fp.truncate(0)
597 fp.truncate(0)
598 fp.write(reviewedpatch)
598 fp.write(reviewedpatch)
599 fp.seek(0)
599 fp.seek(0)
600
600
601 [os.unlink(repo.wjoin(c)) for c in newlyaddedandmodifiedfiles]
601 [os.unlink(repo.wjoin(c)) for c in newlyaddedandmodifiedfiles]
602 # 3a. apply filtered patch to clean repo (clean)
602 # 3a. apply filtered patch to clean repo (clean)
603 if backups:
603 if backups:
604 m = scmutil.matchfiles(repo, set(backups.keys()) | alsorestore)
604 m = scmutil.matchfiles(repo, set(backups.keys()) | alsorestore)
605 mergemod.revert_to(repo[b'.'], matcher=m)
605 mergemod.revert_to(repo[b'.'], matcher=m)
606
606
607 # 3b. (apply)
607 # 3b. (apply)
608 if dopatch:
608 if dopatch:
609 try:
609 try:
610 ui.debug(b'applying patch\n')
610 ui.debug(b'applying patch\n')
611 ui.debug(fp.getvalue())
611 ui.debug(fp.getvalue())
612 patch.internalpatch(ui, repo, fp, 1, eolmode=None)
612 patch.internalpatch(ui, repo, fp, 1, eolmode=None)
613 except error.PatchError as err:
613 except error.PatchError as err:
614 raise error.InputError(pycompat.bytestr(err))
614 raise error.InputError(pycompat.bytestr(err))
615 del fp
615 del fp
616
616
617 # 4. We prepared working directory according to filtered
617 # 4. We prepared working directory according to filtered
618 # patch. Now is the time to delegate the job to
618 # patch. Now is the time to delegate the job to
619 # commit/qrefresh or the like!
619 # commit/qrefresh or the like!
620
620
621 # Make all of the pathnames absolute.
621 # Make all of the pathnames absolute.
622 newfiles = [repo.wjoin(nf) for nf in newfiles]
622 newfiles = [repo.wjoin(nf) for nf in newfiles]
623 return commitfunc(ui, repo, *newfiles, **pycompat.strkwargs(opts))
623 return commitfunc(ui, repo, *newfiles, **pycompat.strkwargs(opts))
624 finally:
624 finally:
625 # 5. finally restore backed-up files
625 # 5. finally restore backed-up files
626 try:
626 try:
627 dirstate = repo.dirstate
627 dirstate = repo.dirstate
628 for realname, tmpname in pycompat.iteritems(backups):
628 for realname, tmpname in pycompat.iteritems(backups):
629 ui.debug(b'restoring %r to %r\n' % (tmpname, realname))
629 ui.debug(b'restoring %r to %r\n' % (tmpname, realname))
630
630
631 if dirstate[realname] == b'n':
631 if dirstate[realname] == b'n':
632 # without normallookup, restoring timestamp
632 # without normallookup, restoring timestamp
633 # may cause partially committed files
633 # may cause partially committed files
634 # to be treated as unmodified
634 # to be treated as unmodified
635 dirstate.normallookup(realname)
635 dirstate.normallookup(realname)
636
636
637 # copystat=True here and above are a hack to trick any
637 # copystat=True here and above are a hack to trick any
638 # editors that have f open that we haven't modified them.
638 # editors that have f open that we haven't modified them.
639 #
639 #
640 # Also note that this racy as an editor could notice the
640 # Also note that this racy as an editor could notice the
641 # file's mtime before we've finished writing it.
641 # file's mtime before we've finished writing it.
642 util.copyfile(tmpname, repo.wjoin(realname), copystat=True)
642 util.copyfile(tmpname, repo.wjoin(realname), copystat=True)
643 os.unlink(tmpname)
643 os.unlink(tmpname)
644 if tobackup:
644 if tobackup:
645 os.rmdir(backupdir)
645 os.rmdir(backupdir)
646 except OSError:
646 except OSError:
647 pass
647 pass
648
648
649 def recordinwlock(ui, repo, message, match, opts):
649 def recordinwlock(ui, repo, message, match, opts):
650 with repo.wlock():
650 with repo.wlock():
651 return recordfunc(ui, repo, message, match, opts)
651 return recordfunc(ui, repo, message, match, opts)
652
652
653 return commit(ui, repo, recordinwlock, pats, opts)
653 return commit(ui, repo, recordinwlock, pats, opts)
654
654
655
655
656 class dirnode(object):
656 class dirnode(object):
657 """
657 """
658 Represent a directory in user working copy with information required for
658 Represent a directory in user working copy with information required for
659 the purpose of tersing its status.
659 the purpose of tersing its status.
660
660
661 path is the path to the directory, without a trailing '/'
661 path is the path to the directory, without a trailing '/'
662
662
663 statuses is a set of statuses of all files in this directory (this includes
663 statuses is a set of statuses of all files in this directory (this includes
664 all the files in all the subdirectories too)
664 all the files in all the subdirectories too)
665
665
666 files is a list of files which are direct child of this directory
666 files is a list of files which are direct child of this directory
667
667
668 subdirs is a dictionary of sub-directory name as the key and it's own
668 subdirs is a dictionary of sub-directory name as the key and it's own
669 dirnode object as the value
669 dirnode object as the value
670 """
670 """
671
671
672 def __init__(self, dirpath):
672 def __init__(self, dirpath):
673 self.path = dirpath
673 self.path = dirpath
674 self.statuses = set()
674 self.statuses = set()
675 self.files = []
675 self.files = []
676 self.subdirs = {}
676 self.subdirs = {}
677
677
678 def _addfileindir(self, filename, status):
678 def _addfileindir(self, filename, status):
679 """Add a file in this directory as a direct child."""
679 """Add a file in this directory as a direct child."""
680 self.files.append((filename, status))
680 self.files.append((filename, status))
681
681
682 def addfile(self, filename, status):
682 def addfile(self, filename, status):
683 """
683 """
684 Add a file to this directory or to its direct parent directory.
684 Add a file to this directory or to its direct parent directory.
685
685
686 If the file is not direct child of this directory, we traverse to the
686 If the file is not direct child of this directory, we traverse to the
687 directory of which this file is a direct child of and add the file
687 directory of which this file is a direct child of and add the file
688 there.
688 there.
689 """
689 """
690
690
691 # the filename contains a path separator, it means it's not the direct
691 # the filename contains a path separator, it means it's not the direct
692 # child of this directory
692 # child of this directory
693 if b'/' in filename:
693 if b'/' in filename:
694 subdir, filep = filename.split(b'/', 1)
694 subdir, filep = filename.split(b'/', 1)
695
695
696 # does the dirnode object for subdir exists
696 # does the dirnode object for subdir exists
697 if subdir not in self.subdirs:
697 if subdir not in self.subdirs:
698 subdirpath = pathutil.join(self.path, subdir)
698 subdirpath = pathutil.join(self.path, subdir)
699 self.subdirs[subdir] = dirnode(subdirpath)
699 self.subdirs[subdir] = dirnode(subdirpath)
700
700
701 # try adding the file in subdir
701 # try adding the file in subdir
702 self.subdirs[subdir].addfile(filep, status)
702 self.subdirs[subdir].addfile(filep, status)
703
703
704 else:
704 else:
705 self._addfileindir(filename, status)
705 self._addfileindir(filename, status)
706
706
707 if status not in self.statuses:
707 if status not in self.statuses:
708 self.statuses.add(status)
708 self.statuses.add(status)
709
709
710 def iterfilepaths(self):
710 def iterfilepaths(self):
711 """Yield (status, path) for files directly under this directory."""
711 """Yield (status, path) for files directly under this directory."""
712 for f, st in self.files:
712 for f, st in self.files:
713 yield st, pathutil.join(self.path, f)
713 yield st, pathutil.join(self.path, f)
714
714
715 def tersewalk(self, terseargs):
715 def tersewalk(self, terseargs):
716 """
716 """
717 Yield (status, path) obtained by processing the status of this
717 Yield (status, path) obtained by processing the status of this
718 dirnode.
718 dirnode.
719
719
720 terseargs is the string of arguments passed by the user with `--terse`
720 terseargs is the string of arguments passed by the user with `--terse`
721 flag.
721 flag.
722
722
723 Following are the cases which can happen:
723 Following are the cases which can happen:
724
724
725 1) All the files in the directory (including all the files in its
725 1) All the files in the directory (including all the files in its
726 subdirectories) share the same status and the user has asked us to terse
726 subdirectories) share the same status and the user has asked us to terse
727 that status. -> yield (status, dirpath). dirpath will end in '/'.
727 that status. -> yield (status, dirpath). dirpath will end in '/'.
728
728
729 2) Otherwise, we do following:
729 2) Otherwise, we do following:
730
730
731 a) Yield (status, filepath) for all the files which are in this
731 a) Yield (status, filepath) for all the files which are in this
732 directory (only the ones in this directory, not the subdirs)
732 directory (only the ones in this directory, not the subdirs)
733
733
734 b) Recurse the function on all the subdirectories of this
734 b) Recurse the function on all the subdirectories of this
735 directory
735 directory
736 """
736 """
737
737
738 if len(self.statuses) == 1:
738 if len(self.statuses) == 1:
739 onlyst = self.statuses.pop()
739 onlyst = self.statuses.pop()
740
740
741 # Making sure we terse only when the status abbreviation is
741 # Making sure we terse only when the status abbreviation is
742 # passed as terse argument
742 # passed as terse argument
743 if onlyst in terseargs:
743 if onlyst in terseargs:
744 yield onlyst, self.path + b'/'
744 yield onlyst, self.path + b'/'
745 return
745 return
746
746
747 # add the files to status list
747 # add the files to status list
748 for st, fpath in self.iterfilepaths():
748 for st, fpath in self.iterfilepaths():
749 yield st, fpath
749 yield st, fpath
750
750
751 # recurse on the subdirs
751 # recurse on the subdirs
752 for dirobj in self.subdirs.values():
752 for dirobj in self.subdirs.values():
753 for st, fpath in dirobj.tersewalk(terseargs):
753 for st, fpath in dirobj.tersewalk(terseargs):
754 yield st, fpath
754 yield st, fpath
755
755
756
756
757 def tersedir(statuslist, terseargs):
757 def tersedir(statuslist, terseargs):
758 """
758 """
759 Terse the status if all the files in a directory shares the same status.
759 Terse the status if all the files in a directory shares the same status.
760
760
761 statuslist is scmutil.status() object which contains a list of files for
761 statuslist is scmutil.status() object which contains a list of files for
762 each status.
762 each status.
763 terseargs is string which is passed by the user as the argument to `--terse`
763 terseargs is string which is passed by the user as the argument to `--terse`
764 flag.
764 flag.
765
765
766 The function makes a tree of objects of dirnode class, and at each node it
766 The function makes a tree of objects of dirnode class, and at each node it
767 stores the information required to know whether we can terse a certain
767 stores the information required to know whether we can terse a certain
768 directory or not.
768 directory or not.
769 """
769 """
770 # the order matters here as that is used to produce final list
770 # the order matters here as that is used to produce final list
771 allst = (b'm', b'a', b'r', b'd', b'u', b'i', b'c')
771 allst = (b'm', b'a', b'r', b'd', b'u', b'i', b'c')
772
772
773 # checking the argument validity
773 # checking the argument validity
774 for s in pycompat.bytestr(terseargs):
774 for s in pycompat.bytestr(terseargs):
775 if s not in allst:
775 if s not in allst:
776 raise error.InputError(_(b"'%s' not recognized") % s)
776 raise error.InputError(_(b"'%s' not recognized") % s)
777
777
778 # creating a dirnode object for the root of the repo
778 # creating a dirnode object for the root of the repo
779 rootobj = dirnode(b'')
779 rootobj = dirnode(b'')
780 pstatus = (
780 pstatus = (
781 b'modified',
781 b'modified',
782 b'added',
782 b'added',
783 b'deleted',
783 b'deleted',
784 b'clean',
784 b'clean',
785 b'unknown',
785 b'unknown',
786 b'ignored',
786 b'ignored',
787 b'removed',
787 b'removed',
788 )
788 )
789
789
790 tersedict = {}
790 tersedict = {}
791 for attrname in pstatus:
791 for attrname in pstatus:
792 statuschar = attrname[0:1]
792 statuschar = attrname[0:1]
793 for f in getattr(statuslist, attrname):
793 for f in getattr(statuslist, attrname):
794 rootobj.addfile(f, statuschar)
794 rootobj.addfile(f, statuschar)
795 tersedict[statuschar] = []
795 tersedict[statuschar] = []
796
796
797 # we won't be tersing the root dir, so add files in it
797 # we won't be tersing the root dir, so add files in it
798 for st, fpath in rootobj.iterfilepaths():
798 for st, fpath in rootobj.iterfilepaths():
799 tersedict[st].append(fpath)
799 tersedict[st].append(fpath)
800
800
801 # process each sub-directory and build tersedict
801 # process each sub-directory and build tersedict
802 for subdir in rootobj.subdirs.values():
802 for subdir in rootobj.subdirs.values():
803 for st, f in subdir.tersewalk(terseargs):
803 for st, f in subdir.tersewalk(terseargs):
804 tersedict[st].append(f)
804 tersedict[st].append(f)
805
805
806 tersedlist = []
806 tersedlist = []
807 for st in allst:
807 for st in allst:
808 tersedict[st].sort()
808 tersedict[st].sort()
809 tersedlist.append(tersedict[st])
809 tersedlist.append(tersedict[st])
810
810
811 return scmutil.status(*tersedlist)
811 return scmutil.status(*tersedlist)
812
812
813
813
814 def _commentlines(raw):
814 def _commentlines(raw):
815 '''Surround lineswith a comment char and a new line'''
815 '''Surround lineswith a comment char and a new line'''
816 lines = raw.splitlines()
816 lines = raw.splitlines()
817 commentedlines = [b'# %s' % line for line in lines]
817 commentedlines = [b'# %s' % line for line in lines]
818 return b'\n'.join(commentedlines) + b'\n'
818 return b'\n'.join(commentedlines) + b'\n'
819
819
820
820
821 @attr.s(frozen=True)
821 @attr.s(frozen=True)
822 class morestatus(object):
822 class morestatus(object):
823 reporoot = attr.ib()
823 reporoot = attr.ib()
824 unfinishedop = attr.ib()
824 unfinishedop = attr.ib()
825 unfinishedmsg = attr.ib()
825 unfinishedmsg = attr.ib()
826 activemerge = attr.ib()
826 activemerge = attr.ib()
827 unresolvedpaths = attr.ib()
827 unresolvedpaths = attr.ib()
828 _formattedpaths = attr.ib(init=False, default=set())
828 _formattedpaths = attr.ib(init=False, default=set())
829 _label = b'status.morestatus'
829 _label = b'status.morestatus'
830
830
831 def formatfile(self, path, fm):
831 def formatfile(self, path, fm):
832 self._formattedpaths.add(path)
832 self._formattedpaths.add(path)
833 if self.activemerge and path in self.unresolvedpaths:
833 if self.activemerge and path in self.unresolvedpaths:
834 fm.data(unresolved=True)
834 fm.data(unresolved=True)
835
835
836 def formatfooter(self, fm):
836 def formatfooter(self, fm):
837 if self.unfinishedop or self.unfinishedmsg:
837 if self.unfinishedop or self.unfinishedmsg:
838 fm.startitem()
838 fm.startitem()
839 fm.data(itemtype=b'morestatus')
839 fm.data(itemtype=b'morestatus')
840
840
841 if self.unfinishedop:
841 if self.unfinishedop:
842 fm.data(unfinished=self.unfinishedop)
842 fm.data(unfinished=self.unfinishedop)
843 statemsg = (
843 statemsg = (
844 _(b'The repository is in an unfinished *%s* state.')
844 _(b'The repository is in an unfinished *%s* state.')
845 % self.unfinishedop
845 % self.unfinishedop
846 )
846 )
847 fm.plain(b'%s\n' % _commentlines(statemsg), label=self._label)
847 fm.plain(b'%s\n' % _commentlines(statemsg), label=self._label)
848 if self.unfinishedmsg:
848 if self.unfinishedmsg:
849 fm.data(unfinishedmsg=self.unfinishedmsg)
849 fm.data(unfinishedmsg=self.unfinishedmsg)
850
850
851 # May also start new data items.
851 # May also start new data items.
852 self._formatconflicts(fm)
852 self._formatconflicts(fm)
853
853
854 if self.unfinishedmsg:
854 if self.unfinishedmsg:
855 fm.plain(
855 fm.plain(
856 b'%s\n' % _commentlines(self.unfinishedmsg), label=self._label
856 b'%s\n' % _commentlines(self.unfinishedmsg), label=self._label
857 )
857 )
858
858
859 def _formatconflicts(self, fm):
859 def _formatconflicts(self, fm):
860 if not self.activemerge:
860 if not self.activemerge:
861 return
861 return
862
862
863 if self.unresolvedpaths:
863 if self.unresolvedpaths:
864 mergeliststr = b'\n'.join(
864 mergeliststr = b'\n'.join(
865 [
865 [
866 b' %s'
866 b' %s'
867 % util.pathto(self.reporoot, encoding.getcwd(), path)
867 % util.pathto(self.reporoot, encoding.getcwd(), path)
868 for path in self.unresolvedpaths
868 for path in self.unresolvedpaths
869 ]
869 ]
870 )
870 )
871 msg = (
871 msg = (
872 _(
872 _(
873 b'''Unresolved merge conflicts:
873 b'''Unresolved merge conflicts:
874
874
875 %s
875 %s
876
876
877 To mark files as resolved: hg resolve --mark FILE'''
877 To mark files as resolved: hg resolve --mark FILE'''
878 )
878 )
879 % mergeliststr
879 % mergeliststr
880 )
880 )
881
881
882 # If any paths with unresolved conflicts were not previously
882 # If any paths with unresolved conflicts were not previously
883 # formatted, output them now.
883 # formatted, output them now.
884 for f in self.unresolvedpaths:
884 for f in self.unresolvedpaths:
885 if f in self._formattedpaths:
885 if f in self._formattedpaths:
886 # Already output.
886 # Already output.
887 continue
887 continue
888 fm.startitem()
888 fm.startitem()
889 # We can't claim to know the status of the file - it may just
889 # We can't claim to know the status of the file - it may just
890 # have been in one of the states that were not requested for
890 # have been in one of the states that were not requested for
891 # display, so it could be anything.
891 # display, so it could be anything.
892 fm.data(itemtype=b'file', path=f, unresolved=True)
892 fm.data(itemtype=b'file', path=f, unresolved=True)
893
893
894 else:
894 else:
895 msg = _(b'No unresolved merge conflicts.')
895 msg = _(b'No unresolved merge conflicts.')
896
896
897 fm.plain(b'%s\n' % _commentlines(msg), label=self._label)
897 fm.plain(b'%s\n' % _commentlines(msg), label=self._label)
898
898
899
899
900 def readmorestatus(repo):
900 def readmorestatus(repo):
901 """Returns a morestatus object if the repo has unfinished state."""
901 """Returns a morestatus object if the repo has unfinished state."""
902 statetuple = statemod.getrepostate(repo)
902 statetuple = statemod.getrepostate(repo)
903 mergestate = mergestatemod.mergestate.read(repo)
903 mergestate = mergestatemod.mergestate.read(repo)
904 activemerge = mergestate.active()
904 activemerge = mergestate.active()
905 if not statetuple and not activemerge:
905 if not statetuple and not activemerge:
906 return None
906 return None
907
907
908 unfinishedop = unfinishedmsg = unresolved = None
908 unfinishedop = unfinishedmsg = unresolved = None
909 if statetuple:
909 if statetuple:
910 unfinishedop, unfinishedmsg = statetuple
910 unfinishedop, unfinishedmsg = statetuple
911 if activemerge:
911 if activemerge:
912 unresolved = sorted(mergestate.unresolved())
912 unresolved = sorted(mergestate.unresolved())
913 return morestatus(
913 return morestatus(
914 repo.root, unfinishedop, unfinishedmsg, activemerge, unresolved
914 repo.root, unfinishedop, unfinishedmsg, activemerge, unresolved
915 )
915 )
916
916
917
917
918 def findpossible(cmd, table, strict=False):
918 def findpossible(cmd, table, strict=False):
919 """
919 """
920 Return cmd -> (aliases, command table entry)
920 Return cmd -> (aliases, command table entry)
921 for each matching command.
921 for each matching command.
922 Return debug commands (or their aliases) only if no normal command matches.
922 Return debug commands (or their aliases) only if no normal command matches.
923 """
923 """
924 choice = {}
924 choice = {}
925 debugchoice = {}
925 debugchoice = {}
926
926
927 if cmd in table:
927 if cmd in table:
928 # short-circuit exact matches, "log" alias beats "log|history"
928 # short-circuit exact matches, "log" alias beats "log|history"
929 keys = [cmd]
929 keys = [cmd]
930 else:
930 else:
931 keys = table.keys()
931 keys = table.keys()
932
932
933 allcmds = []
933 allcmds = []
934 for e in keys:
934 for e in keys:
935 aliases = parsealiases(e)
935 aliases = parsealiases(e)
936 allcmds.extend(aliases)
936 allcmds.extend(aliases)
937 found = None
937 found = None
938 if cmd in aliases:
938 if cmd in aliases:
939 found = cmd
939 found = cmd
940 elif not strict:
940 elif not strict:
941 for a in aliases:
941 for a in aliases:
942 if a.startswith(cmd):
942 if a.startswith(cmd):
943 found = a
943 found = a
944 break
944 break
945 if found is not None:
945 if found is not None:
946 if aliases[0].startswith(b"debug") or found.startswith(b"debug"):
946 if aliases[0].startswith(b"debug") or found.startswith(b"debug"):
947 debugchoice[found] = (aliases, table[e])
947 debugchoice[found] = (aliases, table[e])
948 else:
948 else:
949 choice[found] = (aliases, table[e])
949 choice[found] = (aliases, table[e])
950
950
951 if not choice and debugchoice:
951 if not choice and debugchoice:
952 choice = debugchoice
952 choice = debugchoice
953
953
954 return choice, allcmds
954 return choice, allcmds
955
955
956
956
957 def findcmd(cmd, table, strict=True):
957 def findcmd(cmd, table, strict=True):
958 """Return (aliases, command table entry) for command string."""
958 """Return (aliases, command table entry) for command string."""
959 choice, allcmds = findpossible(cmd, table, strict)
959 choice, allcmds = findpossible(cmd, table, strict)
960
960
961 if cmd in choice:
961 if cmd in choice:
962 return choice[cmd]
962 return choice[cmd]
963
963
964 if len(choice) > 1:
964 if len(choice) > 1:
965 clist = sorted(choice)
965 clist = sorted(choice)
966 raise error.AmbiguousCommand(cmd, clist)
966 raise error.AmbiguousCommand(cmd, clist)
967
967
968 if choice:
968 if choice:
969 return list(choice.values())[0]
969 return list(choice.values())[0]
970
970
971 raise error.UnknownCommand(cmd, allcmds)
971 raise error.UnknownCommand(cmd, allcmds)
972
972
973
973
974 def changebranch(ui, repo, revs, label, opts):
974 def changebranch(ui, repo, revs, label, opts):
975 """ Change the branch name of given revs to label """
975 """ Change the branch name of given revs to label """
976
976
977 with repo.wlock(), repo.lock(), repo.transaction(b'branches'):
977 with repo.wlock(), repo.lock(), repo.transaction(b'branches'):
978 # abort in case of uncommitted merge or dirty wdir
978 # abort in case of uncommitted merge or dirty wdir
979 bailifchanged(repo)
979 bailifchanged(repo)
980 revs = scmutil.revrange(repo, revs)
980 revs = scmutil.revrange(repo, revs)
981 if not revs:
981 if not revs:
982 raise error.InputError(b"empty revision set")
982 raise error.InputError(b"empty revision set")
983 roots = repo.revs(b'roots(%ld)', revs)
983 roots = repo.revs(b'roots(%ld)', revs)
984 if len(roots) > 1:
984 if len(roots) > 1:
985 raise error.InputError(
985 raise error.InputError(
986 _(b"cannot change branch of non-linear revisions")
986 _(b"cannot change branch of non-linear revisions")
987 )
987 )
988 rewriteutil.precheck(repo, revs, b'change branch of')
988 rewriteutil.precheck(repo, revs, b'change branch of')
989
989
990 root = repo[roots.first()]
990 root = repo[roots.first()]
991 rpb = {parent.branch() for parent in root.parents()}
991 rpb = {parent.branch() for parent in root.parents()}
992 if (
992 if (
993 not opts.get(b'force')
993 not opts.get(b'force')
994 and label not in rpb
994 and label not in rpb
995 and label in repo.branchmap()
995 and label in repo.branchmap()
996 ):
996 ):
997 raise error.InputError(
997 raise error.InputError(
998 _(b"a branch of the same name already exists")
998 _(b"a branch of the same name already exists")
999 )
999 )
1000
1000
1001 if repo.revs(b'obsolete() and %ld', revs):
1001 if repo.revs(b'obsolete() and %ld', revs):
1002 raise error.InputError(
1002 raise error.InputError(
1003 _(b"cannot change branch of a obsolete changeset")
1003 _(b"cannot change branch of a obsolete changeset")
1004 )
1004 )
1005
1005
1006 # make sure only topological heads
1006 # make sure only topological heads
1007 if repo.revs(b'heads(%ld) - head()', revs):
1007 if repo.revs(b'heads(%ld) - head()', revs):
1008 raise error.InputError(
1008 raise error.InputError(
1009 _(b"cannot change branch in middle of a stack")
1009 _(b"cannot change branch in middle of a stack")
1010 )
1010 )
1011
1011
1012 replacements = {}
1012 replacements = {}
1013 # avoid import cycle mercurial.cmdutil -> mercurial.context ->
1013 # avoid import cycle mercurial.cmdutil -> mercurial.context ->
1014 # mercurial.subrepo -> mercurial.cmdutil
1014 # mercurial.subrepo -> mercurial.cmdutil
1015 from . import context
1015 from . import context
1016
1016
1017 for rev in revs:
1017 for rev in revs:
1018 ctx = repo[rev]
1018 ctx = repo[rev]
1019 oldbranch = ctx.branch()
1019 oldbranch = ctx.branch()
1020 # check if ctx has same branch
1020 # check if ctx has same branch
1021 if oldbranch == label:
1021 if oldbranch == label:
1022 continue
1022 continue
1023
1023
1024 def filectxfn(repo, newctx, path):
1024 def filectxfn(repo, newctx, path):
1025 try:
1025 try:
1026 return ctx[path]
1026 return ctx[path]
1027 except error.ManifestLookupError:
1027 except error.ManifestLookupError:
1028 return None
1028 return None
1029
1029
1030 ui.debug(
1030 ui.debug(
1031 b"changing branch of '%s' from '%s' to '%s'\n"
1031 b"changing branch of '%s' from '%s' to '%s'\n"
1032 % (hex(ctx.node()), oldbranch, label)
1032 % (hex(ctx.node()), oldbranch, label)
1033 )
1033 )
1034 extra = ctx.extra()
1034 extra = ctx.extra()
1035 extra[b'branch_change'] = hex(ctx.node())
1035 extra[b'branch_change'] = hex(ctx.node())
1036 # While changing branch of set of linear commits, make sure that
1036 # While changing branch of set of linear commits, make sure that
1037 # we base our commits on new parent rather than old parent which
1037 # we base our commits on new parent rather than old parent which
1038 # was obsoleted while changing the branch
1038 # was obsoleted while changing the branch
1039 p1 = ctx.p1().node()
1039 p1 = ctx.p1().node()
1040 p2 = ctx.p2().node()
1040 p2 = ctx.p2().node()
1041 if p1 in replacements:
1041 if p1 in replacements:
1042 p1 = replacements[p1][0]
1042 p1 = replacements[p1][0]
1043 if p2 in replacements:
1043 if p2 in replacements:
1044 p2 = replacements[p2][0]
1044 p2 = replacements[p2][0]
1045
1045
1046 mc = context.memctx(
1046 mc = context.memctx(
1047 repo,
1047 repo,
1048 (p1, p2),
1048 (p1, p2),
1049 ctx.description(),
1049 ctx.description(),
1050 ctx.files(),
1050 ctx.files(),
1051 filectxfn,
1051 filectxfn,
1052 user=ctx.user(),
1052 user=ctx.user(),
1053 date=ctx.date(),
1053 date=ctx.date(),
1054 extra=extra,
1054 extra=extra,
1055 branch=label,
1055 branch=label,
1056 )
1056 )
1057
1057
1058 newnode = repo.commitctx(mc)
1058 newnode = repo.commitctx(mc)
1059 replacements[ctx.node()] = (newnode,)
1059 replacements[ctx.node()] = (newnode,)
1060 ui.debug(b'new node id is %s\n' % hex(newnode))
1060 ui.debug(b'new node id is %s\n' % hex(newnode))
1061
1061
1062 # create obsmarkers and move bookmarks
1062 # create obsmarkers and move bookmarks
1063 scmutil.cleanupnodes(
1063 scmutil.cleanupnodes(
1064 repo, replacements, b'branch-change', fixphase=True
1064 repo, replacements, b'branch-change', fixphase=True
1065 )
1065 )
1066
1066
1067 # move the working copy too
1067 # move the working copy too
1068 wctx = repo[None]
1068 wctx = repo[None]
1069 # in-progress merge is a bit too complex for now.
1069 # in-progress merge is a bit too complex for now.
1070 if len(wctx.parents()) == 1:
1070 if len(wctx.parents()) == 1:
1071 newid = replacements.get(wctx.p1().node())
1071 newid = replacements.get(wctx.p1().node())
1072 if newid is not None:
1072 if newid is not None:
1073 # avoid import cycle mercurial.cmdutil -> mercurial.hg ->
1073 # avoid import cycle mercurial.cmdutil -> mercurial.hg ->
1074 # mercurial.cmdutil
1074 # mercurial.cmdutil
1075 from . import hg
1075 from . import hg
1076
1076
1077 hg.update(repo, newid[0], quietempty=True)
1077 hg.update(repo, newid[0], quietempty=True)
1078
1078
1079 ui.status(_(b"changed branch on %d changesets\n") % len(replacements))
1079 ui.status(_(b"changed branch on %d changesets\n") % len(replacements))
1080
1080
1081
1081
1082 def findrepo(p):
1082 def findrepo(p):
1083 while not os.path.isdir(os.path.join(p, b".hg")):
1083 while not os.path.isdir(os.path.join(p, b".hg")):
1084 oldp, p = p, os.path.dirname(p)
1084 oldp, p = p, os.path.dirname(p)
1085 if p == oldp:
1085 if p == oldp:
1086 return None
1086 return None
1087
1087
1088 return p
1088 return p
1089
1089
1090
1090
1091 def bailifchanged(repo, merge=True, hint=None):
1091 def bailifchanged(repo, merge=True, hint=None):
1092 """enforce the precondition that working directory must be clean.
1092 """enforce the precondition that working directory must be clean.
1093
1093
1094 'merge' can be set to false if a pending uncommitted merge should be
1094 'merge' can be set to false if a pending uncommitted merge should be
1095 ignored (such as when 'update --check' runs).
1095 ignored (such as when 'update --check' runs).
1096
1096
1097 'hint' is the usual hint given to Abort exception.
1097 'hint' is the usual hint given to Abort exception.
1098 """
1098 """
1099
1099
1100 if merge and repo.dirstate.p2() != nullid:
1100 if merge and repo.dirstate.p2() != nullid:
1101 raise error.StateError(_(b'outstanding uncommitted merge'), hint=hint)
1101 raise error.StateError(_(b'outstanding uncommitted merge'), hint=hint)
1102 st = repo.status()
1102 st = repo.status()
1103 if st.modified or st.added or st.removed or st.deleted:
1103 if st.modified or st.added or st.removed or st.deleted:
1104 raise error.StateError(_(b'uncommitted changes'), hint=hint)
1104 raise error.StateError(_(b'uncommitted changes'), hint=hint)
1105 ctx = repo[None]
1105 ctx = repo[None]
1106 for s in sorted(ctx.substate):
1106 for s in sorted(ctx.substate):
1107 ctx.sub(s).bailifchanged(hint=hint)
1107 ctx.sub(s).bailifchanged(hint=hint)
1108
1108
1109
1109
1110 def logmessage(ui, opts):
1110 def logmessage(ui, opts):
1111 """ get the log message according to -m and -l option """
1111 """ get the log message according to -m and -l option """
1112
1112
1113 check_at_most_one_arg(opts, b'message', b'logfile')
1113 check_at_most_one_arg(opts, b'message', b'logfile')
1114
1114
1115 message = opts.get(b'message')
1115 message = opts.get(b'message')
1116 logfile = opts.get(b'logfile')
1116 logfile = opts.get(b'logfile')
1117
1117
1118 if not message and logfile:
1118 if not message and logfile:
1119 try:
1119 try:
1120 if isstdiofilename(logfile):
1120 if isstdiofilename(logfile):
1121 message = ui.fin.read()
1121 message = ui.fin.read()
1122 else:
1122 else:
1123 message = b'\n'.join(util.readfile(logfile).splitlines())
1123 message = b'\n'.join(util.readfile(logfile).splitlines())
1124 except IOError as inst:
1124 except IOError as inst:
1125 raise error.Abort(
1125 raise error.Abort(
1126 _(b"can't read commit message '%s': %s")
1126 _(b"can't read commit message '%s': %s")
1127 % (logfile, encoding.strtolocal(inst.strerror))
1127 % (logfile, encoding.strtolocal(inst.strerror))
1128 )
1128 )
1129 return message
1129 return message
1130
1130
1131
1131
1132 def mergeeditform(ctxorbool, baseformname):
1132 def mergeeditform(ctxorbool, baseformname):
1133 """return appropriate editform name (referencing a committemplate)
1133 """return appropriate editform name (referencing a committemplate)
1134
1134
1135 'ctxorbool' is either a ctx to be committed, or a bool indicating whether
1135 'ctxorbool' is either a ctx to be committed, or a bool indicating whether
1136 merging is committed.
1136 merging is committed.
1137
1137
1138 This returns baseformname with '.merge' appended if it is a merge,
1138 This returns baseformname with '.merge' appended if it is a merge,
1139 otherwise '.normal' is appended.
1139 otherwise '.normal' is appended.
1140 """
1140 """
1141 if isinstance(ctxorbool, bool):
1141 if isinstance(ctxorbool, bool):
1142 if ctxorbool:
1142 if ctxorbool:
1143 return baseformname + b".merge"
1143 return baseformname + b".merge"
1144 elif len(ctxorbool.parents()) > 1:
1144 elif len(ctxorbool.parents()) > 1:
1145 return baseformname + b".merge"
1145 return baseformname + b".merge"
1146
1146
1147 return baseformname + b".normal"
1147 return baseformname + b".normal"
1148
1148
1149
1149
1150 def getcommiteditor(
1150 def getcommiteditor(
1151 edit=False, finishdesc=None, extramsg=None, editform=b'', **opts
1151 edit=False, finishdesc=None, extramsg=None, editform=b'', **opts
1152 ):
1152 ):
1153 """get appropriate commit message editor according to '--edit' option
1153 """get appropriate commit message editor according to '--edit' option
1154
1154
1155 'finishdesc' is a function to be called with edited commit message
1155 'finishdesc' is a function to be called with edited commit message
1156 (= 'description' of the new changeset) just after editing, but
1156 (= 'description' of the new changeset) just after editing, but
1157 before checking empty-ness. It should return actual text to be
1157 before checking empty-ness. It should return actual text to be
1158 stored into history. This allows to change description before
1158 stored into history. This allows to change description before
1159 storing.
1159 storing.
1160
1160
1161 'extramsg' is a extra message to be shown in the editor instead of
1161 'extramsg' is a extra message to be shown in the editor instead of
1162 'Leave message empty to abort commit' line. 'HG: ' prefix and EOL
1162 'Leave message empty to abort commit' line. 'HG: ' prefix and EOL
1163 is automatically added.
1163 is automatically added.
1164
1164
1165 'editform' is a dot-separated list of names, to distinguish
1165 'editform' is a dot-separated list of names, to distinguish
1166 the purpose of commit text editing.
1166 the purpose of commit text editing.
1167
1167
1168 'getcommiteditor' returns 'commitforceeditor' regardless of
1168 'getcommiteditor' returns 'commitforceeditor' regardless of
1169 'edit', if one of 'finishdesc' or 'extramsg' is specified, because
1169 'edit', if one of 'finishdesc' or 'extramsg' is specified, because
1170 they are specific for usage in MQ.
1170 they are specific for usage in MQ.
1171 """
1171 """
1172 if edit or finishdesc or extramsg:
1172 if edit or finishdesc or extramsg:
1173 return lambda r, c, s: commitforceeditor(
1173 return lambda r, c, s: commitforceeditor(
1174 r, c, s, finishdesc=finishdesc, extramsg=extramsg, editform=editform
1174 r, c, s, finishdesc=finishdesc, extramsg=extramsg, editform=editform
1175 )
1175 )
1176 elif editform:
1176 elif editform:
1177 return lambda r, c, s: commiteditor(r, c, s, editform=editform)
1177 return lambda r, c, s: commiteditor(r, c, s, editform=editform)
1178 else:
1178 else:
1179 return commiteditor
1179 return commiteditor
1180
1180
1181
1181
1182 def _escapecommandtemplate(tmpl):
1182 def _escapecommandtemplate(tmpl):
1183 parts = []
1183 parts = []
1184 for typ, start, end in templater.scantemplate(tmpl, raw=True):
1184 for typ, start, end in templater.scantemplate(tmpl, raw=True):
1185 if typ == b'string':
1185 if typ == b'string':
1186 parts.append(stringutil.escapestr(tmpl[start:end]))
1186 parts.append(stringutil.escapestr(tmpl[start:end]))
1187 else:
1187 else:
1188 parts.append(tmpl[start:end])
1188 parts.append(tmpl[start:end])
1189 return b''.join(parts)
1189 return b''.join(parts)
1190
1190
1191
1191
1192 def rendercommandtemplate(ui, tmpl, props):
1192 def rendercommandtemplate(ui, tmpl, props):
1193 r"""Expand a literal template 'tmpl' in a way suitable for command line
1193 r"""Expand a literal template 'tmpl' in a way suitable for command line
1194
1194
1195 '\' in outermost string is not taken as an escape character because it
1195 '\' in outermost string is not taken as an escape character because it
1196 is a directory separator on Windows.
1196 is a directory separator on Windows.
1197
1197
1198 >>> from . import ui as uimod
1198 >>> from . import ui as uimod
1199 >>> ui = uimod.ui()
1199 >>> ui = uimod.ui()
1200 >>> rendercommandtemplate(ui, b'c:\\{path}', {b'path': b'foo'})
1200 >>> rendercommandtemplate(ui, b'c:\\{path}', {b'path': b'foo'})
1201 'c:\\foo'
1201 'c:\\foo'
1202 >>> rendercommandtemplate(ui, b'{"c:\\{path}"}', {'path': b'foo'})
1202 >>> rendercommandtemplate(ui, b'{"c:\\{path}"}', {'path': b'foo'})
1203 'c:{path}'
1203 'c:{path}'
1204 """
1204 """
1205 if not tmpl:
1205 if not tmpl:
1206 return tmpl
1206 return tmpl
1207 t = formatter.maketemplater(ui, _escapecommandtemplate(tmpl))
1207 t = formatter.maketemplater(ui, _escapecommandtemplate(tmpl))
1208 return t.renderdefault(props)
1208 return t.renderdefault(props)
1209
1209
1210
1210
1211 def rendertemplate(ctx, tmpl, props=None):
1211 def rendertemplate(ctx, tmpl, props=None):
1212 """Expand a literal template 'tmpl' byte-string against one changeset
1212 """Expand a literal template 'tmpl' byte-string against one changeset
1213
1213
1214 Each props item must be a stringify-able value or a callable returning
1214 Each props item must be a stringify-able value or a callable returning
1215 such value, i.e. no bare list nor dict should be passed.
1215 such value, i.e. no bare list nor dict should be passed.
1216 """
1216 """
1217 repo = ctx.repo()
1217 repo = ctx.repo()
1218 tres = formatter.templateresources(repo.ui, repo)
1218 tres = formatter.templateresources(repo.ui, repo)
1219 t = formatter.maketemplater(
1219 t = formatter.maketemplater(
1220 repo.ui, tmpl, defaults=templatekw.keywords, resources=tres
1220 repo.ui, tmpl, defaults=templatekw.keywords, resources=tres
1221 )
1221 )
1222 mapping = {b'ctx': ctx}
1222 mapping = {b'ctx': ctx}
1223 if props:
1223 if props:
1224 mapping.update(props)
1224 mapping.update(props)
1225 return t.renderdefault(mapping)
1225 return t.renderdefault(mapping)
1226
1226
1227
1227
1228 def format_changeset_summary(ui, ctx, command=None, default_spec=None):
1228 def format_changeset_summary(ui, ctx, command=None, default_spec=None):
1229 """Format a changeset summary (one line)."""
1229 """Format a changeset summary (one line)."""
1230 spec = None
1230 spec = None
1231 if command:
1231 if command:
1232 spec = ui.config(
1232 spec = ui.config(
1233 b'command-templates', b'oneline-summary.%s' % command, None
1233 b'command-templates', b'oneline-summary.%s' % command, None
1234 )
1234 )
1235 if not spec:
1235 if not spec:
1236 spec = ui.config(b'command-templates', b'oneline-summary')
1236 spec = ui.config(b'command-templates', b'oneline-summary')
1237 if not spec:
1237 if not spec:
1238 spec = default_spec
1238 spec = default_spec
1239 if not spec:
1239 if not spec:
1240 spec = (
1240 spec = (
1241 b'{separate(" ", '
1241 b'{separate(" ", '
1242 b'label("oneline-summary.changeset", "{rev}:{node|short}")'
1242 b'label("oneline-summary.changeset", "{rev}:{node|short}")'
1243 b', '
1243 b', '
1244 b'join(filter(namespaces % "{ifeq(namespace, "branches", "", join(names % "{label("oneline-summary.{namespace}", name)}", " "))}"), " ")'
1244 b'join(filter(namespaces % "{ifeq(namespace, "branches", "", join(names % "{label("oneline-summary.{namespace}", name)}", " "))}"), " ")'
1245 b')} '
1245 b')} '
1246 b'"{label("oneline-summary.desc", desc|firstline)}"'
1246 b'"{label("oneline-summary.desc", desc|firstline)}"'
1247 )
1247 )
1248 text = rendertemplate(ctx, spec)
1248 text = rendertemplate(ctx, spec)
1249 return text.split(b'\n')[0]
1249 return text.split(b'\n')[0]
1250
1250
1251
1251
1252 def _buildfntemplate(pat, total=None, seqno=None, revwidth=None, pathname=None):
1252 def _buildfntemplate(pat, total=None, seqno=None, revwidth=None, pathname=None):
1253 r"""Convert old-style filename format string to template string
1253 r"""Convert old-style filename format string to template string
1254
1254
1255 >>> _buildfntemplate(b'foo-%b-%n.patch', seqno=0)
1255 >>> _buildfntemplate(b'foo-%b-%n.patch', seqno=0)
1256 'foo-{reporoot|basename}-{seqno}.patch'
1256 'foo-{reporoot|basename}-{seqno}.patch'
1257 >>> _buildfntemplate(b'%R{tags % "{tag}"}%H')
1257 >>> _buildfntemplate(b'%R{tags % "{tag}"}%H')
1258 '{rev}{tags % "{tag}"}{node}'
1258 '{rev}{tags % "{tag}"}{node}'
1259
1259
1260 '\' in outermost strings has to be escaped because it is a directory
1260 '\' in outermost strings has to be escaped because it is a directory
1261 separator on Windows:
1261 separator on Windows:
1262
1262
1263 >>> _buildfntemplate(b'c:\\tmp\\%R\\%n.patch', seqno=0)
1263 >>> _buildfntemplate(b'c:\\tmp\\%R\\%n.patch', seqno=0)
1264 'c:\\\\tmp\\\\{rev}\\\\{seqno}.patch'
1264 'c:\\\\tmp\\\\{rev}\\\\{seqno}.patch'
1265 >>> _buildfntemplate(b'\\\\foo\\bar.patch')
1265 >>> _buildfntemplate(b'\\\\foo\\bar.patch')
1266 '\\\\\\\\foo\\\\bar.patch'
1266 '\\\\\\\\foo\\\\bar.patch'
1267 >>> _buildfntemplate(b'\\{tags % "{tag}"}')
1267 >>> _buildfntemplate(b'\\{tags % "{tag}"}')
1268 '\\\\{tags % "{tag}"}'
1268 '\\\\{tags % "{tag}"}'
1269
1269
1270 but inner strings follow the template rules (i.e. '\' is taken as an
1270 but inner strings follow the template rules (i.e. '\' is taken as an
1271 escape character):
1271 escape character):
1272
1272
1273 >>> _buildfntemplate(br'{"c:\tmp"}', seqno=0)
1273 >>> _buildfntemplate(br'{"c:\tmp"}', seqno=0)
1274 '{"c:\\tmp"}'
1274 '{"c:\\tmp"}'
1275 """
1275 """
1276 expander = {
1276 expander = {
1277 b'H': b'{node}',
1277 b'H': b'{node}',
1278 b'R': b'{rev}',
1278 b'R': b'{rev}',
1279 b'h': b'{node|short}',
1279 b'h': b'{node|short}',
1280 b'm': br'{sub(r"[^\w]", "_", desc|firstline)}',
1280 b'm': br'{sub(r"[^\w]", "_", desc|firstline)}',
1281 b'r': b'{if(revwidth, pad(rev, revwidth, "0", left=True), rev)}',
1281 b'r': b'{if(revwidth, pad(rev, revwidth, "0", left=True), rev)}',
1282 b'%': b'%',
1282 b'%': b'%',
1283 b'b': b'{reporoot|basename}',
1283 b'b': b'{reporoot|basename}',
1284 }
1284 }
1285 if total is not None:
1285 if total is not None:
1286 expander[b'N'] = b'{total}'
1286 expander[b'N'] = b'{total}'
1287 if seqno is not None:
1287 if seqno is not None:
1288 expander[b'n'] = b'{seqno}'
1288 expander[b'n'] = b'{seqno}'
1289 if total is not None and seqno is not None:
1289 if total is not None and seqno is not None:
1290 expander[b'n'] = b'{pad(seqno, total|stringify|count, "0", left=True)}'
1290 expander[b'n'] = b'{pad(seqno, total|stringify|count, "0", left=True)}'
1291 if pathname is not None:
1291 if pathname is not None:
1292 expander[b's'] = b'{pathname|basename}'
1292 expander[b's'] = b'{pathname|basename}'
1293 expander[b'd'] = b'{if(pathname|dirname, pathname|dirname, ".")}'
1293 expander[b'd'] = b'{if(pathname|dirname, pathname|dirname, ".")}'
1294 expander[b'p'] = b'{pathname}'
1294 expander[b'p'] = b'{pathname}'
1295
1295
1296 newname = []
1296 newname = []
1297 for typ, start, end in templater.scantemplate(pat, raw=True):
1297 for typ, start, end in templater.scantemplate(pat, raw=True):
1298 if typ != b'string':
1298 if typ != b'string':
1299 newname.append(pat[start:end])
1299 newname.append(pat[start:end])
1300 continue
1300 continue
1301 i = start
1301 i = start
1302 while i < end:
1302 while i < end:
1303 n = pat.find(b'%', i, end)
1303 n = pat.find(b'%', i, end)
1304 if n < 0:
1304 if n < 0:
1305 newname.append(stringutil.escapestr(pat[i:end]))
1305 newname.append(stringutil.escapestr(pat[i:end]))
1306 break
1306 break
1307 newname.append(stringutil.escapestr(pat[i:n]))
1307 newname.append(stringutil.escapestr(pat[i:n]))
1308 if n + 2 > end:
1308 if n + 2 > end:
1309 raise error.Abort(
1309 raise error.Abort(
1310 _(b"incomplete format spec in output filename")
1310 _(b"incomplete format spec in output filename")
1311 )
1311 )
1312 c = pat[n + 1 : n + 2]
1312 c = pat[n + 1 : n + 2]
1313 i = n + 2
1313 i = n + 2
1314 try:
1314 try:
1315 newname.append(expander[c])
1315 newname.append(expander[c])
1316 except KeyError:
1316 except KeyError:
1317 raise error.Abort(
1317 raise error.Abort(
1318 _(b"invalid format spec '%%%s' in output filename") % c
1318 _(b"invalid format spec '%%%s' in output filename") % c
1319 )
1319 )
1320 return b''.join(newname)
1320 return b''.join(newname)
1321
1321
1322
1322
1323 def makefilename(ctx, pat, **props):
1323 def makefilename(ctx, pat, **props):
1324 if not pat:
1324 if not pat:
1325 return pat
1325 return pat
1326 tmpl = _buildfntemplate(pat, **props)
1326 tmpl = _buildfntemplate(pat, **props)
1327 # BUG: alias expansion shouldn't be made against template fragments
1327 # BUG: alias expansion shouldn't be made against template fragments
1328 # rewritten from %-format strings, but we have no easy way to partially
1328 # rewritten from %-format strings, but we have no easy way to partially
1329 # disable the expansion.
1329 # disable the expansion.
1330 return rendertemplate(ctx, tmpl, pycompat.byteskwargs(props))
1330 return rendertemplate(ctx, tmpl, pycompat.byteskwargs(props))
1331
1331
1332
1332
1333 def isstdiofilename(pat):
1333 def isstdiofilename(pat):
1334 """True if the given pat looks like a filename denoting stdin/stdout"""
1334 """True if the given pat looks like a filename denoting stdin/stdout"""
1335 return not pat or pat == b'-'
1335 return not pat or pat == b'-'
1336
1336
1337
1337
1338 class _unclosablefile(object):
1338 class _unclosablefile(object):
1339 def __init__(self, fp):
1339 def __init__(self, fp):
1340 self._fp = fp
1340 self._fp = fp
1341
1341
1342 def close(self):
1342 def close(self):
1343 pass
1343 pass
1344
1344
1345 def __iter__(self):
1345 def __iter__(self):
1346 return iter(self._fp)
1346 return iter(self._fp)
1347
1347
1348 def __getattr__(self, attr):
1348 def __getattr__(self, attr):
1349 return getattr(self._fp, attr)
1349 return getattr(self._fp, attr)
1350
1350
1351 def __enter__(self):
1351 def __enter__(self):
1352 return self
1352 return self
1353
1353
1354 def __exit__(self, exc_type, exc_value, exc_tb):
1354 def __exit__(self, exc_type, exc_value, exc_tb):
1355 pass
1355 pass
1356
1356
1357
1357
1358 def makefileobj(ctx, pat, mode=b'wb', **props):
1358 def makefileobj(ctx, pat, mode=b'wb', **props):
1359 writable = mode not in (b'r', b'rb')
1359 writable = mode not in (b'r', b'rb')
1360
1360
1361 if isstdiofilename(pat):
1361 if isstdiofilename(pat):
1362 repo = ctx.repo()
1362 repo = ctx.repo()
1363 if writable:
1363 if writable:
1364 fp = repo.ui.fout
1364 fp = repo.ui.fout
1365 else:
1365 else:
1366 fp = repo.ui.fin
1366 fp = repo.ui.fin
1367 return _unclosablefile(fp)
1367 return _unclosablefile(fp)
1368 fn = makefilename(ctx, pat, **props)
1368 fn = makefilename(ctx, pat, **props)
1369 return open(fn, mode)
1369 return open(fn, mode)
1370
1370
1371
1371
1372 def openstorage(repo, cmd, file_, opts, returnrevlog=False):
1372 def openstorage(repo, cmd, file_, opts, returnrevlog=False):
1373 """opens the changelog, manifest, a filelog or a given revlog"""
1373 """opens the changelog, manifest, a filelog or a given revlog"""
1374 cl = opts[b'changelog']
1374 cl = opts[b'changelog']
1375 mf = opts[b'manifest']
1375 mf = opts[b'manifest']
1376 dir = opts[b'dir']
1376 dir = opts[b'dir']
1377 msg = None
1377 msg = None
1378 if cl and mf:
1378 if cl and mf:
1379 msg = _(b'cannot specify --changelog and --manifest at the same time')
1379 msg = _(b'cannot specify --changelog and --manifest at the same time')
1380 elif cl and dir:
1380 elif cl and dir:
1381 msg = _(b'cannot specify --changelog and --dir at the same time')
1381 msg = _(b'cannot specify --changelog and --dir at the same time')
1382 elif cl or mf or dir:
1382 elif cl or mf or dir:
1383 if file_:
1383 if file_:
1384 msg = _(b'cannot specify filename with --changelog or --manifest')
1384 msg = _(b'cannot specify filename with --changelog or --manifest')
1385 elif not repo:
1385 elif not repo:
1386 msg = _(
1386 msg = _(
1387 b'cannot specify --changelog or --manifest or --dir '
1387 b'cannot specify --changelog or --manifest or --dir '
1388 b'without a repository'
1388 b'without a repository'
1389 )
1389 )
1390 if msg:
1390 if msg:
1391 raise error.InputError(msg)
1391 raise error.InputError(msg)
1392
1392
1393 r = None
1393 r = None
1394 if repo:
1394 if repo:
1395 if cl:
1395 if cl:
1396 r = repo.unfiltered().changelog
1396 r = repo.unfiltered().changelog
1397 elif dir:
1397 elif dir:
1398 if not scmutil.istreemanifest(repo):
1398 if not scmutil.istreemanifest(repo):
1399 raise error.InputError(
1399 raise error.InputError(
1400 _(
1400 _(
1401 b"--dir can only be used on repos with "
1401 b"--dir can only be used on repos with "
1402 b"treemanifest enabled"
1402 b"treemanifest enabled"
1403 )
1403 )
1404 )
1404 )
1405 if not dir.endswith(b'/'):
1405 if not dir.endswith(b'/'):
1406 dir = dir + b'/'
1406 dir = dir + b'/'
1407 dirlog = repo.manifestlog.getstorage(dir)
1407 dirlog = repo.manifestlog.getstorage(dir)
1408 if len(dirlog):
1408 if len(dirlog):
1409 r = dirlog
1409 r = dirlog
1410 elif mf:
1410 elif mf:
1411 r = repo.manifestlog.getstorage(b'')
1411 r = repo.manifestlog.getstorage(b'')
1412 elif file_:
1412 elif file_:
1413 filelog = repo.file(file_)
1413 filelog = repo.file(file_)
1414 if len(filelog):
1414 if len(filelog):
1415 r = filelog
1415 r = filelog
1416
1416
1417 # Not all storage may be revlogs. If requested, try to return an actual
1417 # Not all storage may be revlogs. If requested, try to return an actual
1418 # revlog instance.
1418 # revlog instance.
1419 if returnrevlog:
1419 if returnrevlog:
1420 if isinstance(r, revlog.revlog):
1420 if isinstance(r, revlog.revlog):
1421 pass
1421 pass
1422 elif util.safehasattr(r, b'_revlog'):
1422 elif util.safehasattr(r, b'_revlog'):
1423 r = r._revlog # pytype: disable=attribute-error
1423 r = r._revlog # pytype: disable=attribute-error
1424 elif r is not None:
1424 elif r is not None:
1425 raise error.InputError(
1425 raise error.InputError(
1426 _(b'%r does not appear to be a revlog') % r
1426 _(b'%r does not appear to be a revlog') % r
1427 )
1427 )
1428
1428
1429 if not r:
1429 if not r:
1430 if not returnrevlog:
1430 if not returnrevlog:
1431 raise error.InputError(_(b'cannot give path to non-revlog'))
1431 raise error.InputError(_(b'cannot give path to non-revlog'))
1432
1432
1433 if not file_:
1433 if not file_:
1434 raise error.CommandError(cmd, _(b'invalid arguments'))
1434 raise error.CommandError(cmd, _(b'invalid arguments'))
1435 if not os.path.isfile(file_):
1435 if not os.path.isfile(file_):
1436 raise error.InputError(_(b"revlog '%s' not found") % file_)
1436 raise error.InputError(_(b"revlog '%s' not found") % file_)
1437 r = revlog.revlog(
1437 r = revlog.revlog(
1438 vfsmod.vfs(encoding.getcwd(), audit=False), file_[:-2] + b".i"
1438 vfsmod.vfs(encoding.getcwd(), audit=False), file_[:-2] + b".i"
1439 )
1439 )
1440 return r
1440 return r
1441
1441
1442
1442
1443 def openrevlog(repo, cmd, file_, opts):
1443 def openrevlog(repo, cmd, file_, opts):
1444 """Obtain a revlog backing storage of an item.
1444 """Obtain a revlog backing storage of an item.
1445
1445
1446 This is similar to ``openstorage()`` except it always returns a revlog.
1446 This is similar to ``openstorage()`` except it always returns a revlog.
1447
1447
1448 In most cases, a caller cares about the main storage object - not the
1448 In most cases, a caller cares about the main storage object - not the
1449 revlog backing it. Therefore, this function should only be used by code
1449 revlog backing it. Therefore, this function should only be used by code
1450 that needs to examine low-level revlog implementation details. e.g. debug
1450 that needs to examine low-level revlog implementation details. e.g. debug
1451 commands.
1451 commands.
1452 """
1452 """
1453 return openstorage(repo, cmd, file_, opts, returnrevlog=True)
1453 return openstorage(repo, cmd, file_, opts, returnrevlog=True)
1454
1454
1455
1455
1456 def copy(ui, repo, pats, opts, rename=False):
1456 def copy(ui, repo, pats, opts, rename=False):
1457 check_incompatible_arguments(opts, b'forget', [b'dry_run'])
1457 check_incompatible_arguments(opts, b'forget', [b'dry_run'])
1458
1458
1459 # called with the repo lock held
1459 # called with the repo lock held
1460 #
1460 #
1461 # hgsep => pathname that uses "/" to separate directories
1461 # hgsep => pathname that uses "/" to separate directories
1462 # ossep => pathname that uses os.sep to separate directories
1462 # ossep => pathname that uses os.sep to separate directories
1463 cwd = repo.getcwd()
1463 cwd = repo.getcwd()
1464 targets = {}
1464 targets = {}
1465 forget = opts.get(b"forget")
1465 forget = opts.get(b"forget")
1466 after = opts.get(b"after")
1466 after = opts.get(b"after")
1467 dryrun = opts.get(b"dry_run")
1467 dryrun = opts.get(b"dry_run")
1468 rev = opts.get(b'at_rev')
1468 rev = opts.get(b'at_rev')
1469 if rev:
1469 if rev:
1470 if not forget and not after:
1470 if not forget and not after:
1471 # TODO: Remove this restriction and make it also create the copy
1471 # TODO: Remove this restriction and make it also create the copy
1472 # targets (and remove the rename source if rename==True).
1472 # targets (and remove the rename source if rename==True).
1473 raise error.InputError(_(b'--at-rev requires --after'))
1473 raise error.InputError(_(b'--at-rev requires --after'))
1474 ctx = scmutil.revsingle(repo, rev)
1474 ctx = scmutil.revsingle(repo, rev)
1475 if len(ctx.parents()) > 1:
1475 if len(ctx.parents()) > 1:
1476 raise error.InputError(
1476 raise error.InputError(
1477 _(b'cannot mark/unmark copy in merge commit')
1477 _(b'cannot mark/unmark copy in merge commit')
1478 )
1478 )
1479 else:
1479 else:
1480 ctx = repo[None]
1480 ctx = repo[None]
1481
1481
1482 pctx = ctx.p1()
1482 pctx = ctx.p1()
1483
1483
1484 uipathfn = scmutil.getuipathfn(repo, legacyrelativevalue=True)
1484 uipathfn = scmutil.getuipathfn(repo, legacyrelativevalue=True)
1485
1485
1486 if forget:
1486 if forget:
1487 if ctx.rev() is None:
1487 if ctx.rev() is None:
1488 new_ctx = ctx
1488 new_ctx = ctx
1489 else:
1489 else:
1490 if len(ctx.parents()) > 1:
1490 if len(ctx.parents()) > 1:
1491 raise error.InputError(_(b'cannot unmark copy in merge commit'))
1491 raise error.InputError(_(b'cannot unmark copy in merge commit'))
1492 # avoid cycle context -> subrepo -> cmdutil
1492 # avoid cycle context -> subrepo -> cmdutil
1493 from . import context
1493 from . import context
1494
1494
1495 rewriteutil.precheck(repo, [ctx.rev()], b'uncopy')
1495 rewriteutil.precheck(repo, [ctx.rev()], b'uncopy')
1496 new_ctx = context.overlayworkingctx(repo)
1496 new_ctx = context.overlayworkingctx(repo)
1497 new_ctx.setbase(ctx.p1())
1497 new_ctx.setbase(ctx.p1())
1498 mergemod.graft(repo, ctx, wctx=new_ctx)
1498 mergemod.graft(repo, ctx, wctx=new_ctx)
1499
1499
1500 match = scmutil.match(ctx, pats, opts)
1500 match = scmutil.match(ctx, pats, opts)
1501
1501
1502 current_copies = ctx.p1copies()
1502 current_copies = ctx.p1copies()
1503 current_copies.update(ctx.p2copies())
1503 current_copies.update(ctx.p2copies())
1504
1504
1505 uipathfn = scmutil.getuipathfn(repo)
1505 uipathfn = scmutil.getuipathfn(repo)
1506 for f in ctx.walk(match):
1506 for f in ctx.walk(match):
1507 if f in current_copies:
1507 if f in current_copies:
1508 new_ctx[f].markcopied(None)
1508 new_ctx[f].markcopied(None)
1509 elif match.exact(f):
1509 elif match.exact(f):
1510 ui.warn(
1510 ui.warn(
1511 _(
1511 _(
1512 b'%s: not unmarking as copy - file is not marked as copied\n'
1512 b'%s: not unmarking as copy - file is not marked as copied\n'
1513 )
1513 )
1514 % uipathfn(f)
1514 % uipathfn(f)
1515 )
1515 )
1516
1516
1517 if ctx.rev() is not None:
1517 if ctx.rev() is not None:
1518 with repo.lock():
1518 with repo.lock():
1519 mem_ctx = new_ctx.tomemctx_for_amend(ctx)
1519 mem_ctx = new_ctx.tomemctx_for_amend(ctx)
1520 new_node = mem_ctx.commit()
1520 new_node = mem_ctx.commit()
1521
1521
1522 if repo.dirstate.p1() == ctx.node():
1522 if repo.dirstate.p1() == ctx.node():
1523 with repo.dirstate.parentchange():
1523 with repo.dirstate.parentchange():
1524 scmutil.movedirstate(repo, repo[new_node])
1524 scmutil.movedirstate(repo, repo[new_node])
1525 replacements = {ctx.node(): [new_node]}
1525 replacements = {ctx.node(): [new_node]}
1526 scmutil.cleanupnodes(
1526 scmutil.cleanupnodes(
1527 repo, replacements, b'uncopy', fixphase=True
1527 repo, replacements, b'uncopy', fixphase=True
1528 )
1528 )
1529
1529
1530 return
1530 return
1531
1531
1532 pats = scmutil.expandpats(pats)
1532 pats = scmutil.expandpats(pats)
1533 if not pats:
1533 if not pats:
1534 raise error.InputError(_(b'no source or destination specified'))
1534 raise error.InputError(_(b'no source or destination specified'))
1535 if len(pats) == 1:
1535 if len(pats) == 1:
1536 raise error.InputError(_(b'no destination specified'))
1536 raise error.InputError(_(b'no destination specified'))
1537 dest = pats.pop()
1537 dest = pats.pop()
1538
1538
1539 def walkpat(pat):
1539 def walkpat(pat):
1540 srcs = []
1540 srcs = []
1541 # TODO: Inline and simplify the non-working-copy version of this code
1541 # TODO: Inline and simplify the non-working-copy version of this code
1542 # since it shares very little with the working-copy version of it.
1542 # since it shares very little with the working-copy version of it.
1543 ctx_to_walk = ctx if ctx.rev() is None else pctx
1543 ctx_to_walk = ctx if ctx.rev() is None else pctx
1544 m = scmutil.match(ctx_to_walk, [pat], opts, globbed=True)
1544 m = scmutil.match(ctx_to_walk, [pat], opts, globbed=True)
1545 for abs in ctx_to_walk.walk(m):
1545 for abs in ctx_to_walk.walk(m):
1546 rel = uipathfn(abs)
1546 rel = uipathfn(abs)
1547 exact = m.exact(abs)
1547 exact = m.exact(abs)
1548 if abs not in ctx:
1548 if abs not in ctx:
1549 if abs in pctx:
1549 if abs in pctx:
1550 if not after:
1550 if not after:
1551 if exact:
1551 if exact:
1552 ui.warn(
1552 ui.warn(
1553 _(
1553 _(
1554 b'%s: not copying - file has been marked '
1554 b'%s: not copying - file has been marked '
1555 b'for remove\n'
1555 b'for remove\n'
1556 )
1556 )
1557 % rel
1557 % rel
1558 )
1558 )
1559 continue
1559 continue
1560 else:
1560 else:
1561 if exact:
1561 if exact:
1562 ui.warn(
1562 ui.warn(
1563 _(b'%s: not copying - file is not managed\n') % rel
1563 _(b'%s: not copying - file is not managed\n') % rel
1564 )
1564 )
1565 continue
1565 continue
1566
1566
1567 # abs: hgsep
1567 # abs: hgsep
1568 # rel: ossep
1568 # rel: ossep
1569 srcs.append((abs, rel, exact))
1569 srcs.append((abs, rel, exact))
1570 return srcs
1570 return srcs
1571
1571
1572 if ctx.rev() is not None:
1572 if ctx.rev() is not None:
1573 rewriteutil.precheck(repo, [ctx.rev()], b'uncopy')
1573 rewriteutil.precheck(repo, [ctx.rev()], b'uncopy')
1574 absdest = pathutil.canonpath(repo.root, cwd, dest)
1574 absdest = pathutil.canonpath(repo.root, cwd, dest)
1575 if ctx.hasdir(absdest):
1575 if ctx.hasdir(absdest):
1576 raise error.InputError(
1576 raise error.InputError(
1577 _(b'%s: --at-rev does not support a directory as destination')
1577 _(b'%s: --at-rev does not support a directory as destination')
1578 % uipathfn(absdest)
1578 % uipathfn(absdest)
1579 )
1579 )
1580 if absdest not in ctx:
1580 if absdest not in ctx:
1581 raise error.InputError(
1581 raise error.InputError(
1582 _(b'%s: copy destination does not exist in %s')
1582 _(b'%s: copy destination does not exist in %s')
1583 % (uipathfn(absdest), ctx)
1583 % (uipathfn(absdest), ctx)
1584 )
1584 )
1585
1585
1586 # avoid cycle context -> subrepo -> cmdutil
1586 # avoid cycle context -> subrepo -> cmdutil
1587 from . import context
1587 from . import context
1588
1588
1589 copylist = []
1589 copylist = []
1590 for pat in pats:
1590 for pat in pats:
1591 srcs = walkpat(pat)
1591 srcs = walkpat(pat)
1592 if not srcs:
1592 if not srcs:
1593 continue
1593 continue
1594 for abs, rel, exact in srcs:
1594 for abs, rel, exact in srcs:
1595 copylist.append(abs)
1595 copylist.append(abs)
1596
1596
1597 if not copylist:
1597 if not copylist:
1598 raise error.InputError(_(b'no files to copy'))
1598 raise error.InputError(_(b'no files to copy'))
1599 # TODO: Add support for `hg cp --at-rev . foo bar dir` and
1599 # TODO: Add support for `hg cp --at-rev . foo bar dir` and
1600 # `hg cp --at-rev . dir1 dir2`, preferably unifying the code with the
1600 # `hg cp --at-rev . dir1 dir2`, preferably unifying the code with the
1601 # existing functions below.
1601 # existing functions below.
1602 if len(copylist) != 1:
1602 if len(copylist) != 1:
1603 raise error.InputError(_(b'--at-rev requires a single source'))
1603 raise error.InputError(_(b'--at-rev requires a single source'))
1604
1604
1605 new_ctx = context.overlayworkingctx(repo)
1605 new_ctx = context.overlayworkingctx(repo)
1606 new_ctx.setbase(ctx.p1())
1606 new_ctx.setbase(ctx.p1())
1607 mergemod.graft(repo, ctx, wctx=new_ctx)
1607 mergemod.graft(repo, ctx, wctx=new_ctx)
1608
1608
1609 new_ctx.markcopied(absdest, copylist[0])
1609 new_ctx.markcopied(absdest, copylist[0])
1610
1610
1611 with repo.lock():
1611 with repo.lock():
1612 mem_ctx = new_ctx.tomemctx_for_amend(ctx)
1612 mem_ctx = new_ctx.tomemctx_for_amend(ctx)
1613 new_node = mem_ctx.commit()
1613 new_node = mem_ctx.commit()
1614
1614
1615 if repo.dirstate.p1() == ctx.node():
1615 if repo.dirstate.p1() == ctx.node():
1616 with repo.dirstate.parentchange():
1616 with repo.dirstate.parentchange():
1617 scmutil.movedirstate(repo, repo[new_node])
1617 scmutil.movedirstate(repo, repo[new_node])
1618 replacements = {ctx.node(): [new_node]}
1618 replacements = {ctx.node(): [new_node]}
1619 scmutil.cleanupnodes(repo, replacements, b'copy', fixphase=True)
1619 scmutil.cleanupnodes(repo, replacements, b'copy', fixphase=True)
1620
1620
1621 return
1621 return
1622
1622
1623 # abssrc: hgsep
1623 # abssrc: hgsep
1624 # relsrc: ossep
1624 # relsrc: ossep
1625 # otarget: ossep
1625 # otarget: ossep
1626 def copyfile(abssrc, relsrc, otarget, exact):
1626 def copyfile(abssrc, relsrc, otarget, exact):
1627 abstarget = pathutil.canonpath(repo.root, cwd, otarget)
1627 abstarget = pathutil.canonpath(repo.root, cwd, otarget)
1628 if b'/' in abstarget:
1628 if b'/' in abstarget:
1629 # We cannot normalize abstarget itself, this would prevent
1629 # We cannot normalize abstarget itself, this would prevent
1630 # case only renames, like a => A.
1630 # case only renames, like a => A.
1631 abspath, absname = abstarget.rsplit(b'/', 1)
1631 abspath, absname = abstarget.rsplit(b'/', 1)
1632 abstarget = repo.dirstate.normalize(abspath) + b'/' + absname
1632 abstarget = repo.dirstate.normalize(abspath) + b'/' + absname
1633 reltarget = repo.pathto(abstarget, cwd)
1633 reltarget = repo.pathto(abstarget, cwd)
1634 target = repo.wjoin(abstarget)
1634 target = repo.wjoin(abstarget)
1635 src = repo.wjoin(abssrc)
1635 src = repo.wjoin(abssrc)
1636 state = repo.dirstate[abstarget]
1636 state = repo.dirstate[abstarget]
1637
1637
1638 scmutil.checkportable(ui, abstarget)
1638 scmutil.checkportable(ui, abstarget)
1639
1639
1640 # check for collisions
1640 # check for collisions
1641 prevsrc = targets.get(abstarget)
1641 prevsrc = targets.get(abstarget)
1642 if prevsrc is not None:
1642 if prevsrc is not None:
1643 ui.warn(
1643 ui.warn(
1644 _(b'%s: not overwriting - %s collides with %s\n')
1644 _(b'%s: not overwriting - %s collides with %s\n')
1645 % (
1645 % (
1646 reltarget,
1646 reltarget,
1647 repo.pathto(abssrc, cwd),
1647 repo.pathto(abssrc, cwd),
1648 repo.pathto(prevsrc, cwd),
1648 repo.pathto(prevsrc, cwd),
1649 )
1649 )
1650 )
1650 )
1651 return True # report a failure
1651 return True # report a failure
1652
1652
1653 # check for overwrites
1653 # check for overwrites
1654 exists = os.path.lexists(target)
1654 exists = os.path.lexists(target)
1655 samefile = False
1655 samefile = False
1656 if exists and abssrc != abstarget:
1656 if exists and abssrc != abstarget:
1657 if repo.dirstate.normalize(abssrc) == repo.dirstate.normalize(
1657 if repo.dirstate.normalize(abssrc) == repo.dirstate.normalize(
1658 abstarget
1658 abstarget
1659 ):
1659 ):
1660 if not rename:
1660 if not rename:
1661 ui.warn(_(b"%s: can't copy - same file\n") % reltarget)
1661 ui.warn(_(b"%s: can't copy - same file\n") % reltarget)
1662 return True # report a failure
1662 return True # report a failure
1663 exists = False
1663 exists = False
1664 samefile = True
1664 samefile = True
1665
1665
1666 if not after and exists or after and state in b'mn':
1666 if not after and exists or after and state in b'mn':
1667 if not opts[b'force']:
1667 if not opts[b'force']:
1668 if state in b'mn':
1668 if state in b'mn':
1669 msg = _(b'%s: not overwriting - file already committed\n')
1669 msg = _(b'%s: not overwriting - file already committed\n')
1670 if after:
1670 if after:
1671 flags = b'--after --force'
1671 flags = b'--after --force'
1672 else:
1672 else:
1673 flags = b'--force'
1673 flags = b'--force'
1674 if rename:
1674 if rename:
1675 hint = (
1675 hint = (
1676 _(
1676 _(
1677 b"('hg rename %s' to replace the file by "
1677 b"('hg rename %s' to replace the file by "
1678 b'recording a rename)\n'
1678 b'recording a rename)\n'
1679 )
1679 )
1680 % flags
1680 % flags
1681 )
1681 )
1682 else:
1682 else:
1683 hint = (
1683 hint = (
1684 _(
1684 _(
1685 b"('hg copy %s' to replace the file by "
1685 b"('hg copy %s' to replace the file by "
1686 b'recording a copy)\n'
1686 b'recording a copy)\n'
1687 )
1687 )
1688 % flags
1688 % flags
1689 )
1689 )
1690 else:
1690 else:
1691 msg = _(b'%s: not overwriting - file exists\n')
1691 msg = _(b'%s: not overwriting - file exists\n')
1692 if rename:
1692 if rename:
1693 hint = _(
1693 hint = _(
1694 b"('hg rename --after' to record the rename)\n"
1694 b"('hg rename --after' to record the rename)\n"
1695 )
1695 )
1696 else:
1696 else:
1697 hint = _(b"('hg copy --after' to record the copy)\n")
1697 hint = _(b"('hg copy --after' to record the copy)\n")
1698 ui.warn(msg % reltarget)
1698 ui.warn(msg % reltarget)
1699 ui.warn(hint)
1699 ui.warn(hint)
1700 return True # report a failure
1700 return True # report a failure
1701
1701
1702 if after:
1702 if after:
1703 if not exists:
1703 if not exists:
1704 if rename:
1704 if rename:
1705 ui.warn(
1705 ui.warn(
1706 _(b'%s: not recording move - %s does not exist\n')
1706 _(b'%s: not recording move - %s does not exist\n')
1707 % (relsrc, reltarget)
1707 % (relsrc, reltarget)
1708 )
1708 )
1709 else:
1709 else:
1710 ui.warn(
1710 ui.warn(
1711 _(b'%s: not recording copy - %s does not exist\n')
1711 _(b'%s: not recording copy - %s does not exist\n')
1712 % (relsrc, reltarget)
1712 % (relsrc, reltarget)
1713 )
1713 )
1714 return True # report a failure
1714 return True # report a failure
1715 elif not dryrun:
1715 elif not dryrun:
1716 try:
1716 try:
1717 if exists:
1717 if exists:
1718 os.unlink(target)
1718 os.unlink(target)
1719 targetdir = os.path.dirname(target) or b'.'
1719 targetdir = os.path.dirname(target) or b'.'
1720 if not os.path.isdir(targetdir):
1720 if not os.path.isdir(targetdir):
1721 os.makedirs(targetdir)
1721 os.makedirs(targetdir)
1722 if samefile:
1722 if samefile:
1723 tmp = target + b"~hgrename"
1723 tmp = target + b"~hgrename"
1724 os.rename(src, tmp)
1724 os.rename(src, tmp)
1725 os.rename(tmp, target)
1725 os.rename(tmp, target)
1726 else:
1726 else:
1727 # Preserve stat info on renames, not on copies; this matches
1727 # Preserve stat info on renames, not on copies; this matches
1728 # Linux CLI behavior.
1728 # Linux CLI behavior.
1729 util.copyfile(src, target, copystat=rename)
1729 util.copyfile(src, target, copystat=rename)
1730 srcexists = True
1730 srcexists = True
1731 except IOError as inst:
1731 except IOError as inst:
1732 if inst.errno == errno.ENOENT:
1732 if inst.errno == errno.ENOENT:
1733 ui.warn(_(b'%s: deleted in working directory\n') % relsrc)
1733 ui.warn(_(b'%s: deleted in working directory\n') % relsrc)
1734 srcexists = False
1734 srcexists = False
1735 else:
1735 else:
1736 ui.warn(
1736 ui.warn(
1737 _(b'%s: cannot copy - %s\n')
1737 _(b'%s: cannot copy - %s\n')
1738 % (relsrc, encoding.strtolocal(inst.strerror))
1738 % (relsrc, encoding.strtolocal(inst.strerror))
1739 )
1739 )
1740 return True # report a failure
1740 return True # report a failure
1741
1741
1742 if ui.verbose or not exact:
1742 if ui.verbose or not exact:
1743 if rename:
1743 if rename:
1744 ui.status(_(b'moving %s to %s\n') % (relsrc, reltarget))
1744 ui.status(_(b'moving %s to %s\n') % (relsrc, reltarget))
1745 else:
1745 else:
1746 ui.status(_(b'copying %s to %s\n') % (relsrc, reltarget))
1746 ui.status(_(b'copying %s to %s\n') % (relsrc, reltarget))
1747
1747
1748 targets[abstarget] = abssrc
1748 targets[abstarget] = abssrc
1749
1749
1750 # fix up dirstate
1750 # fix up dirstate
1751 scmutil.dirstatecopy(
1751 scmutil.dirstatecopy(
1752 ui, repo, ctx, abssrc, abstarget, dryrun=dryrun, cwd=cwd
1752 ui, repo, ctx, abssrc, abstarget, dryrun=dryrun, cwd=cwd
1753 )
1753 )
1754 if rename and not dryrun:
1754 if rename and not dryrun:
1755 if not after and srcexists and not samefile:
1755 if not after and srcexists and not samefile:
1756 rmdir = repo.ui.configbool(b'experimental', b'removeemptydirs')
1756 rmdir = repo.ui.configbool(b'experimental', b'removeemptydirs')
1757 repo.wvfs.unlinkpath(abssrc, rmdir=rmdir)
1757 repo.wvfs.unlinkpath(abssrc, rmdir=rmdir)
1758 ctx.forget([abssrc])
1758 ctx.forget([abssrc])
1759
1759
1760 # pat: ossep
1760 # pat: ossep
1761 # dest ossep
1761 # dest ossep
1762 # srcs: list of (hgsep, hgsep, ossep, bool)
1762 # srcs: list of (hgsep, hgsep, ossep, bool)
1763 # return: function that takes hgsep and returns ossep
1763 # return: function that takes hgsep and returns ossep
1764 def targetpathfn(pat, dest, srcs):
1764 def targetpathfn(pat, dest, srcs):
1765 if os.path.isdir(pat):
1765 if os.path.isdir(pat):
1766 abspfx = pathutil.canonpath(repo.root, cwd, pat)
1766 abspfx = pathutil.canonpath(repo.root, cwd, pat)
1767 abspfx = util.localpath(abspfx)
1767 abspfx = util.localpath(abspfx)
1768 if destdirexists:
1768 if destdirexists:
1769 striplen = len(os.path.split(abspfx)[0])
1769 striplen = len(os.path.split(abspfx)[0])
1770 else:
1770 else:
1771 striplen = len(abspfx)
1771 striplen = len(abspfx)
1772 if striplen:
1772 if striplen:
1773 striplen += len(pycompat.ossep)
1773 striplen += len(pycompat.ossep)
1774 res = lambda p: os.path.join(dest, util.localpath(p)[striplen:])
1774 res = lambda p: os.path.join(dest, util.localpath(p)[striplen:])
1775 elif destdirexists:
1775 elif destdirexists:
1776 res = lambda p: os.path.join(
1776 res = lambda p: os.path.join(
1777 dest, os.path.basename(util.localpath(p))
1777 dest, os.path.basename(util.localpath(p))
1778 )
1778 )
1779 else:
1779 else:
1780 res = lambda p: dest
1780 res = lambda p: dest
1781 return res
1781 return res
1782
1782
1783 # pat: ossep
1783 # pat: ossep
1784 # dest ossep
1784 # dest ossep
1785 # srcs: list of (hgsep, hgsep, ossep, bool)
1785 # srcs: list of (hgsep, hgsep, ossep, bool)
1786 # return: function that takes hgsep and returns ossep
1786 # return: function that takes hgsep and returns ossep
1787 def targetpathafterfn(pat, dest, srcs):
1787 def targetpathafterfn(pat, dest, srcs):
1788 if matchmod.patkind(pat):
1788 if matchmod.patkind(pat):
1789 # a mercurial pattern
1789 # a mercurial pattern
1790 res = lambda p: os.path.join(
1790 res = lambda p: os.path.join(
1791 dest, os.path.basename(util.localpath(p))
1791 dest, os.path.basename(util.localpath(p))
1792 )
1792 )
1793 else:
1793 else:
1794 abspfx = pathutil.canonpath(repo.root, cwd, pat)
1794 abspfx = pathutil.canonpath(repo.root, cwd, pat)
1795 if len(abspfx) < len(srcs[0][0]):
1795 if len(abspfx) < len(srcs[0][0]):
1796 # A directory. Either the target path contains the last
1796 # A directory. Either the target path contains the last
1797 # component of the source path or it does not.
1797 # component of the source path or it does not.
1798 def evalpath(striplen):
1798 def evalpath(striplen):
1799 score = 0
1799 score = 0
1800 for s in srcs:
1800 for s in srcs:
1801 t = os.path.join(dest, util.localpath(s[0])[striplen:])
1801 t = os.path.join(dest, util.localpath(s[0])[striplen:])
1802 if os.path.lexists(t):
1802 if os.path.lexists(t):
1803 score += 1
1803 score += 1
1804 return score
1804 return score
1805
1805
1806 abspfx = util.localpath(abspfx)
1806 abspfx = util.localpath(abspfx)
1807 striplen = len(abspfx)
1807 striplen = len(abspfx)
1808 if striplen:
1808 if striplen:
1809 striplen += len(pycompat.ossep)
1809 striplen += len(pycompat.ossep)
1810 if os.path.isdir(os.path.join(dest, os.path.split(abspfx)[1])):
1810 if os.path.isdir(os.path.join(dest, os.path.split(abspfx)[1])):
1811 score = evalpath(striplen)
1811 score = evalpath(striplen)
1812 striplen1 = len(os.path.split(abspfx)[0])
1812 striplen1 = len(os.path.split(abspfx)[0])
1813 if striplen1:
1813 if striplen1:
1814 striplen1 += len(pycompat.ossep)
1814 striplen1 += len(pycompat.ossep)
1815 if evalpath(striplen1) > score:
1815 if evalpath(striplen1) > score:
1816 striplen = striplen1
1816 striplen = striplen1
1817 res = lambda p: os.path.join(dest, util.localpath(p)[striplen:])
1817 res = lambda p: os.path.join(dest, util.localpath(p)[striplen:])
1818 else:
1818 else:
1819 # a file
1819 # a file
1820 if destdirexists:
1820 if destdirexists:
1821 res = lambda p: os.path.join(
1821 res = lambda p: os.path.join(
1822 dest, os.path.basename(util.localpath(p))
1822 dest, os.path.basename(util.localpath(p))
1823 )
1823 )
1824 else:
1824 else:
1825 res = lambda p: dest
1825 res = lambda p: dest
1826 return res
1826 return res
1827
1827
1828 destdirexists = os.path.isdir(dest) and not os.path.islink(dest)
1828 destdirexists = os.path.isdir(dest) and not os.path.islink(dest)
1829 if not destdirexists:
1829 if not destdirexists:
1830 if len(pats) > 1 or matchmod.patkind(pats[0]):
1830 if len(pats) > 1 or matchmod.patkind(pats[0]):
1831 raise error.InputError(
1831 raise error.InputError(
1832 _(
1832 _(
1833 b'with multiple sources, destination must be an '
1833 b'with multiple sources, destination must be an '
1834 b'existing directory'
1834 b'existing directory'
1835 )
1835 )
1836 )
1836 )
1837 if util.endswithsep(dest):
1837 if util.endswithsep(dest):
1838 raise error.InputError(
1838 raise error.InputError(
1839 _(b'destination %s is not a directory') % dest
1839 _(b'destination %s is not a directory') % dest
1840 )
1840 )
1841
1841
1842 tfn = targetpathfn
1842 tfn = targetpathfn
1843 if after:
1843 if after:
1844 tfn = targetpathafterfn
1844 tfn = targetpathafterfn
1845 copylist = []
1845 copylist = []
1846 for pat in pats:
1846 for pat in pats:
1847 srcs = walkpat(pat)
1847 srcs = walkpat(pat)
1848 if not srcs:
1848 if not srcs:
1849 continue
1849 continue
1850 copylist.append((tfn(pat, dest, srcs), srcs))
1850 copylist.append((tfn(pat, dest, srcs), srcs))
1851 if not copylist:
1851 if not copylist:
1852 raise error.InputError(_(b'no files to copy'))
1852 raise error.InputError(_(b'no files to copy'))
1853
1853
1854 errors = 0
1854 errors = 0
1855 for targetpath, srcs in copylist:
1855 for targetpath, srcs in copylist:
1856 for abssrc, relsrc, exact in srcs:
1856 for abssrc, relsrc, exact in srcs:
1857 if copyfile(abssrc, relsrc, targetpath(abssrc), exact):
1857 if copyfile(abssrc, relsrc, targetpath(abssrc), exact):
1858 errors += 1
1858 errors += 1
1859
1859
1860 return errors != 0
1860 return errors != 0
1861
1861
1862
1862
1863 ## facility to let extension process additional data into an import patch
1863 ## facility to let extension process additional data into an import patch
1864 # list of identifier to be executed in order
1864 # list of identifier to be executed in order
1865 extrapreimport = [] # run before commit
1865 extrapreimport = [] # run before commit
1866 extrapostimport = [] # run after commit
1866 extrapostimport = [] # run after commit
1867 # mapping from identifier to actual import function
1867 # mapping from identifier to actual import function
1868 #
1868 #
1869 # 'preimport' are run before the commit is made and are provided the following
1869 # 'preimport' are run before the commit is made and are provided the following
1870 # arguments:
1870 # arguments:
1871 # - repo: the localrepository instance,
1871 # - repo: the localrepository instance,
1872 # - patchdata: data extracted from patch header (cf m.patch.patchheadermap),
1872 # - patchdata: data extracted from patch header (cf m.patch.patchheadermap),
1873 # - extra: the future extra dictionary of the changeset, please mutate it,
1873 # - extra: the future extra dictionary of the changeset, please mutate it,
1874 # - opts: the import options.
1874 # - opts: the import options.
1875 # XXX ideally, we would just pass an ctx ready to be computed, that would allow
1875 # XXX ideally, we would just pass an ctx ready to be computed, that would allow
1876 # mutation of in memory commit and more. Feel free to rework the code to get
1876 # mutation of in memory commit and more. Feel free to rework the code to get
1877 # there.
1877 # there.
1878 extrapreimportmap = {}
1878 extrapreimportmap = {}
1879 # 'postimport' are run after the commit is made and are provided the following
1879 # 'postimport' are run after the commit is made and are provided the following
1880 # argument:
1880 # argument:
1881 # - ctx: the changectx created by import.
1881 # - ctx: the changectx created by import.
1882 extrapostimportmap = {}
1882 extrapostimportmap = {}
1883
1883
1884
1884
1885 def tryimportone(ui, repo, patchdata, parents, opts, msgs, updatefunc):
1885 def tryimportone(ui, repo, patchdata, parents, opts, msgs, updatefunc):
1886 """Utility function used by commands.import to import a single patch
1886 """Utility function used by commands.import to import a single patch
1887
1887
1888 This function is explicitly defined here to help the evolve extension to
1888 This function is explicitly defined here to help the evolve extension to
1889 wrap this part of the import logic.
1889 wrap this part of the import logic.
1890
1890
1891 The API is currently a bit ugly because it a simple code translation from
1891 The API is currently a bit ugly because it a simple code translation from
1892 the import command. Feel free to make it better.
1892 the import command. Feel free to make it better.
1893
1893
1894 :patchdata: a dictionary containing parsed patch data (such as from
1894 :patchdata: a dictionary containing parsed patch data (such as from
1895 ``patch.extract()``)
1895 ``patch.extract()``)
1896 :parents: nodes that will be parent of the created commit
1896 :parents: nodes that will be parent of the created commit
1897 :opts: the full dict of option passed to the import command
1897 :opts: the full dict of option passed to the import command
1898 :msgs: list to save commit message to.
1898 :msgs: list to save commit message to.
1899 (used in case we need to save it when failing)
1899 (used in case we need to save it when failing)
1900 :updatefunc: a function that update a repo to a given node
1900 :updatefunc: a function that update a repo to a given node
1901 updatefunc(<repo>, <node>)
1901 updatefunc(<repo>, <node>)
1902 """
1902 """
1903 # avoid cycle context -> subrepo -> cmdutil
1903 # avoid cycle context -> subrepo -> cmdutil
1904 from . import context
1904 from . import context
1905
1905
1906 tmpname = patchdata.get(b'filename')
1906 tmpname = patchdata.get(b'filename')
1907 message = patchdata.get(b'message')
1907 message = patchdata.get(b'message')
1908 user = opts.get(b'user') or patchdata.get(b'user')
1908 user = opts.get(b'user') or patchdata.get(b'user')
1909 date = opts.get(b'date') or patchdata.get(b'date')
1909 date = opts.get(b'date') or patchdata.get(b'date')
1910 branch = patchdata.get(b'branch')
1910 branch = patchdata.get(b'branch')
1911 nodeid = patchdata.get(b'nodeid')
1911 nodeid = patchdata.get(b'nodeid')
1912 p1 = patchdata.get(b'p1')
1912 p1 = patchdata.get(b'p1')
1913 p2 = patchdata.get(b'p2')
1913 p2 = patchdata.get(b'p2')
1914
1914
1915 nocommit = opts.get(b'no_commit')
1915 nocommit = opts.get(b'no_commit')
1916 importbranch = opts.get(b'import_branch')
1916 importbranch = opts.get(b'import_branch')
1917 update = not opts.get(b'bypass')
1917 update = not opts.get(b'bypass')
1918 strip = opts[b"strip"]
1918 strip = opts[b"strip"]
1919 prefix = opts[b"prefix"]
1919 prefix = opts[b"prefix"]
1920 sim = float(opts.get(b'similarity') or 0)
1920 sim = float(opts.get(b'similarity') or 0)
1921
1921
1922 if not tmpname:
1922 if not tmpname:
1923 return None, None, False
1923 return None, None, False
1924
1924
1925 rejects = False
1925 rejects = False
1926
1926
1927 cmdline_message = logmessage(ui, opts)
1927 cmdline_message = logmessage(ui, opts)
1928 if cmdline_message:
1928 if cmdline_message:
1929 # pickup the cmdline msg
1929 # pickup the cmdline msg
1930 message = cmdline_message
1930 message = cmdline_message
1931 elif message:
1931 elif message:
1932 # pickup the patch msg
1932 # pickup the patch msg
1933 message = message.strip()
1933 message = message.strip()
1934 else:
1934 else:
1935 # launch the editor
1935 # launch the editor
1936 message = None
1936 message = None
1937 ui.debug(b'message:\n%s\n' % (message or b''))
1937 ui.debug(b'message:\n%s\n' % (message or b''))
1938
1938
1939 if len(parents) == 1:
1939 if len(parents) == 1:
1940 parents.append(repo[nullrev])
1940 parents.append(repo[nullrev])
1941 if opts.get(b'exact'):
1941 if opts.get(b'exact'):
1942 if not nodeid or not p1:
1942 if not nodeid or not p1:
1943 raise error.InputError(_(b'not a Mercurial patch'))
1943 raise error.InputError(_(b'not a Mercurial patch'))
1944 p1 = repo[p1]
1944 p1 = repo[p1]
1945 p2 = repo[p2 or nullrev]
1945 p2 = repo[p2 or nullrev]
1946 elif p2:
1946 elif p2:
1947 try:
1947 try:
1948 p1 = repo[p1]
1948 p1 = repo[p1]
1949 p2 = repo[p2]
1949 p2 = repo[p2]
1950 # Without any options, consider p2 only if the
1950 # Without any options, consider p2 only if the
1951 # patch is being applied on top of the recorded
1951 # patch is being applied on top of the recorded
1952 # first parent.
1952 # first parent.
1953 if p1 != parents[0]:
1953 if p1 != parents[0]:
1954 p1 = parents[0]
1954 p1 = parents[0]
1955 p2 = repo[nullrev]
1955 p2 = repo[nullrev]
1956 except error.RepoError:
1956 except error.RepoError:
1957 p1, p2 = parents
1957 p1, p2 = parents
1958 if p2.rev() == nullrev:
1958 if p2.rev() == nullrev:
1959 ui.warn(
1959 ui.warn(
1960 _(
1960 _(
1961 b"warning: import the patch as a normal revision\n"
1961 b"warning: import the patch as a normal revision\n"
1962 b"(use --exact to import the patch as a merge)\n"
1962 b"(use --exact to import the patch as a merge)\n"
1963 )
1963 )
1964 )
1964 )
1965 else:
1965 else:
1966 p1, p2 = parents
1966 p1, p2 = parents
1967
1967
1968 n = None
1968 n = None
1969 if update:
1969 if update:
1970 if p1 != parents[0]:
1970 if p1 != parents[0]:
1971 updatefunc(repo, p1.node())
1971 updatefunc(repo, p1.node())
1972 if p2 != parents[1]:
1972 if p2 != parents[1]:
1973 repo.setparents(p1.node(), p2.node())
1973 repo.setparents(p1.node(), p2.node())
1974
1974
1975 if opts.get(b'exact') or importbranch:
1975 if opts.get(b'exact') or importbranch:
1976 repo.dirstate.setbranch(branch or b'default')
1976 repo.dirstate.setbranch(branch or b'default')
1977
1977
1978 partial = opts.get(b'partial', False)
1978 partial = opts.get(b'partial', False)
1979 files = set()
1979 files = set()
1980 try:
1980 try:
1981 patch.patch(
1981 patch.patch(
1982 ui,
1982 ui,
1983 repo,
1983 repo,
1984 tmpname,
1984 tmpname,
1985 strip=strip,
1985 strip=strip,
1986 prefix=prefix,
1986 prefix=prefix,
1987 files=files,
1987 files=files,
1988 eolmode=None,
1988 eolmode=None,
1989 similarity=sim / 100.0,
1989 similarity=sim / 100.0,
1990 )
1990 )
1991 except error.PatchError as e:
1991 except error.PatchError as e:
1992 if not partial:
1992 if not partial:
1993 raise error.Abort(pycompat.bytestr(e))
1993 raise error.Abort(pycompat.bytestr(e))
1994 if partial:
1994 if partial:
1995 rejects = True
1995 rejects = True
1996
1996
1997 files = list(files)
1997 files = list(files)
1998 if nocommit:
1998 if nocommit:
1999 if message:
1999 if message:
2000 msgs.append(message)
2000 msgs.append(message)
2001 else:
2001 else:
2002 if opts.get(b'exact') or p2:
2002 if opts.get(b'exact') or p2:
2003 # If you got here, you either use --force and know what
2003 # If you got here, you either use --force and know what
2004 # you are doing or used --exact or a merge patch while
2004 # you are doing or used --exact or a merge patch while
2005 # being updated to its first parent.
2005 # being updated to its first parent.
2006 m = None
2006 m = None
2007 else:
2007 else:
2008 m = scmutil.matchfiles(repo, files or [])
2008 m = scmutil.matchfiles(repo, files or [])
2009 editform = mergeeditform(repo[None], b'import.normal')
2009 editform = mergeeditform(repo[None], b'import.normal')
2010 if opts.get(b'exact'):
2010 if opts.get(b'exact'):
2011 editor = None
2011 editor = None
2012 else:
2012 else:
2013 editor = getcommiteditor(
2013 editor = getcommiteditor(
2014 editform=editform, **pycompat.strkwargs(opts)
2014 editform=editform, **pycompat.strkwargs(opts)
2015 )
2015 )
2016 extra = {}
2016 extra = {}
2017 for idfunc in extrapreimport:
2017 for idfunc in extrapreimport:
2018 extrapreimportmap[idfunc](repo, patchdata, extra, opts)
2018 extrapreimportmap[idfunc](repo, patchdata, extra, opts)
2019 overrides = {}
2019 overrides = {}
2020 if partial:
2020 if partial:
2021 overrides[(b'ui', b'allowemptycommit')] = True
2021 overrides[(b'ui', b'allowemptycommit')] = True
2022 if opts.get(b'secret'):
2022 if opts.get(b'secret'):
2023 overrides[(b'phases', b'new-commit')] = b'secret'
2023 overrides[(b'phases', b'new-commit')] = b'secret'
2024 with repo.ui.configoverride(overrides, b'import'):
2024 with repo.ui.configoverride(overrides, b'import'):
2025 n = repo.commit(
2025 n = repo.commit(
2026 message, user, date, match=m, editor=editor, extra=extra
2026 message, user, date, match=m, editor=editor, extra=extra
2027 )
2027 )
2028 for idfunc in extrapostimport:
2028 for idfunc in extrapostimport:
2029 extrapostimportmap[idfunc](repo[n])
2029 extrapostimportmap[idfunc](repo[n])
2030 else:
2030 else:
2031 if opts.get(b'exact') or importbranch:
2031 if opts.get(b'exact') or importbranch:
2032 branch = branch or b'default'
2032 branch = branch or b'default'
2033 else:
2033 else:
2034 branch = p1.branch()
2034 branch = p1.branch()
2035 store = patch.filestore()
2035 store = patch.filestore()
2036 try:
2036 try:
2037 files = set()
2037 files = set()
2038 try:
2038 try:
2039 patch.patchrepo(
2039 patch.patchrepo(
2040 ui,
2040 ui,
2041 repo,
2041 repo,
2042 p1,
2042 p1,
2043 store,
2043 store,
2044 tmpname,
2044 tmpname,
2045 strip,
2045 strip,
2046 prefix,
2046 prefix,
2047 files,
2047 files,
2048 eolmode=None,
2048 eolmode=None,
2049 )
2049 )
2050 except error.PatchError as e:
2050 except error.PatchError as e:
2051 raise error.Abort(stringutil.forcebytestr(e))
2051 raise error.Abort(stringutil.forcebytestr(e))
2052 if opts.get(b'exact'):
2052 if opts.get(b'exact'):
2053 editor = None
2053 editor = None
2054 else:
2054 else:
2055 editor = getcommiteditor(editform=b'import.bypass')
2055 editor = getcommiteditor(editform=b'import.bypass')
2056 memctx = context.memctx(
2056 memctx = context.memctx(
2057 repo,
2057 repo,
2058 (p1.node(), p2.node()),
2058 (p1.node(), p2.node()),
2059 message,
2059 message,
2060 files=files,
2060 files=files,
2061 filectxfn=store,
2061 filectxfn=store,
2062 user=user,
2062 user=user,
2063 date=date,
2063 date=date,
2064 branch=branch,
2064 branch=branch,
2065 editor=editor,
2065 editor=editor,
2066 )
2066 )
2067
2067
2068 overrides = {}
2068 overrides = {}
2069 if opts.get(b'secret'):
2069 if opts.get(b'secret'):
2070 overrides[(b'phases', b'new-commit')] = b'secret'
2070 overrides[(b'phases', b'new-commit')] = b'secret'
2071 with repo.ui.configoverride(overrides, b'import'):
2071 with repo.ui.configoverride(overrides, b'import'):
2072 n = memctx.commit()
2072 n = memctx.commit()
2073 finally:
2073 finally:
2074 store.close()
2074 store.close()
2075 if opts.get(b'exact') and nocommit:
2075 if opts.get(b'exact') and nocommit:
2076 # --exact with --no-commit is still useful in that it does merge
2076 # --exact with --no-commit is still useful in that it does merge
2077 # and branch bits
2077 # and branch bits
2078 ui.warn(_(b"warning: can't check exact import with --no-commit\n"))
2078 ui.warn(_(b"warning: can't check exact import with --no-commit\n"))
2079 elif opts.get(b'exact') and (not n or hex(n) != nodeid):
2079 elif opts.get(b'exact') and (not n or hex(n) != nodeid):
2080 raise error.Abort(_(b'patch is damaged or loses information'))
2080 raise error.Abort(_(b'patch is damaged or loses information'))
2081 msg = _(b'applied to working directory')
2081 msg = _(b'applied to working directory')
2082 if n:
2082 if n:
2083 # i18n: refers to a short changeset id
2083 # i18n: refers to a short changeset id
2084 msg = _(b'created %s') % short(n)
2084 msg = _(b'created %s') % short(n)
2085 return msg, n, rejects
2085 return msg, n, rejects
2086
2086
2087
2087
2088 # facility to let extensions include additional data in an exported patch
2088 # facility to let extensions include additional data in an exported patch
2089 # list of identifiers to be executed in order
2089 # list of identifiers to be executed in order
2090 extraexport = []
2090 extraexport = []
2091 # mapping from identifier to actual export function
2091 # mapping from identifier to actual export function
2092 # function as to return a string to be added to the header or None
2092 # function as to return a string to be added to the header or None
2093 # it is given two arguments (sequencenumber, changectx)
2093 # it is given two arguments (sequencenumber, changectx)
2094 extraexportmap = {}
2094 extraexportmap = {}
2095
2095
2096
2096
2097 def _exportsingle(repo, ctx, fm, match, switch_parent, seqno, diffopts):
2097 def _exportsingle(repo, ctx, fm, match, switch_parent, seqno, diffopts):
2098 node = scmutil.binnode(ctx)
2098 node = scmutil.binnode(ctx)
2099 parents = [p.node() for p in ctx.parents() if p]
2099 parents = [p.node() for p in ctx.parents() if p]
2100 branch = ctx.branch()
2100 branch = ctx.branch()
2101 if switch_parent:
2101 if switch_parent:
2102 parents.reverse()
2102 parents.reverse()
2103
2103
2104 if parents:
2104 if parents:
2105 prev = parents[0]
2105 prev = parents[0]
2106 else:
2106 else:
2107 prev = nullid
2107 prev = nullid
2108
2108
2109 fm.context(ctx=ctx)
2109 fm.context(ctx=ctx)
2110 fm.plain(b'# HG changeset patch\n')
2110 fm.plain(b'# HG changeset patch\n')
2111 fm.write(b'user', b'# User %s\n', ctx.user())
2111 fm.write(b'user', b'# User %s\n', ctx.user())
2112 fm.plain(b'# Date %d %d\n' % ctx.date())
2112 fm.plain(b'# Date %d %d\n' % ctx.date())
2113 fm.write(b'date', b'# %s\n', fm.formatdate(ctx.date()))
2113 fm.write(b'date', b'# %s\n', fm.formatdate(ctx.date()))
2114 fm.condwrite(
2114 fm.condwrite(
2115 branch and branch != b'default', b'branch', b'# Branch %s\n', branch
2115 branch and branch != b'default', b'branch', b'# Branch %s\n', branch
2116 )
2116 )
2117 fm.write(b'node', b'# Node ID %s\n', hex(node))
2117 fm.write(b'node', b'# Node ID %s\n', hex(node))
2118 fm.plain(b'# Parent %s\n' % hex(prev))
2118 fm.plain(b'# Parent %s\n' % hex(prev))
2119 if len(parents) > 1:
2119 if len(parents) > 1:
2120 fm.plain(b'# Parent %s\n' % hex(parents[1]))
2120 fm.plain(b'# Parent %s\n' % hex(parents[1]))
2121 fm.data(parents=fm.formatlist(pycompat.maplist(hex, parents), name=b'node'))
2121 fm.data(parents=fm.formatlist(pycompat.maplist(hex, parents), name=b'node'))
2122
2122
2123 # TODO: redesign extraexportmap function to support formatter
2123 # TODO: redesign extraexportmap function to support formatter
2124 for headerid in extraexport:
2124 for headerid in extraexport:
2125 header = extraexportmap[headerid](seqno, ctx)
2125 header = extraexportmap[headerid](seqno, ctx)
2126 if header is not None:
2126 if header is not None:
2127 fm.plain(b'# %s\n' % header)
2127 fm.plain(b'# %s\n' % header)
2128
2128
2129 fm.write(b'desc', b'%s\n', ctx.description().rstrip())
2129 fm.write(b'desc', b'%s\n', ctx.description().rstrip())
2130 fm.plain(b'\n')
2130 fm.plain(b'\n')
2131
2131
2132 if fm.isplain():
2132 if fm.isplain():
2133 chunkiter = patch.diffui(repo, prev, node, match, opts=diffopts)
2133 chunkiter = patch.diffui(repo, prev, node, match, opts=diffopts)
2134 for chunk, label in chunkiter:
2134 for chunk, label in chunkiter:
2135 fm.plain(chunk, label=label)
2135 fm.plain(chunk, label=label)
2136 else:
2136 else:
2137 chunkiter = patch.diff(repo, prev, node, match, opts=diffopts)
2137 chunkiter = patch.diff(repo, prev, node, match, opts=diffopts)
2138 # TODO: make it structured?
2138 # TODO: make it structured?
2139 fm.data(diff=b''.join(chunkiter))
2139 fm.data(diff=b''.join(chunkiter))
2140
2140
2141
2141
2142 def _exportfile(repo, revs, fm, dest, switch_parent, diffopts, match):
2142 def _exportfile(repo, revs, fm, dest, switch_parent, diffopts, match):
2143 """Export changesets to stdout or a single file"""
2143 """Export changesets to stdout or a single file"""
2144 for seqno, rev in enumerate(revs, 1):
2144 for seqno, rev in enumerate(revs, 1):
2145 ctx = repo[rev]
2145 ctx = repo[rev]
2146 if not dest.startswith(b'<'):
2146 if not dest.startswith(b'<'):
2147 repo.ui.note(b"%s\n" % dest)
2147 repo.ui.note(b"%s\n" % dest)
2148 fm.startitem()
2148 fm.startitem()
2149 _exportsingle(repo, ctx, fm, match, switch_parent, seqno, diffopts)
2149 _exportsingle(repo, ctx, fm, match, switch_parent, seqno, diffopts)
2150
2150
2151
2151
2152 def _exportfntemplate(
2152 def _exportfntemplate(
2153 repo, revs, basefm, fntemplate, switch_parent, diffopts, match
2153 repo, revs, basefm, fntemplate, switch_parent, diffopts, match
2154 ):
2154 ):
2155 """Export changesets to possibly multiple files"""
2155 """Export changesets to possibly multiple files"""
2156 total = len(revs)
2156 total = len(revs)
2157 revwidth = max(len(str(rev)) for rev in revs)
2157 revwidth = max(len(str(rev)) for rev in revs)
2158 filemap = util.sortdict() # filename: [(seqno, rev), ...]
2158 filemap = util.sortdict() # filename: [(seqno, rev), ...]
2159
2159
2160 for seqno, rev in enumerate(revs, 1):
2160 for seqno, rev in enumerate(revs, 1):
2161 ctx = repo[rev]
2161 ctx = repo[rev]
2162 dest = makefilename(
2162 dest = makefilename(
2163 ctx, fntemplate, total=total, seqno=seqno, revwidth=revwidth
2163 ctx, fntemplate, total=total, seqno=seqno, revwidth=revwidth
2164 )
2164 )
2165 filemap.setdefault(dest, []).append((seqno, rev))
2165 filemap.setdefault(dest, []).append((seqno, rev))
2166
2166
2167 for dest in filemap:
2167 for dest in filemap:
2168 with formatter.maybereopen(basefm, dest) as fm:
2168 with formatter.maybereopen(basefm, dest) as fm:
2169 repo.ui.note(b"%s\n" % dest)
2169 repo.ui.note(b"%s\n" % dest)
2170 for seqno, rev in filemap[dest]:
2170 for seqno, rev in filemap[dest]:
2171 fm.startitem()
2171 fm.startitem()
2172 ctx = repo[rev]
2172 ctx = repo[rev]
2173 _exportsingle(
2173 _exportsingle(
2174 repo, ctx, fm, match, switch_parent, seqno, diffopts
2174 repo, ctx, fm, match, switch_parent, seqno, diffopts
2175 )
2175 )
2176
2176
2177
2177
2178 def _prefetchchangedfiles(repo, revs, match):
2178 def _prefetchchangedfiles(repo, revs, match):
2179 allfiles = set()
2179 allfiles = set()
2180 for rev in revs:
2180 for rev in revs:
2181 for file in repo[rev].files():
2181 for file in repo[rev].files():
2182 if not match or match(file):
2182 if not match or match(file):
2183 allfiles.add(file)
2183 allfiles.add(file)
2184 match = scmutil.matchfiles(repo, allfiles)
2184 match = scmutil.matchfiles(repo, allfiles)
2185 revmatches = [(rev, match) for rev in revs]
2185 revmatches = [(rev, match) for rev in revs]
2186 scmutil.prefetchfiles(repo, revmatches)
2186 scmutil.prefetchfiles(repo, revmatches)
2187
2187
2188
2188
2189 def export(
2189 def export(
2190 repo,
2190 repo,
2191 revs,
2191 revs,
2192 basefm,
2192 basefm,
2193 fntemplate=b'hg-%h.patch',
2193 fntemplate=b'hg-%h.patch',
2194 switch_parent=False,
2194 switch_parent=False,
2195 opts=None,
2195 opts=None,
2196 match=None,
2196 match=None,
2197 ):
2197 ):
2198 """export changesets as hg patches
2198 """export changesets as hg patches
2199
2199
2200 Args:
2200 Args:
2201 repo: The repository from which we're exporting revisions.
2201 repo: The repository from which we're exporting revisions.
2202 revs: A list of revisions to export as revision numbers.
2202 revs: A list of revisions to export as revision numbers.
2203 basefm: A formatter to which patches should be written.
2203 basefm: A formatter to which patches should be written.
2204 fntemplate: An optional string to use for generating patch file names.
2204 fntemplate: An optional string to use for generating patch file names.
2205 switch_parent: If True, show diffs against second parent when not nullid.
2205 switch_parent: If True, show diffs against second parent when not nullid.
2206 Default is false, which always shows diff against p1.
2206 Default is false, which always shows diff against p1.
2207 opts: diff options to use for generating the patch.
2207 opts: diff options to use for generating the patch.
2208 match: If specified, only export changes to files matching this matcher.
2208 match: If specified, only export changes to files matching this matcher.
2209
2209
2210 Returns:
2210 Returns:
2211 Nothing.
2211 Nothing.
2212
2212
2213 Side Effect:
2213 Side Effect:
2214 "HG Changeset Patch" data is emitted to one of the following
2214 "HG Changeset Patch" data is emitted to one of the following
2215 destinations:
2215 destinations:
2216 fntemplate specified: Each rev is written to a unique file named using
2216 fntemplate specified: Each rev is written to a unique file named using
2217 the given template.
2217 the given template.
2218 Otherwise: All revs will be written to basefm.
2218 Otherwise: All revs will be written to basefm.
2219 """
2219 """
2220 _prefetchchangedfiles(repo, revs, match)
2220 _prefetchchangedfiles(repo, revs, match)
2221
2221
2222 if not fntemplate:
2222 if not fntemplate:
2223 _exportfile(
2223 _exportfile(
2224 repo, revs, basefm, b'<unnamed>', switch_parent, opts, match
2224 repo, revs, basefm, b'<unnamed>', switch_parent, opts, match
2225 )
2225 )
2226 else:
2226 else:
2227 _exportfntemplate(
2227 _exportfntemplate(
2228 repo, revs, basefm, fntemplate, switch_parent, opts, match
2228 repo, revs, basefm, fntemplate, switch_parent, opts, match
2229 )
2229 )
2230
2230
2231
2231
2232 def exportfile(repo, revs, fp, switch_parent=False, opts=None, match=None):
2232 def exportfile(repo, revs, fp, switch_parent=False, opts=None, match=None):
2233 """Export changesets to the given file stream"""
2233 """Export changesets to the given file stream"""
2234 _prefetchchangedfiles(repo, revs, match)
2234 _prefetchchangedfiles(repo, revs, match)
2235
2235
2236 dest = getattr(fp, 'name', b'<unnamed>')
2236 dest = getattr(fp, 'name', b'<unnamed>')
2237 with formatter.formatter(repo.ui, fp, b'export', {}) as fm:
2237 with formatter.formatter(repo.ui, fp, b'export', {}) as fm:
2238 _exportfile(repo, revs, fm, dest, switch_parent, opts, match)
2238 _exportfile(repo, revs, fm, dest, switch_parent, opts, match)
2239
2239
2240
2240
2241 def showmarker(fm, marker, index=None):
2241 def showmarker(fm, marker, index=None):
2242 """utility function to display obsolescence marker in a readable way
2242 """utility function to display obsolescence marker in a readable way
2243
2243
2244 To be used by debug function."""
2244 To be used by debug function."""
2245 if index is not None:
2245 if index is not None:
2246 fm.write(b'index', b'%i ', index)
2246 fm.write(b'index', b'%i ', index)
2247 fm.write(b'prednode', b'%s ', hex(marker.prednode()))
2247 fm.write(b'prednode', b'%s ', hex(marker.prednode()))
2248 succs = marker.succnodes()
2248 succs = marker.succnodes()
2249 fm.condwrite(
2249 fm.condwrite(
2250 succs,
2250 succs,
2251 b'succnodes',
2251 b'succnodes',
2252 b'%s ',
2252 b'%s ',
2253 fm.formatlist(map(hex, succs), name=b'node'),
2253 fm.formatlist(map(hex, succs), name=b'node'),
2254 )
2254 )
2255 fm.write(b'flag', b'%X ', marker.flags())
2255 fm.write(b'flag', b'%X ', marker.flags())
2256 parents = marker.parentnodes()
2256 parents = marker.parentnodes()
2257 if parents is not None:
2257 if parents is not None:
2258 fm.write(
2258 fm.write(
2259 b'parentnodes',
2259 b'parentnodes',
2260 b'{%s} ',
2260 b'{%s} ',
2261 fm.formatlist(map(hex, parents), name=b'node', sep=b', '),
2261 fm.formatlist(map(hex, parents), name=b'node', sep=b', '),
2262 )
2262 )
2263 fm.write(b'date', b'(%s) ', fm.formatdate(marker.date()))
2263 fm.write(b'date', b'(%s) ', fm.formatdate(marker.date()))
2264 meta = marker.metadata().copy()
2264 meta = marker.metadata().copy()
2265 meta.pop(b'date', None)
2265 meta.pop(b'date', None)
2266 smeta = pycompat.rapply(pycompat.maybebytestr, meta)
2266 smeta = pycompat.rapply(pycompat.maybebytestr, meta)
2267 fm.write(
2267 fm.write(
2268 b'metadata', b'{%s}', fm.formatdict(smeta, fmt=b'%r: %r', sep=b', ')
2268 b'metadata', b'{%s}', fm.formatdict(smeta, fmt=b'%r: %r', sep=b', ')
2269 )
2269 )
2270 fm.plain(b'\n')
2270 fm.plain(b'\n')
2271
2271
2272
2272
2273 def finddate(ui, repo, date):
2273 def finddate(ui, repo, date):
2274 """Find the tipmost changeset that matches the given date spec"""
2274 """Find the tipmost changeset that matches the given date spec"""
2275 mrevs = repo.revs(b'date(%s)', date)
2275 mrevs = repo.revs(b'date(%s)', date)
2276 try:
2276 try:
2277 rev = mrevs.max()
2277 rev = mrevs.max()
2278 except ValueError:
2278 except ValueError:
2279 raise error.InputError(_(b"revision matching date not found"))
2279 raise error.InputError(_(b"revision matching date not found"))
2280
2280
2281 ui.status(
2281 ui.status(
2282 _(b"found revision %d from %s\n")
2282 _(b"found revision %d from %s\n")
2283 % (rev, dateutil.datestr(repo[rev].date()))
2283 % (rev, dateutil.datestr(repo[rev].date()))
2284 )
2284 )
2285 return b'%d' % rev
2285 return b'%d' % rev
2286
2286
2287
2287
2288 def add(ui, repo, match, prefix, uipathfn, explicitonly, **opts):
2288 def add(ui, repo, match, prefix, uipathfn, explicitonly, **opts):
2289 bad = []
2289 bad = []
2290
2290
2291 badfn = lambda x, y: bad.append(x) or match.bad(x, y)
2291 badfn = lambda x, y: bad.append(x) or match.bad(x, y)
2292 names = []
2292 names = []
2293 wctx = repo[None]
2293 wctx = repo[None]
2294 cca = None
2294 cca = None
2295 abort, warn = scmutil.checkportabilityalert(ui)
2295 abort, warn = scmutil.checkportabilityalert(ui)
2296 if abort or warn:
2296 if abort or warn:
2297 cca = scmutil.casecollisionauditor(ui, abort, repo.dirstate)
2297 cca = scmutil.casecollisionauditor(ui, abort, repo.dirstate)
2298
2298
2299 match = repo.narrowmatch(match, includeexact=True)
2299 match = repo.narrowmatch(match, includeexact=True)
2300 badmatch = matchmod.badmatch(match, badfn)
2300 badmatch = matchmod.badmatch(match, badfn)
2301 dirstate = repo.dirstate
2301 dirstate = repo.dirstate
2302 # We don't want to just call wctx.walk here, since it would return a lot of
2302 # We don't want to just call wctx.walk here, since it would return a lot of
2303 # clean files, which we aren't interested in and takes time.
2303 # clean files, which we aren't interested in and takes time.
2304 for f in sorted(
2304 for f in sorted(
2305 dirstate.walk(
2305 dirstate.walk(
2306 badmatch,
2306 badmatch,
2307 subrepos=sorted(wctx.substate),
2307 subrepos=sorted(wctx.substate),
2308 unknown=True,
2308 unknown=True,
2309 ignored=False,
2309 ignored=False,
2310 full=False,
2310 full=False,
2311 )
2311 )
2312 ):
2312 ):
2313 exact = match.exact(f)
2313 exact = match.exact(f)
2314 if exact or not explicitonly and f not in wctx and repo.wvfs.lexists(f):
2314 if exact or not explicitonly and f not in wctx and repo.wvfs.lexists(f):
2315 if cca:
2315 if cca:
2316 cca(f)
2316 cca(f)
2317 names.append(f)
2317 names.append(f)
2318 if ui.verbose or not exact:
2318 if ui.verbose or not exact:
2319 ui.status(
2319 ui.status(
2320 _(b'adding %s\n') % uipathfn(f), label=b'ui.addremove.added'
2320 _(b'adding %s\n') % uipathfn(f), label=b'ui.addremove.added'
2321 )
2321 )
2322
2322
2323 for subpath in sorted(wctx.substate):
2323 for subpath in sorted(wctx.substate):
2324 sub = wctx.sub(subpath)
2324 sub = wctx.sub(subpath)
2325 try:
2325 try:
2326 submatch = matchmod.subdirmatcher(subpath, match)
2326 submatch = matchmod.subdirmatcher(subpath, match)
2327 subprefix = repo.wvfs.reljoin(prefix, subpath)
2327 subprefix = repo.wvfs.reljoin(prefix, subpath)
2328 subuipathfn = scmutil.subdiruipathfn(subpath, uipathfn)
2328 subuipathfn = scmutil.subdiruipathfn(subpath, uipathfn)
2329 if opts.get('subrepos'):
2329 if opts.get('subrepos'):
2330 bad.extend(
2330 bad.extend(
2331 sub.add(ui, submatch, subprefix, subuipathfn, False, **opts)
2331 sub.add(ui, submatch, subprefix, subuipathfn, False, **opts)
2332 )
2332 )
2333 else:
2333 else:
2334 bad.extend(
2334 bad.extend(
2335 sub.add(ui, submatch, subprefix, subuipathfn, True, **opts)
2335 sub.add(ui, submatch, subprefix, subuipathfn, True, **opts)
2336 )
2336 )
2337 except error.LookupError:
2337 except error.LookupError:
2338 ui.status(
2338 ui.status(
2339 _(b"skipping missing subrepository: %s\n") % uipathfn(subpath)
2339 _(b"skipping missing subrepository: %s\n") % uipathfn(subpath)
2340 )
2340 )
2341
2341
2342 if not opts.get('dry_run'):
2342 if not opts.get('dry_run'):
2343 rejected = wctx.add(names, prefix)
2343 rejected = wctx.add(names, prefix)
2344 bad.extend(f for f in rejected if f in match.files())
2344 bad.extend(f for f in rejected if f in match.files())
2345 return bad
2345 return bad
2346
2346
2347
2347
2348 def addwebdirpath(repo, serverpath, webconf):
2348 def addwebdirpath(repo, serverpath, webconf):
2349 webconf[serverpath] = repo.root
2349 webconf[serverpath] = repo.root
2350 repo.ui.debug(b'adding %s = %s\n' % (serverpath, repo.root))
2350 repo.ui.debug(b'adding %s = %s\n' % (serverpath, repo.root))
2351
2351
2352 for r in repo.revs(b'filelog("path:.hgsub")'):
2352 for r in repo.revs(b'filelog("path:.hgsub")'):
2353 ctx = repo[r]
2353 ctx = repo[r]
2354 for subpath in ctx.substate:
2354 for subpath in ctx.substate:
2355 ctx.sub(subpath).addwebdirpath(serverpath, webconf)
2355 ctx.sub(subpath).addwebdirpath(serverpath, webconf)
2356
2356
2357
2357
2358 def forget(
2358 def forget(
2359 ui, repo, match, prefix, uipathfn, explicitonly, dryrun, interactive
2359 ui, repo, match, prefix, uipathfn, explicitonly, dryrun, interactive
2360 ):
2360 ):
2361 if dryrun and interactive:
2361 if dryrun and interactive:
2362 raise error.InputError(
2362 raise error.InputError(
2363 _(b"cannot specify both --dry-run and --interactive")
2363 _(b"cannot specify both --dry-run and --interactive")
2364 )
2364 )
2365 bad = []
2365 bad = []
2366 badfn = lambda x, y: bad.append(x) or match.bad(x, y)
2366 badfn = lambda x, y: bad.append(x) or match.bad(x, y)
2367 wctx = repo[None]
2367 wctx = repo[None]
2368 forgot = []
2368 forgot = []
2369
2369
2370 s = repo.status(match=matchmod.badmatch(match, badfn), clean=True)
2370 s = repo.status(match=matchmod.badmatch(match, badfn), clean=True)
2371 forget = sorted(s.modified + s.added + s.deleted + s.clean)
2371 forget = sorted(s.modified + s.added + s.deleted + s.clean)
2372 if explicitonly:
2372 if explicitonly:
2373 forget = [f for f in forget if match.exact(f)]
2373 forget = [f for f in forget if match.exact(f)]
2374
2374
2375 for subpath in sorted(wctx.substate):
2375 for subpath in sorted(wctx.substate):
2376 sub = wctx.sub(subpath)
2376 sub = wctx.sub(subpath)
2377 submatch = matchmod.subdirmatcher(subpath, match)
2377 submatch = matchmod.subdirmatcher(subpath, match)
2378 subprefix = repo.wvfs.reljoin(prefix, subpath)
2378 subprefix = repo.wvfs.reljoin(prefix, subpath)
2379 subuipathfn = scmutil.subdiruipathfn(subpath, uipathfn)
2379 subuipathfn = scmutil.subdiruipathfn(subpath, uipathfn)
2380 try:
2380 try:
2381 subbad, subforgot = sub.forget(
2381 subbad, subforgot = sub.forget(
2382 submatch,
2382 submatch,
2383 subprefix,
2383 subprefix,
2384 subuipathfn,
2384 subuipathfn,
2385 dryrun=dryrun,
2385 dryrun=dryrun,
2386 interactive=interactive,
2386 interactive=interactive,
2387 )
2387 )
2388 bad.extend([subpath + b'/' + f for f in subbad])
2388 bad.extend([subpath + b'/' + f for f in subbad])
2389 forgot.extend([subpath + b'/' + f for f in subforgot])
2389 forgot.extend([subpath + b'/' + f for f in subforgot])
2390 except error.LookupError:
2390 except error.LookupError:
2391 ui.status(
2391 ui.status(
2392 _(b"skipping missing subrepository: %s\n") % uipathfn(subpath)
2392 _(b"skipping missing subrepository: %s\n") % uipathfn(subpath)
2393 )
2393 )
2394
2394
2395 if not explicitonly:
2395 if not explicitonly:
2396 for f in match.files():
2396 for f in match.files():
2397 if f not in repo.dirstate and not repo.wvfs.isdir(f):
2397 if f not in repo.dirstate and not repo.wvfs.isdir(f):
2398 if f not in forgot:
2398 if f not in forgot:
2399 if repo.wvfs.exists(f):
2399 if repo.wvfs.exists(f):
2400 # Don't complain if the exact case match wasn't given.
2400 # Don't complain if the exact case match wasn't given.
2401 # But don't do this until after checking 'forgot', so
2401 # But don't do this until after checking 'forgot', so
2402 # that subrepo files aren't normalized, and this op is
2402 # that subrepo files aren't normalized, and this op is
2403 # purely from data cached by the status walk above.
2403 # purely from data cached by the status walk above.
2404 if repo.dirstate.normalize(f) in repo.dirstate:
2404 if repo.dirstate.normalize(f) in repo.dirstate:
2405 continue
2405 continue
2406 ui.warn(
2406 ui.warn(
2407 _(
2407 _(
2408 b'not removing %s: '
2408 b'not removing %s: '
2409 b'file is already untracked\n'
2409 b'file is already untracked\n'
2410 )
2410 )
2411 % uipathfn(f)
2411 % uipathfn(f)
2412 )
2412 )
2413 bad.append(f)
2413 bad.append(f)
2414
2414
2415 if interactive:
2415 if interactive:
2416 responses = _(
2416 responses = _(
2417 b'[Ynsa?]'
2417 b'[Ynsa?]'
2418 b'$$ &Yes, forget this file'
2418 b'$$ &Yes, forget this file'
2419 b'$$ &No, skip this file'
2419 b'$$ &No, skip this file'
2420 b'$$ &Skip remaining files'
2420 b'$$ &Skip remaining files'
2421 b'$$ Include &all remaining files'
2421 b'$$ Include &all remaining files'
2422 b'$$ &? (display help)'
2422 b'$$ &? (display help)'
2423 )
2423 )
2424 for filename in forget[:]:
2424 for filename in forget[:]:
2425 r = ui.promptchoice(
2425 r = ui.promptchoice(
2426 _(b'forget %s %s') % (uipathfn(filename), responses)
2426 _(b'forget %s %s') % (uipathfn(filename), responses)
2427 )
2427 )
2428 if r == 4: # ?
2428 if r == 4: # ?
2429 while r == 4:
2429 while r == 4:
2430 for c, t in ui.extractchoices(responses)[1]:
2430 for c, t in ui.extractchoices(responses)[1]:
2431 ui.write(b'%s - %s\n' % (c, encoding.lower(t)))
2431 ui.write(b'%s - %s\n' % (c, encoding.lower(t)))
2432 r = ui.promptchoice(
2432 r = ui.promptchoice(
2433 _(b'forget %s %s') % (uipathfn(filename), responses)
2433 _(b'forget %s %s') % (uipathfn(filename), responses)
2434 )
2434 )
2435 if r == 0: # yes
2435 if r == 0: # yes
2436 continue
2436 continue
2437 elif r == 1: # no
2437 elif r == 1: # no
2438 forget.remove(filename)
2438 forget.remove(filename)
2439 elif r == 2: # Skip
2439 elif r == 2: # Skip
2440 fnindex = forget.index(filename)
2440 fnindex = forget.index(filename)
2441 del forget[fnindex:]
2441 del forget[fnindex:]
2442 break
2442 break
2443 elif r == 3: # All
2443 elif r == 3: # All
2444 break
2444 break
2445
2445
2446 for f in forget:
2446 for f in forget:
2447 if ui.verbose or not match.exact(f) or interactive:
2447 if ui.verbose or not match.exact(f) or interactive:
2448 ui.status(
2448 ui.status(
2449 _(b'removing %s\n') % uipathfn(f), label=b'ui.addremove.removed'
2449 _(b'removing %s\n') % uipathfn(f), label=b'ui.addremove.removed'
2450 )
2450 )
2451
2451
2452 if not dryrun:
2452 if not dryrun:
2453 rejected = wctx.forget(forget, prefix)
2453 rejected = wctx.forget(forget, prefix)
2454 bad.extend(f for f in rejected if f in match.files())
2454 bad.extend(f for f in rejected if f in match.files())
2455 forgot.extend(f for f in forget if f not in rejected)
2455 forgot.extend(f for f in forget if f not in rejected)
2456 return bad, forgot
2456 return bad, forgot
2457
2457
2458
2458
2459 def files(ui, ctx, m, uipathfn, fm, fmt, subrepos):
2459 def files(ui, ctx, m, uipathfn, fm, fmt, subrepos):
2460 ret = 1
2460 ret = 1
2461
2461
2462 needsfctx = ui.verbose or {b'size', b'flags'} & fm.datahint()
2462 needsfctx = ui.verbose or {b'size', b'flags'} & fm.datahint()
2463 if fm.isplain() and not needsfctx:
2463 if fm.isplain() and not needsfctx:
2464 # Fast path. The speed-up comes from skipping the formatter, and batching
2464 # Fast path. The speed-up comes from skipping the formatter, and batching
2465 # calls to ui.write.
2465 # calls to ui.write.
2466 buf = []
2466 buf = []
2467 for f in ctx.matches(m):
2467 for f in ctx.matches(m):
2468 buf.append(fmt % uipathfn(f))
2468 buf.append(fmt % uipathfn(f))
2469 if len(buf) > 100:
2469 if len(buf) > 100:
2470 ui.write(b''.join(buf))
2470 ui.write(b''.join(buf))
2471 del buf[:]
2471 del buf[:]
2472 ret = 0
2472 ret = 0
2473 if buf:
2473 if buf:
2474 ui.write(b''.join(buf))
2474 ui.write(b''.join(buf))
2475 else:
2475 else:
2476 for f in ctx.matches(m):
2476 for f in ctx.matches(m):
2477 fm.startitem()
2477 fm.startitem()
2478 fm.context(ctx=ctx)
2478 fm.context(ctx=ctx)
2479 if needsfctx:
2479 if needsfctx:
2480 fc = ctx[f]
2480 fc = ctx[f]
2481 fm.write(b'size flags', b'% 10d % 1s ', fc.size(), fc.flags())
2481 fm.write(b'size flags', b'% 10d % 1s ', fc.size(), fc.flags())
2482 fm.data(path=f)
2482 fm.data(path=f)
2483 fm.plain(fmt % uipathfn(f))
2483 fm.plain(fmt % uipathfn(f))
2484 ret = 0
2484 ret = 0
2485
2485
2486 for subpath in sorted(ctx.substate):
2486 for subpath in sorted(ctx.substate):
2487 submatch = matchmod.subdirmatcher(subpath, m)
2487 submatch = matchmod.subdirmatcher(subpath, m)
2488 subuipathfn = scmutil.subdiruipathfn(subpath, uipathfn)
2488 subuipathfn = scmutil.subdiruipathfn(subpath, uipathfn)
2489 if subrepos or m.exact(subpath) or any(submatch.files()):
2489 if subrepos or m.exact(subpath) or any(submatch.files()):
2490 sub = ctx.sub(subpath)
2490 sub = ctx.sub(subpath)
2491 try:
2491 try:
2492 recurse = m.exact(subpath) or subrepos
2492 recurse = m.exact(subpath) or subrepos
2493 if (
2493 if (
2494 sub.printfiles(ui, submatch, subuipathfn, fm, fmt, recurse)
2494 sub.printfiles(ui, submatch, subuipathfn, fm, fmt, recurse)
2495 == 0
2495 == 0
2496 ):
2496 ):
2497 ret = 0
2497 ret = 0
2498 except error.LookupError:
2498 except error.LookupError:
2499 ui.status(
2499 ui.status(
2500 _(b"skipping missing subrepository: %s\n")
2500 _(b"skipping missing subrepository: %s\n")
2501 % uipathfn(subpath)
2501 % uipathfn(subpath)
2502 )
2502 )
2503
2503
2504 return ret
2504 return ret
2505
2505
2506
2506
2507 def remove(
2507 def remove(
2508 ui, repo, m, prefix, uipathfn, after, force, subrepos, dryrun, warnings=None
2508 ui, repo, m, prefix, uipathfn, after, force, subrepos, dryrun, warnings=None
2509 ):
2509 ):
2510 ret = 0
2510 ret = 0
2511 s = repo.status(match=m, clean=True)
2511 s = repo.status(match=m, clean=True)
2512 modified, added, deleted, clean = s.modified, s.added, s.deleted, s.clean
2512 modified, added, deleted, clean = s.modified, s.added, s.deleted, s.clean
2513
2513
2514 wctx = repo[None]
2514 wctx = repo[None]
2515
2515
2516 if warnings is None:
2516 if warnings is None:
2517 warnings = []
2517 warnings = []
2518 warn = True
2518 warn = True
2519 else:
2519 else:
2520 warn = False
2520 warn = False
2521
2521
2522 subs = sorted(wctx.substate)
2522 subs = sorted(wctx.substate)
2523 progress = ui.makeprogress(
2523 progress = ui.makeprogress(
2524 _(b'searching'), total=len(subs), unit=_(b'subrepos')
2524 _(b'searching'), total=len(subs), unit=_(b'subrepos')
2525 )
2525 )
2526 for subpath in subs:
2526 for subpath in subs:
2527 submatch = matchmod.subdirmatcher(subpath, m)
2527 submatch = matchmod.subdirmatcher(subpath, m)
2528 subprefix = repo.wvfs.reljoin(prefix, subpath)
2528 subprefix = repo.wvfs.reljoin(prefix, subpath)
2529 subuipathfn = scmutil.subdiruipathfn(subpath, uipathfn)
2529 subuipathfn = scmutil.subdiruipathfn(subpath, uipathfn)
2530 if subrepos or m.exact(subpath) or any(submatch.files()):
2530 if subrepos or m.exact(subpath) or any(submatch.files()):
2531 progress.increment()
2531 progress.increment()
2532 sub = wctx.sub(subpath)
2532 sub = wctx.sub(subpath)
2533 try:
2533 try:
2534 if sub.removefiles(
2534 if sub.removefiles(
2535 submatch,
2535 submatch,
2536 subprefix,
2536 subprefix,
2537 subuipathfn,
2537 subuipathfn,
2538 after,
2538 after,
2539 force,
2539 force,
2540 subrepos,
2540 subrepos,
2541 dryrun,
2541 dryrun,
2542 warnings,
2542 warnings,
2543 ):
2543 ):
2544 ret = 1
2544 ret = 1
2545 except error.LookupError:
2545 except error.LookupError:
2546 warnings.append(
2546 warnings.append(
2547 _(b"skipping missing subrepository: %s\n")
2547 _(b"skipping missing subrepository: %s\n")
2548 % uipathfn(subpath)
2548 % uipathfn(subpath)
2549 )
2549 )
2550 progress.complete()
2550 progress.complete()
2551
2551
2552 # warn about failure to delete explicit files/dirs
2552 # warn about failure to delete explicit files/dirs
2553 deleteddirs = pathutil.dirs(deleted)
2553 deleteddirs = pathutil.dirs(deleted)
2554 files = m.files()
2554 files = m.files()
2555 progress = ui.makeprogress(
2555 progress = ui.makeprogress(
2556 _(b'deleting'), total=len(files), unit=_(b'files')
2556 _(b'deleting'), total=len(files), unit=_(b'files')
2557 )
2557 )
2558 for f in files:
2558 for f in files:
2559
2559
2560 def insubrepo():
2560 def insubrepo():
2561 for subpath in wctx.substate:
2561 for subpath in wctx.substate:
2562 if f.startswith(subpath + b'/'):
2562 if f.startswith(subpath + b'/'):
2563 return True
2563 return True
2564 return False
2564 return False
2565
2565
2566 progress.increment()
2566 progress.increment()
2567 isdir = f in deleteddirs or wctx.hasdir(f)
2567 isdir = f in deleteddirs or wctx.hasdir(f)
2568 if f in repo.dirstate or isdir or f == b'.' or insubrepo() or f in subs:
2568 if f in repo.dirstate or isdir or f == b'.' or insubrepo() or f in subs:
2569 continue
2569 continue
2570
2570
2571 if repo.wvfs.exists(f):
2571 if repo.wvfs.exists(f):
2572 if repo.wvfs.isdir(f):
2572 if repo.wvfs.isdir(f):
2573 warnings.append(
2573 warnings.append(
2574 _(b'not removing %s: no tracked files\n') % uipathfn(f)
2574 _(b'not removing %s: no tracked files\n') % uipathfn(f)
2575 )
2575 )
2576 else:
2576 else:
2577 warnings.append(
2577 warnings.append(
2578 _(b'not removing %s: file is untracked\n') % uipathfn(f)
2578 _(b'not removing %s: file is untracked\n') % uipathfn(f)
2579 )
2579 )
2580 # missing files will generate a warning elsewhere
2580 # missing files will generate a warning elsewhere
2581 ret = 1
2581 ret = 1
2582 progress.complete()
2582 progress.complete()
2583
2583
2584 if force:
2584 if force:
2585 list = modified + deleted + clean + added
2585 list = modified + deleted + clean + added
2586 elif after:
2586 elif after:
2587 list = deleted
2587 list = deleted
2588 remaining = modified + added + clean
2588 remaining = modified + added + clean
2589 progress = ui.makeprogress(
2589 progress = ui.makeprogress(
2590 _(b'skipping'), total=len(remaining), unit=_(b'files')
2590 _(b'skipping'), total=len(remaining), unit=_(b'files')
2591 )
2591 )
2592 for f in remaining:
2592 for f in remaining:
2593 progress.increment()
2593 progress.increment()
2594 if ui.verbose or (f in files):
2594 if ui.verbose or (f in files):
2595 warnings.append(
2595 warnings.append(
2596 _(b'not removing %s: file still exists\n') % uipathfn(f)
2596 _(b'not removing %s: file still exists\n') % uipathfn(f)
2597 )
2597 )
2598 ret = 1
2598 ret = 1
2599 progress.complete()
2599 progress.complete()
2600 else:
2600 else:
2601 list = deleted + clean
2601 list = deleted + clean
2602 progress = ui.makeprogress(
2602 progress = ui.makeprogress(
2603 _(b'skipping'), total=(len(modified) + len(added)), unit=_(b'files')
2603 _(b'skipping'), total=(len(modified) + len(added)), unit=_(b'files')
2604 )
2604 )
2605 for f in modified:
2605 for f in modified:
2606 progress.increment()
2606 progress.increment()
2607 warnings.append(
2607 warnings.append(
2608 _(
2608 _(
2609 b'not removing %s: file is modified (use -f'
2609 b'not removing %s: file is modified (use -f'
2610 b' to force removal)\n'
2610 b' to force removal)\n'
2611 )
2611 )
2612 % uipathfn(f)
2612 % uipathfn(f)
2613 )
2613 )
2614 ret = 1
2614 ret = 1
2615 for f in added:
2615 for f in added:
2616 progress.increment()
2616 progress.increment()
2617 warnings.append(
2617 warnings.append(
2618 _(
2618 _(
2619 b"not removing %s: file has been marked for add"
2619 b"not removing %s: file has been marked for add"
2620 b" (use 'hg forget' to undo add)\n"
2620 b" (use 'hg forget' to undo add)\n"
2621 )
2621 )
2622 % uipathfn(f)
2622 % uipathfn(f)
2623 )
2623 )
2624 ret = 1
2624 ret = 1
2625 progress.complete()
2625 progress.complete()
2626
2626
2627 list = sorted(list)
2627 list = sorted(list)
2628 progress = ui.makeprogress(
2628 progress = ui.makeprogress(
2629 _(b'deleting'), total=len(list), unit=_(b'files')
2629 _(b'deleting'), total=len(list), unit=_(b'files')
2630 )
2630 )
2631 for f in list:
2631 for f in list:
2632 if ui.verbose or not m.exact(f):
2632 if ui.verbose or not m.exact(f):
2633 progress.increment()
2633 progress.increment()
2634 ui.status(
2634 ui.status(
2635 _(b'removing %s\n') % uipathfn(f), label=b'ui.addremove.removed'
2635 _(b'removing %s\n') % uipathfn(f), label=b'ui.addremove.removed'
2636 )
2636 )
2637 progress.complete()
2637 progress.complete()
2638
2638
2639 if not dryrun:
2639 if not dryrun:
2640 with repo.wlock():
2640 with repo.wlock():
2641 if not after:
2641 if not after:
2642 for f in list:
2642 for f in list:
2643 if f in added:
2643 if f in added:
2644 continue # we never unlink added files on remove
2644 continue # we never unlink added files on remove
2645 rmdir = repo.ui.configbool(
2645 rmdir = repo.ui.configbool(
2646 b'experimental', b'removeemptydirs'
2646 b'experimental', b'removeemptydirs'
2647 )
2647 )
2648 repo.wvfs.unlinkpath(f, ignoremissing=True, rmdir=rmdir)
2648 repo.wvfs.unlinkpath(f, ignoremissing=True, rmdir=rmdir)
2649 repo[None].forget(list)
2649 repo[None].forget(list)
2650
2650
2651 if warn:
2651 if warn:
2652 for warning in warnings:
2652 for warning in warnings:
2653 ui.warn(warning)
2653 ui.warn(warning)
2654
2654
2655 return ret
2655 return ret
2656
2656
2657
2657
2658 def _catfmtneedsdata(fm):
2658 def _catfmtneedsdata(fm):
2659 return not fm.datahint() or b'data' in fm.datahint()
2659 return not fm.datahint() or b'data' in fm.datahint()
2660
2660
2661
2661
2662 def _updatecatformatter(fm, ctx, matcher, path, decode):
2662 def _updatecatformatter(fm, ctx, matcher, path, decode):
2663 """Hook for adding data to the formatter used by ``hg cat``.
2663 """Hook for adding data to the formatter used by ``hg cat``.
2664
2664
2665 Extensions (e.g., lfs) can wrap this to inject keywords/data, but must call
2665 Extensions (e.g., lfs) can wrap this to inject keywords/data, but must call
2666 this method first."""
2666 this method first."""
2667
2667
2668 # data() can be expensive to fetch (e.g. lfs), so don't fetch it if it
2668 # data() can be expensive to fetch (e.g. lfs), so don't fetch it if it
2669 # wasn't requested.
2669 # wasn't requested.
2670 data = b''
2670 data = b''
2671 if _catfmtneedsdata(fm):
2671 if _catfmtneedsdata(fm):
2672 data = ctx[path].data()
2672 data = ctx[path].data()
2673 if decode:
2673 if decode:
2674 data = ctx.repo().wwritedata(path, data)
2674 data = ctx.repo().wwritedata(path, data)
2675 fm.startitem()
2675 fm.startitem()
2676 fm.context(ctx=ctx)
2676 fm.context(ctx=ctx)
2677 fm.write(b'data', b'%s', data)
2677 fm.write(b'data', b'%s', data)
2678 fm.data(path=path)
2678 fm.data(path=path)
2679
2679
2680
2680
2681 def cat(ui, repo, ctx, matcher, basefm, fntemplate, prefix, **opts):
2681 def cat(ui, repo, ctx, matcher, basefm, fntemplate, prefix, **opts):
2682 err = 1
2682 err = 1
2683 opts = pycompat.byteskwargs(opts)
2683 opts = pycompat.byteskwargs(opts)
2684
2684
2685 def write(path):
2685 def write(path):
2686 filename = None
2686 filename = None
2687 if fntemplate:
2687 if fntemplate:
2688 filename = makefilename(
2688 filename = makefilename(
2689 ctx, fntemplate, pathname=os.path.join(prefix, path)
2689 ctx, fntemplate, pathname=os.path.join(prefix, path)
2690 )
2690 )
2691 # attempt to create the directory if it does not already exist
2691 # attempt to create the directory if it does not already exist
2692 try:
2692 try:
2693 os.makedirs(os.path.dirname(filename))
2693 os.makedirs(os.path.dirname(filename))
2694 except OSError:
2694 except OSError:
2695 pass
2695 pass
2696 with formatter.maybereopen(basefm, filename) as fm:
2696 with formatter.maybereopen(basefm, filename) as fm:
2697 _updatecatformatter(fm, ctx, matcher, path, opts.get(b'decode'))
2697 _updatecatformatter(fm, ctx, matcher, path, opts.get(b'decode'))
2698
2698
2699 # Automation often uses hg cat on single files, so special case it
2699 # Automation often uses hg cat on single files, so special case it
2700 # for performance to avoid the cost of parsing the manifest.
2700 # for performance to avoid the cost of parsing the manifest.
2701 if len(matcher.files()) == 1 and not matcher.anypats():
2701 if len(matcher.files()) == 1 and not matcher.anypats():
2702 file = matcher.files()[0]
2702 file = matcher.files()[0]
2703 mfl = repo.manifestlog
2703 mfl = repo.manifestlog
2704 mfnode = ctx.manifestnode()
2704 mfnode = ctx.manifestnode()
2705 try:
2705 try:
2706 if mfnode and mfl[mfnode].find(file)[0]:
2706 if mfnode and mfl[mfnode].find(file)[0]:
2707 if _catfmtneedsdata(basefm):
2707 if _catfmtneedsdata(basefm):
2708 scmutil.prefetchfiles(repo, [(ctx.rev(), matcher)])
2708 scmutil.prefetchfiles(repo, [(ctx.rev(), matcher)])
2709 write(file)
2709 write(file)
2710 return 0
2710 return 0
2711 except KeyError:
2711 except KeyError:
2712 pass
2712 pass
2713
2713
2714 if _catfmtneedsdata(basefm):
2714 if _catfmtneedsdata(basefm):
2715 scmutil.prefetchfiles(repo, [(ctx.rev(), matcher)])
2715 scmutil.prefetchfiles(repo, [(ctx.rev(), matcher)])
2716
2716
2717 for abs in ctx.walk(matcher):
2717 for abs in ctx.walk(matcher):
2718 write(abs)
2718 write(abs)
2719 err = 0
2719 err = 0
2720
2720
2721 uipathfn = scmutil.getuipathfn(repo, legacyrelativevalue=True)
2721 uipathfn = scmutil.getuipathfn(repo, legacyrelativevalue=True)
2722 for subpath in sorted(ctx.substate):
2722 for subpath in sorted(ctx.substate):
2723 sub = ctx.sub(subpath)
2723 sub = ctx.sub(subpath)
2724 try:
2724 try:
2725 submatch = matchmod.subdirmatcher(subpath, matcher)
2725 submatch = matchmod.subdirmatcher(subpath, matcher)
2726 subprefix = os.path.join(prefix, subpath)
2726 subprefix = os.path.join(prefix, subpath)
2727 if not sub.cat(
2727 if not sub.cat(
2728 submatch,
2728 submatch,
2729 basefm,
2729 basefm,
2730 fntemplate,
2730 fntemplate,
2731 subprefix,
2731 subprefix,
2732 **pycompat.strkwargs(opts)
2732 **pycompat.strkwargs(opts)
2733 ):
2733 ):
2734 err = 0
2734 err = 0
2735 except error.RepoLookupError:
2735 except error.RepoLookupError:
2736 ui.status(
2736 ui.status(
2737 _(b"skipping missing subrepository: %s\n") % uipathfn(subpath)
2737 _(b"skipping missing subrepository: %s\n") % uipathfn(subpath)
2738 )
2738 )
2739
2739
2740 return err
2740 return err
2741
2741
2742
2742
2743 def commit(ui, repo, commitfunc, pats, opts):
2743 def commit(ui, repo, commitfunc, pats, opts):
2744 '''commit the specified files or all outstanding changes'''
2744 '''commit the specified files or all outstanding changes'''
2745 date = opts.get(b'date')
2745 date = opts.get(b'date')
2746 if date:
2746 if date:
2747 opts[b'date'] = dateutil.parsedate(date)
2747 opts[b'date'] = dateutil.parsedate(date)
2748 message = logmessage(ui, opts)
2748 message = logmessage(ui, opts)
2749 matcher = scmutil.match(repo[None], pats, opts)
2749 matcher = scmutil.match(repo[None], pats, opts)
2750
2750
2751 dsguard = None
2751 dsguard = None
2752 # extract addremove carefully -- this function can be called from a command
2752 # extract addremove carefully -- this function can be called from a command
2753 # that doesn't support addremove
2753 # that doesn't support addremove
2754 if opts.get(b'addremove'):
2754 if opts.get(b'addremove'):
2755 dsguard = dirstateguard.dirstateguard(repo, b'commit')
2755 dsguard = dirstateguard.dirstateguard(repo, b'commit')
2756 with dsguard or util.nullcontextmanager():
2756 with dsguard or util.nullcontextmanager():
2757 if dsguard:
2757 if dsguard:
2758 relative = scmutil.anypats(pats, opts)
2758 relative = scmutil.anypats(pats, opts)
2759 uipathfn = scmutil.getuipathfn(repo, legacyrelativevalue=relative)
2759 uipathfn = scmutil.getuipathfn(repo, legacyrelativevalue=relative)
2760 if scmutil.addremove(repo, matcher, b"", uipathfn, opts) != 0:
2760 if scmutil.addremove(repo, matcher, b"", uipathfn, opts) != 0:
2761 raise error.Abort(
2761 raise error.Abort(
2762 _(b"failed to mark all new/missing files as added/removed")
2762 _(b"failed to mark all new/missing files as added/removed")
2763 )
2763 )
2764
2764
2765 return commitfunc(ui, repo, message, matcher, opts)
2765 return commitfunc(ui, repo, message, matcher, opts)
2766
2766
2767
2767
2768 def samefile(f, ctx1, ctx2):
2768 def samefile(f, ctx1, ctx2):
2769 if f in ctx1.manifest():
2769 if f in ctx1.manifest():
2770 a = ctx1.filectx(f)
2770 a = ctx1.filectx(f)
2771 if f in ctx2.manifest():
2771 if f in ctx2.manifest():
2772 b = ctx2.filectx(f)
2772 b = ctx2.filectx(f)
2773 return not a.cmp(b) and a.flags() == b.flags()
2773 return not a.cmp(b) and a.flags() == b.flags()
2774 else:
2774 else:
2775 return False
2775 return False
2776 else:
2776 else:
2777 return f not in ctx2.manifest()
2777 return f not in ctx2.manifest()
2778
2778
2779
2779
2780 def amend(ui, repo, old, extra, pats, opts):
2780 def amend(ui, repo, old, extra, pats, opts):
2781 # avoid cycle context -> subrepo -> cmdutil
2781 # avoid cycle context -> subrepo -> cmdutil
2782 from . import context
2782 from . import context
2783
2783
2784 # amend will reuse the existing user if not specified, but the obsolete
2784 # amend will reuse the existing user if not specified, but the obsolete
2785 # marker creation requires that the current user's name is specified.
2785 # marker creation requires that the current user's name is specified.
2786 if obsolete.isenabled(repo, obsolete.createmarkersopt):
2786 if obsolete.isenabled(repo, obsolete.createmarkersopt):
2787 ui.username() # raise exception if username not set
2787 ui.username() # raise exception if username not set
2788
2788
2789 ui.note(_(b'amending changeset %s\n') % old)
2789 ui.note(_(b'amending changeset %s\n') % old)
2790 base = old.p1()
2790 base = old.p1()
2791
2791
2792 with repo.wlock(), repo.lock(), repo.transaction(b'amend'):
2792 with repo.wlock(), repo.lock(), repo.transaction(b'amend'):
2793 # Participating changesets:
2793 # Participating changesets:
2794 #
2794 #
2795 # wctx o - workingctx that contains changes from working copy
2795 # wctx o - workingctx that contains changes from working copy
2796 # | to go into amending commit
2796 # | to go into amending commit
2797 # |
2797 # |
2798 # old o - changeset to amend
2798 # old o - changeset to amend
2799 # |
2799 # |
2800 # base o - first parent of the changeset to amend
2800 # base o - first parent of the changeset to amend
2801 wctx = repo[None]
2801 wctx = repo[None]
2802
2802
2803 # Copy to avoid mutating input
2803 # Copy to avoid mutating input
2804 extra = extra.copy()
2804 extra = extra.copy()
2805 # Update extra dict from amended commit (e.g. to preserve graft
2805 # Update extra dict from amended commit (e.g. to preserve graft
2806 # source)
2806 # source)
2807 extra.update(old.extra())
2807 extra.update(old.extra())
2808
2808
2809 # Also update it from the from the wctx
2809 # Also update it from the from the wctx
2810 extra.update(wctx.extra())
2810 extra.update(wctx.extra())
2811
2811
2812 # date-only change should be ignored?
2812 # date-only change should be ignored?
2813 datemaydiffer = resolvecommitoptions(ui, opts)
2813 datemaydiffer = resolvecommitoptions(ui, opts)
2814
2814
2815 date = old.date()
2815 date = old.date()
2816 if opts.get(b'date'):
2816 if opts.get(b'date'):
2817 date = dateutil.parsedate(opts.get(b'date'))
2817 date = dateutil.parsedate(opts.get(b'date'))
2818 user = opts.get(b'user') or old.user()
2818 user = opts.get(b'user') or old.user()
2819
2819
2820 if len(old.parents()) > 1:
2820 if len(old.parents()) > 1:
2821 # ctx.files() isn't reliable for merges, so fall back to the
2821 # ctx.files() isn't reliable for merges, so fall back to the
2822 # slower repo.status() method
2822 # slower repo.status() method
2823 st = base.status(old)
2823 st = base.status(old)
2824 files = set(st.modified) | set(st.added) | set(st.removed)
2824 files = set(st.modified) | set(st.added) | set(st.removed)
2825 else:
2825 else:
2826 files = set(old.files())
2826 files = set(old.files())
2827
2827
2828 # add/remove the files to the working copy if the "addremove" option
2828 # add/remove the files to the working copy if the "addremove" option
2829 # was specified.
2829 # was specified.
2830 matcher = scmutil.match(wctx, pats, opts)
2830 matcher = scmutil.match(wctx, pats, opts)
2831 relative = scmutil.anypats(pats, opts)
2831 relative = scmutil.anypats(pats, opts)
2832 uipathfn = scmutil.getuipathfn(repo, legacyrelativevalue=relative)
2832 uipathfn = scmutil.getuipathfn(repo, legacyrelativevalue=relative)
2833 if opts.get(b'addremove') and scmutil.addremove(
2833 if opts.get(b'addremove') and scmutil.addremove(
2834 repo, matcher, b"", uipathfn, opts
2834 repo, matcher, b"", uipathfn, opts
2835 ):
2835 ):
2836 raise error.Abort(
2836 raise error.Abort(
2837 _(b"failed to mark all new/missing files as added/removed")
2837 _(b"failed to mark all new/missing files as added/removed")
2838 )
2838 )
2839
2839
2840 # Check subrepos. This depends on in-place wctx._status update in
2840 # Check subrepos. This depends on in-place wctx._status update in
2841 # subrepo.precommit(). To minimize the risk of this hack, we do
2841 # subrepo.precommit(). To minimize the risk of this hack, we do
2842 # nothing if .hgsub does not exist.
2842 # nothing if .hgsub does not exist.
2843 if b'.hgsub' in wctx or b'.hgsub' in old:
2843 if b'.hgsub' in wctx or b'.hgsub' in old:
2844 subs, commitsubs, newsubstate = subrepoutil.precommit(
2844 subs, commitsubs, newsubstate = subrepoutil.precommit(
2845 ui, wctx, wctx._status, matcher
2845 ui, wctx, wctx._status, matcher
2846 )
2846 )
2847 # amend should abort if commitsubrepos is enabled
2847 # amend should abort if commitsubrepos is enabled
2848 assert not commitsubs
2848 assert not commitsubs
2849 if subs:
2849 if subs:
2850 subrepoutil.writestate(repo, newsubstate)
2850 subrepoutil.writestate(repo, newsubstate)
2851
2851
2852 ms = mergestatemod.mergestate.read(repo)
2852 ms = mergestatemod.mergestate.read(repo)
2853 mergeutil.checkunresolved(ms)
2853 mergeutil.checkunresolved(ms)
2854
2854
2855 filestoamend = {f for f in wctx.files() if matcher(f)}
2855 filestoamend = {f for f in wctx.files() if matcher(f)}
2856
2856
2857 changes = len(filestoamend) > 0
2857 changes = len(filestoamend) > 0
2858 if changes:
2858 if changes:
2859 # Recompute copies (avoid recording a -> b -> a)
2859 # Recompute copies (avoid recording a -> b -> a)
2860 copied = copies.pathcopies(base, wctx, matcher)
2860 copied = copies.pathcopies(base, wctx, matcher)
2861 if old.p2:
2861 if old.p2:
2862 copied.update(copies.pathcopies(old.p2(), wctx, matcher))
2862 copied.update(copies.pathcopies(old.p2(), wctx, matcher))
2863
2863
2864 # Prune files which were reverted by the updates: if old
2864 # Prune files which were reverted by the updates: if old
2865 # introduced file X and the file was renamed in the working
2865 # introduced file X and the file was renamed in the working
2866 # copy, then those two files are the same and
2866 # copy, then those two files are the same and
2867 # we can discard X from our list of files. Likewise if X
2867 # we can discard X from our list of files. Likewise if X
2868 # was removed, it's no longer relevant. If X is missing (aka
2868 # was removed, it's no longer relevant. If X is missing (aka
2869 # deleted), old X must be preserved.
2869 # deleted), old X must be preserved.
2870 files.update(filestoamend)
2870 files.update(filestoamend)
2871 files = [
2871 files = [
2872 f
2872 f
2873 for f in files
2873 for f in files
2874 if (f not in filestoamend or not samefile(f, wctx, base))
2874 if (f not in filestoamend or not samefile(f, wctx, base))
2875 ]
2875 ]
2876
2876
2877 def filectxfn(repo, ctx_, path):
2877 def filectxfn(repo, ctx_, path):
2878 try:
2878 try:
2879 # If the file being considered is not amongst the files
2879 # If the file being considered is not amongst the files
2880 # to be amended, we should return the file context from the
2880 # to be amended, we should return the file context from the
2881 # old changeset. This avoids issues when only some files in
2881 # old changeset. This avoids issues when only some files in
2882 # the working copy are being amended but there are also
2882 # the working copy are being amended but there are also
2883 # changes to other files from the old changeset.
2883 # changes to other files from the old changeset.
2884 if path not in filestoamend:
2884 if path not in filestoamend:
2885 return old.filectx(path)
2885 return old.filectx(path)
2886
2886
2887 # Return None for removed files.
2887 # Return None for removed files.
2888 if path in wctx.removed():
2888 if path in wctx.removed():
2889 return None
2889 return None
2890
2890
2891 fctx = wctx[path]
2891 fctx = wctx[path]
2892 flags = fctx.flags()
2892 flags = fctx.flags()
2893 mctx = context.memfilectx(
2893 mctx = context.memfilectx(
2894 repo,
2894 repo,
2895 ctx_,
2895 ctx_,
2896 fctx.path(),
2896 fctx.path(),
2897 fctx.data(),
2897 fctx.data(),
2898 islink=b'l' in flags,
2898 islink=b'l' in flags,
2899 isexec=b'x' in flags,
2899 isexec=b'x' in flags,
2900 copysource=copied.get(path),
2900 copysource=copied.get(path),
2901 )
2901 )
2902 return mctx
2902 return mctx
2903 except KeyError:
2903 except KeyError:
2904 return None
2904 return None
2905
2905
2906 else:
2906 else:
2907 ui.note(_(b'copying changeset %s to %s\n') % (old, base))
2907 ui.note(_(b'copying changeset %s to %s\n') % (old, base))
2908
2908
2909 # Use version of files as in the old cset
2909 # Use version of files as in the old cset
2910 def filectxfn(repo, ctx_, path):
2910 def filectxfn(repo, ctx_, path):
2911 try:
2911 try:
2912 return old.filectx(path)
2912 return old.filectx(path)
2913 except KeyError:
2913 except KeyError:
2914 return None
2914 return None
2915
2915
2916 # See if we got a message from -m or -l, if not, open the editor with
2916 # See if we got a message from -m or -l, if not, open the editor with
2917 # the message of the changeset to amend.
2917 # the message of the changeset to amend.
2918 message = logmessage(ui, opts)
2918 message = logmessage(ui, opts)
2919
2919
2920 editform = mergeeditform(old, b'commit.amend')
2920 editform = mergeeditform(old, b'commit.amend')
2921
2921
2922 if not message:
2922 if not message:
2923 message = old.description()
2923 message = old.description()
2924 # Default if message isn't provided and --edit is not passed is to
2924 # Default if message isn't provided and --edit is not passed is to
2925 # invoke editor, but allow --no-edit. If somehow we don't have any
2925 # invoke editor, but allow --no-edit. If somehow we don't have any
2926 # description, let's always start the editor.
2926 # description, let's always start the editor.
2927 doedit = not message or opts.get(b'edit') in [True, None]
2927 doedit = not message or opts.get(b'edit') in [True, None]
2928 else:
2928 else:
2929 # Default if message is provided is to not invoke editor, but allow
2929 # Default if message is provided is to not invoke editor, but allow
2930 # --edit.
2930 # --edit.
2931 doedit = opts.get(b'edit') is True
2931 doedit = opts.get(b'edit') is True
2932 editor = getcommiteditor(edit=doedit, editform=editform)
2932 editor = getcommiteditor(edit=doedit, editform=editform)
2933
2933
2934 pureextra = extra.copy()
2934 pureextra = extra.copy()
2935 extra[b'amend_source'] = old.hex()
2935 extra[b'amend_source'] = old.hex()
2936
2936
2937 new = context.memctx(
2937 new = context.memctx(
2938 repo,
2938 repo,
2939 parents=[base.node(), old.p2().node()],
2939 parents=[base.node(), old.p2().node()],
2940 text=message,
2940 text=message,
2941 files=files,
2941 files=files,
2942 filectxfn=filectxfn,
2942 filectxfn=filectxfn,
2943 user=user,
2943 user=user,
2944 date=date,
2944 date=date,
2945 extra=extra,
2945 extra=extra,
2946 editor=editor,
2946 editor=editor,
2947 )
2947 )
2948
2948
2949 newdesc = changelog.stripdesc(new.description())
2949 newdesc = changelog.stripdesc(new.description())
2950 if (
2950 if (
2951 (not changes)
2951 (not changes)
2952 and newdesc == old.description()
2952 and newdesc == old.description()
2953 and user == old.user()
2953 and user == old.user()
2954 and (date == old.date() or datemaydiffer)
2954 and (date == old.date() or datemaydiffer)
2955 and pureextra == old.extra()
2955 and pureextra == old.extra()
2956 ):
2956 ):
2957 # nothing changed. continuing here would create a new node
2957 # nothing changed. continuing here would create a new node
2958 # anyway because of the amend_source noise.
2958 # anyway because of the amend_source noise.
2959 #
2959 #
2960 # This not what we expect from amend.
2960 # This not what we expect from amend.
2961 return old.node()
2961 return old.node()
2962
2962
2963 commitphase = None
2963 commitphase = None
2964 if opts.get(b'secret'):
2964 if opts.get(b'secret'):
2965 commitphase = phases.secret
2965 commitphase = phases.secret
2966 newid = repo.commitctx(new)
2966 newid = repo.commitctx(new)
2967 ms.reset()
2967 ms.reset()
2968
2968
2969 # Reroute the working copy parent to the new changeset
2969 # Reroute the working copy parent to the new changeset
2970 repo.setparents(newid, nullid)
2970 repo.setparents(newid, nullid)
2971
2971
2972 # Fixing the dirstate because localrepo.commitctx does not update
2972 # Fixing the dirstate because localrepo.commitctx does not update
2973 # it. This is rather convenient because we did not need to update
2973 # it. This is rather convenient because we did not need to update
2974 # the dirstate for all the files in the new commit which commitctx
2974 # the dirstate for all the files in the new commit which commitctx
2975 # could have done if it updated the dirstate. Now, we can
2975 # could have done if it updated the dirstate. Now, we can
2976 # selectively update the dirstate only for the amended files.
2976 # selectively update the dirstate only for the amended files.
2977 dirstate = repo.dirstate
2977 dirstate = repo.dirstate
2978
2978
2979 # Update the state of the files which were added and modified in the
2979 # Update the state of the files which were added and modified in the
2980 # amend to "normal" in the dirstate. We need to use "normallookup" since
2980 # amend to "normal" in the dirstate. We need to use "normallookup" since
2981 # the files may have changed since the command started; using "normal"
2981 # the files may have changed since the command started; using "normal"
2982 # would mark them as clean but with uncommitted contents.
2982 # would mark them as clean but with uncommitted contents.
2983 normalfiles = set(wctx.modified() + wctx.added()) & filestoamend
2983 normalfiles = set(wctx.modified() + wctx.added()) & filestoamend
2984 for f in normalfiles:
2984 for f in normalfiles:
2985 dirstate.normallookup(f)
2985 dirstate.normallookup(f)
2986
2986
2987 # Update the state of files which were removed in the amend
2987 # Update the state of files which were removed in the amend
2988 # to "removed" in the dirstate.
2988 # to "removed" in the dirstate.
2989 removedfiles = set(wctx.removed()) & filestoamend
2989 removedfiles = set(wctx.removed()) & filestoamend
2990 for f in removedfiles:
2990 for f in removedfiles:
2991 dirstate.drop(f)
2991 dirstate.drop(f)
2992
2992
2993 mapping = {old.node(): (newid,)}
2993 mapping = {old.node(): (newid,)}
2994 obsmetadata = None
2994 obsmetadata = None
2995 if opts.get(b'note'):
2995 if opts.get(b'note'):
2996 obsmetadata = {b'note': encoding.fromlocal(opts[b'note'])}
2996 obsmetadata = {b'note': encoding.fromlocal(opts[b'note'])}
2997 backup = ui.configbool(b'rewrite', b'backup-bundle')
2997 backup = ui.configbool(b'rewrite', b'backup-bundle')
2998 scmutil.cleanupnodes(
2998 scmutil.cleanupnodes(
2999 repo,
2999 repo,
3000 mapping,
3000 mapping,
3001 b'amend',
3001 b'amend',
3002 metadata=obsmetadata,
3002 metadata=obsmetadata,
3003 fixphase=True,
3003 fixphase=True,
3004 targetphase=commitphase,
3004 targetphase=commitphase,
3005 backup=backup,
3005 backup=backup,
3006 )
3006 )
3007
3007
3008 return newid
3008 return newid
3009
3009
3010
3010
3011 def commiteditor(repo, ctx, subs, editform=b''):
3011 def commiteditor(repo, ctx, subs, editform=b''):
3012 if ctx.description():
3012 if ctx.description():
3013 return ctx.description()
3013 return ctx.description()
3014 return commitforceeditor(
3014 return commitforceeditor(
3015 repo, ctx, subs, editform=editform, unchangedmessagedetection=True
3015 repo, ctx, subs, editform=editform, unchangedmessagedetection=True
3016 )
3016 )
3017
3017
3018
3018
3019 def commitforceeditor(
3019 def commitforceeditor(
3020 repo,
3020 repo,
3021 ctx,
3021 ctx,
3022 subs,
3022 subs,
3023 finishdesc=None,
3023 finishdesc=None,
3024 extramsg=None,
3024 extramsg=None,
3025 editform=b'',
3025 editform=b'',
3026 unchangedmessagedetection=False,
3026 unchangedmessagedetection=False,
3027 ):
3027 ):
3028 if not extramsg:
3028 if not extramsg:
3029 extramsg = _(b"Leave message empty to abort commit.")
3029 extramsg = _(b"Leave message empty to abort commit.")
3030
3030
3031 forms = [e for e in editform.split(b'.') if e]
3031 forms = [e for e in editform.split(b'.') if e]
3032 forms.insert(0, b'changeset')
3032 forms.insert(0, b'changeset')
3033 templatetext = None
3033 templatetext = None
3034 while forms:
3034 while forms:
3035 ref = b'.'.join(forms)
3035 ref = b'.'.join(forms)
3036 if repo.ui.config(b'committemplate', ref):
3036 if repo.ui.config(b'committemplate', ref):
3037 templatetext = committext = buildcommittemplate(
3037 templatetext = committext = buildcommittemplate(
3038 repo, ctx, subs, extramsg, ref
3038 repo, ctx, subs, extramsg, ref
3039 )
3039 )
3040 break
3040 break
3041 forms.pop()
3041 forms.pop()
3042 else:
3042 else:
3043 committext = buildcommittext(repo, ctx, subs, extramsg)
3043 committext = buildcommittext(repo, ctx, subs, extramsg)
3044
3044
3045 # run editor in the repository root
3045 # run editor in the repository root
3046 olddir = encoding.getcwd()
3046 olddir = encoding.getcwd()
3047 os.chdir(repo.root)
3047 os.chdir(repo.root)
3048
3048
3049 # make in-memory changes visible to external process
3049 # make in-memory changes visible to external process
3050 tr = repo.currenttransaction()
3050 tr = repo.currenttransaction()
3051 repo.dirstate.write(tr)
3051 repo.dirstate.write(tr)
3052 pending = tr and tr.writepending() and repo.root
3052 pending = tr and tr.writepending() and repo.root
3053
3053
3054 editortext = repo.ui.edit(
3054 editortext = repo.ui.edit(
3055 committext,
3055 committext,
3056 ctx.user(),
3056 ctx.user(),
3057 ctx.extra(),
3057 ctx.extra(),
3058 editform=editform,
3058 editform=editform,
3059 pending=pending,
3059 pending=pending,
3060 repopath=repo.path,
3060 repopath=repo.path,
3061 action=b'commit',
3061 action=b'commit',
3062 )
3062 )
3063 text = editortext
3063 text = editortext
3064
3064
3065 # strip away anything below this special string (used for editors that want
3065 # strip away anything below this special string (used for editors that want
3066 # to display the diff)
3066 # to display the diff)
3067 stripbelow = re.search(_linebelow, text, flags=re.MULTILINE)
3067 stripbelow = re.search(_linebelow, text, flags=re.MULTILINE)
3068 if stripbelow:
3068 if stripbelow:
3069 text = text[: stripbelow.start()]
3069 text = text[: stripbelow.start()]
3070
3070
3071 text = re.sub(b"(?m)^HG:.*(\n|$)", b"", text)
3071 text = re.sub(b"(?m)^HG:.*(\n|$)", b"", text)
3072 os.chdir(olddir)
3072 os.chdir(olddir)
3073
3073
3074 if finishdesc:
3074 if finishdesc:
3075 text = finishdesc(text)
3075 text = finishdesc(text)
3076 if not text.strip():
3076 if not text.strip():
3077 raise error.InputError(_(b"empty commit message"))
3077 raise error.InputError(_(b"empty commit message"))
3078 if unchangedmessagedetection and editortext == templatetext:
3078 if unchangedmessagedetection and editortext == templatetext:
3079 raise error.InputError(_(b"commit message unchanged"))
3079 raise error.InputError(_(b"commit message unchanged"))
3080
3080
3081 return text
3081 return text
3082
3082
3083
3083
3084 def buildcommittemplate(repo, ctx, subs, extramsg, ref):
3084 def buildcommittemplate(repo, ctx, subs, extramsg, ref):
3085 ui = repo.ui
3085 ui = repo.ui
3086 spec = formatter.reference_templatespec(ref)
3086 spec = formatter.reference_templatespec(ref)
3087 t = logcmdutil.changesettemplater(ui, repo, spec)
3087 t = logcmdutil.changesettemplater(ui, repo, spec)
3088 t.t.cache.update(
3088 t.t.cache.update(
3089 (k, templater.unquotestring(v))
3089 (k, templater.unquotestring(v))
3090 for k, v in repo.ui.configitems(b'committemplate')
3090 for k, v in repo.ui.configitems(b'committemplate')
3091 )
3091 )
3092
3092
3093 if not extramsg:
3093 if not extramsg:
3094 extramsg = b'' # ensure that extramsg is string
3094 extramsg = b'' # ensure that extramsg is string
3095
3095
3096 ui.pushbuffer()
3096 ui.pushbuffer()
3097 t.show(ctx, extramsg=extramsg)
3097 t.show(ctx, extramsg=extramsg)
3098 return ui.popbuffer()
3098 return ui.popbuffer()
3099
3099
3100
3100
3101 def hgprefix(msg):
3101 def hgprefix(msg):
3102 return b"\n".join([b"HG: %s" % a for a in msg.split(b"\n") if a])
3102 return b"\n".join([b"HG: %s" % a for a in msg.split(b"\n") if a])
3103
3103
3104
3104
3105 def buildcommittext(repo, ctx, subs, extramsg):
3105 def buildcommittext(repo, ctx, subs, extramsg):
3106 edittext = []
3106 edittext = []
3107 modified, added, removed = ctx.modified(), ctx.added(), ctx.removed()
3107 modified, added, removed = ctx.modified(), ctx.added(), ctx.removed()
3108 if ctx.description():
3108 if ctx.description():
3109 edittext.append(ctx.description())
3109 edittext.append(ctx.description())
3110 edittext.append(b"")
3110 edittext.append(b"")
3111 edittext.append(b"") # Empty line between message and comments.
3111 edittext.append(b"") # Empty line between message and comments.
3112 edittext.append(
3112 edittext.append(
3113 hgprefix(
3113 hgprefix(
3114 _(
3114 _(
3115 b"Enter commit message."
3115 b"Enter commit message."
3116 b" Lines beginning with 'HG:' are removed."
3116 b" Lines beginning with 'HG:' are removed."
3117 )
3117 )
3118 )
3118 )
3119 )
3119 )
3120 edittext.append(hgprefix(extramsg))
3120 edittext.append(hgprefix(extramsg))
3121 edittext.append(b"HG: --")
3121 edittext.append(b"HG: --")
3122 edittext.append(hgprefix(_(b"user: %s") % ctx.user()))
3122 edittext.append(hgprefix(_(b"user: %s") % ctx.user()))
3123 if ctx.p2():
3123 if ctx.p2():
3124 edittext.append(hgprefix(_(b"branch merge")))
3124 edittext.append(hgprefix(_(b"branch merge")))
3125 if ctx.branch():
3125 if ctx.branch():
3126 edittext.append(hgprefix(_(b"branch '%s'") % ctx.branch()))
3126 edittext.append(hgprefix(_(b"branch '%s'") % ctx.branch()))
3127 if bookmarks.isactivewdirparent(repo):
3127 if bookmarks.isactivewdirparent(repo):
3128 edittext.append(hgprefix(_(b"bookmark '%s'") % repo._activebookmark))
3128 edittext.append(hgprefix(_(b"bookmark '%s'") % repo._activebookmark))
3129 edittext.extend([hgprefix(_(b"subrepo %s") % s) for s in subs])
3129 edittext.extend([hgprefix(_(b"subrepo %s") % s) for s in subs])
3130 edittext.extend([hgprefix(_(b"added %s") % f) for f in added])
3130 edittext.extend([hgprefix(_(b"added %s") % f) for f in added])
3131 edittext.extend([hgprefix(_(b"changed %s") % f) for f in modified])
3131 edittext.extend([hgprefix(_(b"changed %s") % f) for f in modified])
3132 edittext.extend([hgprefix(_(b"removed %s") % f) for f in removed])
3132 edittext.extend([hgprefix(_(b"removed %s") % f) for f in removed])
3133 if not added and not modified and not removed:
3133 if not added and not modified and not removed:
3134 edittext.append(hgprefix(_(b"no files changed")))
3134 edittext.append(hgprefix(_(b"no files changed")))
3135 edittext.append(b"")
3135 edittext.append(b"")
3136
3136
3137 return b"\n".join(edittext)
3137 return b"\n".join(edittext)
3138
3138
3139
3139
3140 def commitstatus(repo, node, branch, bheads=None, tip=None, opts=None):
3140 def commitstatus(repo, node, branch, bheads=None, tip=None, opts=None):
3141 if opts is None:
3141 if opts is None:
3142 opts = {}
3142 opts = {}
3143 ctx = repo[node]
3143 ctx = repo[node]
3144 parents = ctx.parents()
3144 parents = ctx.parents()
3145
3145
3146 if tip is not None and repo.changelog.tip() == tip:
3146 if tip is not None and repo.changelog.tip() == tip:
3147 # avoid reporting something like "committed new head" when
3147 # avoid reporting something like "committed new head" when
3148 # recommitting old changesets, and issue a helpful warning
3148 # recommitting old changesets, and issue a helpful warning
3149 # for most instances
3149 # for most instances
3150 repo.ui.warn(_(b"warning: commit already existed in the repository!\n"))
3150 repo.ui.warn(_(b"warning: commit already existed in the repository!\n"))
3151 elif (
3151 elif (
3152 not opts.get(b'amend')
3152 not opts.get(b'amend')
3153 and bheads
3153 and bheads
3154 and node not in bheads
3154 and node not in bheads
3155 and not any(
3155 and not any(
3156 p.node() in bheads and p.branch() == branch for p in parents
3156 p.node() in bheads and p.branch() == branch for p in parents
3157 )
3157 )
3158 ):
3158 ):
3159 repo.ui.status(_(b'created new head\n'))
3159 repo.ui.status(_(b'created new head\n'))
3160 # The message is not printed for initial roots. For the other
3160 # The message is not printed for initial roots. For the other
3161 # changesets, it is printed in the following situations:
3161 # changesets, it is printed in the following situations:
3162 #
3162 #
3163 # Par column: for the 2 parents with ...
3163 # Par column: for the 2 parents with ...
3164 # N: null or no parent
3164 # N: null or no parent
3165 # B: parent is on another named branch
3165 # B: parent is on another named branch
3166 # C: parent is a regular non head changeset
3166 # C: parent is a regular non head changeset
3167 # H: parent was a branch head of the current branch
3167 # H: parent was a branch head of the current branch
3168 # Msg column: whether we print "created new head" message
3168 # Msg column: whether we print "created new head" message
3169 # In the following, it is assumed that there already exists some
3169 # In the following, it is assumed that there already exists some
3170 # initial branch heads of the current branch, otherwise nothing is
3170 # initial branch heads of the current branch, otherwise nothing is
3171 # printed anyway.
3171 # printed anyway.
3172 #
3172 #
3173 # Par Msg Comment
3173 # Par Msg Comment
3174 # N N y additional topo root
3174 # N N y additional topo root
3175 #
3175 #
3176 # B N y additional branch root
3176 # B N y additional branch root
3177 # C N y additional topo head
3177 # C N y additional topo head
3178 # H N n usual case
3178 # H N n usual case
3179 #
3179 #
3180 # B B y weird additional branch root
3180 # B B y weird additional branch root
3181 # C B y branch merge
3181 # C B y branch merge
3182 # H B n merge with named branch
3182 # H B n merge with named branch
3183 #
3183 #
3184 # C C y additional head from merge
3184 # C C y additional head from merge
3185 # C H n merge with a head
3185 # C H n merge with a head
3186 #
3186 #
3187 # H H n head merge: head count decreases
3187 # H H n head merge: head count decreases
3188
3188
3189 if not opts.get(b'close_branch'):
3189 if not opts.get(b'close_branch'):
3190 for r in parents:
3190 for r in parents:
3191 if r.closesbranch() and r.branch() == branch:
3191 if r.closesbranch() and r.branch() == branch:
3192 repo.ui.status(
3192 repo.ui.status(
3193 _(b'reopening closed branch head %d\n') % r.rev()
3193 _(b'reopening closed branch head %d\n') % r.rev()
3194 )
3194 )
3195
3195
3196 if repo.ui.debugflag:
3196 if repo.ui.debugflag:
3197 repo.ui.write(
3197 repo.ui.write(
3198 _(b'committed changeset %d:%s\n') % (ctx.rev(), ctx.hex())
3198 _(b'committed changeset %d:%s\n') % (ctx.rev(), ctx.hex())
3199 )
3199 )
3200 elif repo.ui.verbose:
3200 elif repo.ui.verbose:
3201 repo.ui.write(_(b'committed changeset %d:%s\n') % (ctx.rev(), ctx))
3201 repo.ui.write(_(b'committed changeset %d:%s\n') % (ctx.rev(), ctx))
3202
3202
3203
3203
3204 def postcommitstatus(repo, pats, opts):
3204 def postcommitstatus(repo, pats, opts):
3205 return repo.status(match=scmutil.match(repo[None], pats, opts))
3205 return repo.status(match=scmutil.match(repo[None], pats, opts))
3206
3206
3207
3207
3208 def revert(ui, repo, ctx, *pats, **opts):
3208 def revert(ui, repo, ctx, *pats, **opts):
3209 opts = pycompat.byteskwargs(opts)
3209 opts = pycompat.byteskwargs(opts)
3210 parent, p2 = repo.dirstate.parents()
3210 parent, p2 = repo.dirstate.parents()
3211 node = ctx.node()
3211 node = ctx.node()
3212
3212
3213 mf = ctx.manifest()
3213 mf = ctx.manifest()
3214 if node == p2:
3214 if node == p2:
3215 parent = p2
3215 parent = p2
3216
3216
3217 # need all matching names in dirstate and manifest of target rev,
3217 # need all matching names in dirstate and manifest of target rev,
3218 # so have to walk both. do not print errors if files exist in one
3218 # so have to walk both. do not print errors if files exist in one
3219 # but not other. in both cases, filesets should be evaluated against
3219 # but not other. in both cases, filesets should be evaluated against
3220 # workingctx to get consistent result (issue4497). this means 'set:**'
3220 # workingctx to get consistent result (issue4497). this means 'set:**'
3221 # cannot be used to select missing files from target rev.
3221 # cannot be used to select missing files from target rev.
3222
3222
3223 # `names` is a mapping for all elements in working copy and target revision
3223 # `names` is a mapping for all elements in working copy and target revision
3224 # The mapping is in the form:
3224 # The mapping is in the form:
3225 # <abs path in repo> -> (<path from CWD>, <exactly specified by matcher?>)
3225 # <abs path in repo> -> (<path from CWD>, <exactly specified by matcher?>)
3226 names = {}
3226 names = {}
3227 uipathfn = scmutil.getuipathfn(repo, legacyrelativevalue=True)
3227 uipathfn = scmutil.getuipathfn(repo, legacyrelativevalue=True)
3228
3228
3229 with repo.wlock():
3229 with repo.wlock():
3230 ## filling of the `names` mapping
3230 ## filling of the `names` mapping
3231 # walk dirstate to fill `names`
3231 # walk dirstate to fill `names`
3232
3232
3233 interactive = opts.get(b'interactive', False)
3233 interactive = opts.get(b'interactive', False)
3234 wctx = repo[None]
3234 wctx = repo[None]
3235 m = scmutil.match(wctx, pats, opts)
3235 m = scmutil.match(wctx, pats, opts)
3236
3236
3237 # we'll need this later
3237 # we'll need this later
3238 targetsubs = sorted(s for s in wctx.substate if m(s))
3238 targetsubs = sorted(s for s in wctx.substate if m(s))
3239
3239
3240 if not m.always():
3240 if not m.always():
3241 matcher = matchmod.badmatch(m, lambda x, y: False)
3241 matcher = matchmod.badmatch(m, lambda x, y: False)
3242 for abs in wctx.walk(matcher):
3242 for abs in wctx.walk(matcher):
3243 names[abs] = m.exact(abs)
3243 names[abs] = m.exact(abs)
3244
3244
3245 # walk target manifest to fill `names`
3245 # walk target manifest to fill `names`
3246
3246
3247 def badfn(path, msg):
3247 def badfn(path, msg):
3248 if path in names:
3248 if path in names:
3249 return
3249 return
3250 if path in ctx.substate:
3250 if path in ctx.substate:
3251 return
3251 return
3252 path_ = path + b'/'
3252 path_ = path + b'/'
3253 for f in names:
3253 for f in names:
3254 if f.startswith(path_):
3254 if f.startswith(path_):
3255 return
3255 return
3256 ui.warn(b"%s: %s\n" % (uipathfn(path), msg))
3256 ui.warn(b"%s: %s\n" % (uipathfn(path), msg))
3257
3257
3258 for abs in ctx.walk(matchmod.badmatch(m, badfn)):
3258 for abs in ctx.walk(matchmod.badmatch(m, badfn)):
3259 if abs not in names:
3259 if abs not in names:
3260 names[abs] = m.exact(abs)
3260 names[abs] = m.exact(abs)
3261
3261
3262 # Find status of all file in `names`.
3262 # Find status of all file in `names`.
3263 m = scmutil.matchfiles(repo, names)
3263 m = scmutil.matchfiles(repo, names)
3264
3264
3265 changes = repo.status(
3265 changes = repo.status(
3266 node1=node, match=m, unknown=True, ignored=True, clean=True
3266 node1=node, match=m, unknown=True, ignored=True, clean=True
3267 )
3267 )
3268 else:
3268 else:
3269 changes = repo.status(node1=node, match=m)
3269 changes = repo.status(node1=node, match=m)
3270 for kind in changes:
3270 for kind in changes:
3271 for abs in kind:
3271 for abs in kind:
3272 names[abs] = m.exact(abs)
3272 names[abs] = m.exact(abs)
3273
3273
3274 m = scmutil.matchfiles(repo, names)
3274 m = scmutil.matchfiles(repo, names)
3275
3275
3276 modified = set(changes.modified)
3276 modified = set(changes.modified)
3277 added = set(changes.added)
3277 added = set(changes.added)
3278 removed = set(changes.removed)
3278 removed = set(changes.removed)
3279 _deleted = set(changes.deleted)
3279 _deleted = set(changes.deleted)
3280 unknown = set(changes.unknown)
3280 unknown = set(changes.unknown)
3281 unknown.update(changes.ignored)
3281 unknown.update(changes.ignored)
3282 clean = set(changes.clean)
3282 clean = set(changes.clean)
3283 modadded = set()
3283 modadded = set()
3284
3284
3285 # We need to account for the state of the file in the dirstate,
3285 # We need to account for the state of the file in the dirstate,
3286 # even when we revert against something else than parent. This will
3286 # even when we revert against something else than parent. This will
3287 # slightly alter the behavior of revert (doing back up or not, delete
3287 # slightly alter the behavior of revert (doing back up or not, delete
3288 # or just forget etc).
3288 # or just forget etc).
3289 if parent == node:
3289 if parent == node:
3290 dsmodified = modified
3290 dsmodified = modified
3291 dsadded = added
3291 dsadded = added
3292 dsremoved = removed
3292 dsremoved = removed
3293 # store all local modifications, useful later for rename detection
3293 # store all local modifications, useful later for rename detection
3294 localchanges = dsmodified | dsadded
3294 localchanges = dsmodified | dsadded
3295 modified, added, removed = set(), set(), set()
3295 modified, added, removed = set(), set(), set()
3296 else:
3296 else:
3297 changes = repo.status(node1=parent, match=m)
3297 changes = repo.status(node1=parent, match=m)
3298 dsmodified = set(changes.modified)
3298 dsmodified = set(changes.modified)
3299 dsadded = set(changes.added)
3299 dsadded = set(changes.added)
3300 dsremoved = set(changes.removed)
3300 dsremoved = set(changes.removed)
3301 # store all local modifications, useful later for rename detection
3301 # store all local modifications, useful later for rename detection
3302 localchanges = dsmodified | dsadded
3302 localchanges = dsmodified | dsadded
3303
3303
3304 # only take into account for removes between wc and target
3304 # only take into account for removes between wc and target
3305 clean |= dsremoved - removed
3305 clean |= dsremoved - removed
3306 dsremoved &= removed
3306 dsremoved &= removed
3307 # distinct between dirstate remove and other
3307 # distinct between dirstate remove and other
3308 removed -= dsremoved
3308 removed -= dsremoved
3309
3309
3310 modadded = added & dsmodified
3310 modadded = added & dsmodified
3311 added -= modadded
3311 added -= modadded
3312
3312
3313 # tell newly modified apart.
3313 # tell newly modified apart.
3314 dsmodified &= modified
3314 dsmodified &= modified
3315 dsmodified |= modified & dsadded # dirstate added may need backup
3315 dsmodified |= modified & dsadded # dirstate added may need backup
3316 modified -= dsmodified
3316 modified -= dsmodified
3317
3317
3318 # We need to wait for some post-processing to update this set
3318 # We need to wait for some post-processing to update this set
3319 # before making the distinction. The dirstate will be used for
3319 # before making the distinction. The dirstate will be used for
3320 # that purpose.
3320 # that purpose.
3321 dsadded = added
3321 dsadded = added
3322
3322
3323 # in case of merge, files that are actually added can be reported as
3323 # in case of merge, files that are actually added can be reported as
3324 # modified, we need to post process the result
3324 # modified, we need to post process the result
3325 if p2 != nullid:
3325 if p2 != nullid:
3326 mergeadd = set(dsmodified)
3326 mergeadd = set(dsmodified)
3327 for path in dsmodified:
3327 for path in dsmodified:
3328 if path in mf:
3328 if path in mf:
3329 mergeadd.remove(path)
3329 mergeadd.remove(path)
3330 dsadded |= mergeadd
3330 dsadded |= mergeadd
3331 dsmodified -= mergeadd
3331 dsmodified -= mergeadd
3332
3332
3333 # if f is a rename, update `names` to also revert the source
3333 # if f is a rename, update `names` to also revert the source
3334 for f in localchanges:
3334 for f in localchanges:
3335 src = repo.dirstate.copied(f)
3335 src = repo.dirstate.copied(f)
3336 # XXX should we check for rename down to target node?
3336 # XXX should we check for rename down to target node?
3337 if src and src not in names and repo.dirstate[src] == b'r':
3337 if src and src not in names and repo.dirstate[src] == b'r':
3338 dsremoved.add(src)
3338 dsremoved.add(src)
3339 names[src] = True
3339 names[src] = True
3340
3340
3341 # determine the exact nature of the deleted changesets
3341 # determine the exact nature of the deleted changesets
3342 deladded = set(_deleted)
3342 deladded = set(_deleted)
3343 for path in _deleted:
3343 for path in _deleted:
3344 if path in mf:
3344 if path in mf:
3345 deladded.remove(path)
3345 deladded.remove(path)
3346 deleted = _deleted - deladded
3346 deleted = _deleted - deladded
3347
3347
3348 # distinguish between file to forget and the other
3348 # distinguish between file to forget and the other
3349 added = set()
3349 added = set()
3350 for abs in dsadded:
3350 for abs in dsadded:
3351 if repo.dirstate[abs] != b'a':
3351 if repo.dirstate[abs] != b'a':
3352 added.add(abs)
3352 added.add(abs)
3353 dsadded -= added
3353 dsadded -= added
3354
3354
3355 for abs in deladded:
3355 for abs in deladded:
3356 if repo.dirstate[abs] == b'a':
3356 if repo.dirstate[abs] == b'a':
3357 dsadded.add(abs)
3357 dsadded.add(abs)
3358 deladded -= dsadded
3358 deladded -= dsadded
3359
3359
3360 # For files marked as removed, we check if an unknown file is present at
3360 # For files marked as removed, we check if an unknown file is present at
3361 # the same path. If a such file exists it may need to be backed up.
3361 # the same path. If a such file exists it may need to be backed up.
3362 # Making the distinction at this stage helps have simpler backup
3362 # Making the distinction at this stage helps have simpler backup
3363 # logic.
3363 # logic.
3364 removunk = set()
3364 removunk = set()
3365 for abs in removed:
3365 for abs in removed:
3366 target = repo.wjoin(abs)
3366 target = repo.wjoin(abs)
3367 if os.path.lexists(target):
3367 if os.path.lexists(target):
3368 removunk.add(abs)
3368 removunk.add(abs)
3369 removed -= removunk
3369 removed -= removunk
3370
3370
3371 dsremovunk = set()
3371 dsremovunk = set()
3372 for abs in dsremoved:
3372 for abs in dsremoved:
3373 target = repo.wjoin(abs)
3373 target = repo.wjoin(abs)
3374 if os.path.lexists(target):
3374 if os.path.lexists(target):
3375 dsremovunk.add(abs)
3375 dsremovunk.add(abs)
3376 dsremoved -= dsremovunk
3376 dsremoved -= dsremovunk
3377
3377
3378 # action to be actually performed by revert
3378 # action to be actually performed by revert
3379 # (<list of file>, message>) tuple
3379 # (<list of file>, message>) tuple
3380 actions = {
3380 actions = {
3381 b'revert': ([], _(b'reverting %s\n')),
3381 b'revert': ([], _(b'reverting %s\n')),
3382 b'add': ([], _(b'adding %s\n')),
3382 b'add': ([], _(b'adding %s\n')),
3383 b'remove': ([], _(b'removing %s\n')),
3383 b'remove': ([], _(b'removing %s\n')),
3384 b'drop': ([], _(b'removing %s\n')),
3384 b'drop': ([], _(b'removing %s\n')),
3385 b'forget': ([], _(b'forgetting %s\n')),
3385 b'forget': ([], _(b'forgetting %s\n')),
3386 b'undelete': ([], _(b'undeleting %s\n')),
3386 b'undelete': ([], _(b'undeleting %s\n')),
3387 b'noop': (None, _(b'no changes needed to %s\n')),
3387 b'noop': (None, _(b'no changes needed to %s\n')),
3388 b'unknown': (None, _(b'file not managed: %s\n')),
3388 b'unknown': (None, _(b'file not managed: %s\n')),
3389 }
3389 }
3390
3390
3391 # "constant" that convey the backup strategy.
3391 # "constant" that convey the backup strategy.
3392 # All set to `discard` if `no-backup` is set do avoid checking
3392 # All set to `discard` if `no-backup` is set do avoid checking
3393 # no_backup lower in the code.
3393 # no_backup lower in the code.
3394 # These values are ordered for comparison purposes
3394 # These values are ordered for comparison purposes
3395 backupinteractive = 3 # do backup if interactively modified
3395 backupinteractive = 3 # do backup if interactively modified
3396 backup = 2 # unconditionally do backup
3396 backup = 2 # unconditionally do backup
3397 check = 1 # check if the existing file differs from target
3397 check = 1 # check if the existing file differs from target
3398 discard = 0 # never do backup
3398 discard = 0 # never do backup
3399 if opts.get(b'no_backup'):
3399 if opts.get(b'no_backup'):
3400 backupinteractive = backup = check = discard
3400 backupinteractive = backup = check = discard
3401 if interactive:
3401 if interactive:
3402 dsmodifiedbackup = backupinteractive
3402 dsmodifiedbackup = backupinteractive
3403 else:
3403 else:
3404 dsmodifiedbackup = backup
3404 dsmodifiedbackup = backup
3405 tobackup = set()
3405 tobackup = set()
3406
3406
3407 backupanddel = actions[b'remove']
3407 backupanddel = actions[b'remove']
3408 if not opts.get(b'no_backup'):
3408 if not opts.get(b'no_backup'):
3409 backupanddel = actions[b'drop']
3409 backupanddel = actions[b'drop']
3410
3410
3411 disptable = (
3411 disptable = (
3412 # dispatch table:
3412 # dispatch table:
3413 # file state
3413 # file state
3414 # action
3414 # action
3415 # make backup
3415 # make backup
3416 ## Sets that results that will change file on disk
3416 ## Sets that results that will change file on disk
3417 # Modified compared to target, no local change
3417 # Modified compared to target, no local change
3418 (modified, actions[b'revert'], discard),
3418 (modified, actions[b'revert'], discard),
3419 # Modified compared to target, but local file is deleted
3419 # Modified compared to target, but local file is deleted
3420 (deleted, actions[b'revert'], discard),
3420 (deleted, actions[b'revert'], discard),
3421 # Modified compared to target, local change
3421 # Modified compared to target, local change
3422 (dsmodified, actions[b'revert'], dsmodifiedbackup),
3422 (dsmodified, actions[b'revert'], dsmodifiedbackup),
3423 # Added since target
3423 # Added since target
3424 (added, actions[b'remove'], discard),
3424 (added, actions[b'remove'], discard),
3425 # Added in working directory
3425 # Added in working directory
3426 (dsadded, actions[b'forget'], discard),
3426 (dsadded, actions[b'forget'], discard),
3427 # Added since target, have local modification
3427 # Added since target, have local modification
3428 (modadded, backupanddel, backup),
3428 (modadded, backupanddel, backup),
3429 # Added since target but file is missing in working directory
3429 # Added since target but file is missing in working directory
3430 (deladded, actions[b'drop'], discard),
3430 (deladded, actions[b'drop'], discard),
3431 # Removed since target, before working copy parent
3431 # Removed since target, before working copy parent
3432 (removed, actions[b'add'], discard),
3432 (removed, actions[b'add'], discard),
3433 # Same as `removed` but an unknown file exists at the same path
3433 # Same as `removed` but an unknown file exists at the same path
3434 (removunk, actions[b'add'], check),
3434 (removunk, actions[b'add'], check),
3435 # Removed since targe, marked as such in working copy parent
3435 # Removed since targe, marked as such in working copy parent
3436 (dsremoved, actions[b'undelete'], discard),
3436 (dsremoved, actions[b'undelete'], discard),
3437 # Same as `dsremoved` but an unknown file exists at the same path
3437 # Same as `dsremoved` but an unknown file exists at the same path
3438 (dsremovunk, actions[b'undelete'], check),
3438 (dsremovunk, actions[b'undelete'], check),
3439 ## the following sets does not result in any file changes
3439 ## the following sets does not result in any file changes
3440 # File with no modification
3440 # File with no modification
3441 (clean, actions[b'noop'], discard),
3441 (clean, actions[b'noop'], discard),
3442 # Existing file, not tracked anywhere
3442 # Existing file, not tracked anywhere
3443 (unknown, actions[b'unknown'], discard),
3443 (unknown, actions[b'unknown'], discard),
3444 )
3444 )
3445
3445
3446 for abs, exact in sorted(names.items()):
3446 for abs, exact in sorted(names.items()):
3447 # target file to be touch on disk (relative to cwd)
3447 # target file to be touch on disk (relative to cwd)
3448 target = repo.wjoin(abs)
3448 target = repo.wjoin(abs)
3449 # search the entry in the dispatch table.
3449 # search the entry in the dispatch table.
3450 # if the file is in any of these sets, it was touched in the working
3450 # if the file is in any of these sets, it was touched in the working
3451 # directory parent and we are sure it needs to be reverted.
3451 # directory parent and we are sure it needs to be reverted.
3452 for table, (xlist, msg), dobackup in disptable:
3452 for table, (xlist, msg), dobackup in disptable:
3453 if abs not in table:
3453 if abs not in table:
3454 continue
3454 continue
3455 if xlist is not None:
3455 if xlist is not None:
3456 xlist.append(abs)
3456 xlist.append(abs)
3457 if dobackup:
3457 if dobackup:
3458 # If in interactive mode, don't automatically create
3458 # If in interactive mode, don't automatically create
3459 # .orig files (issue4793)
3459 # .orig files (issue4793)
3460 if dobackup == backupinteractive:
3460 if dobackup == backupinteractive:
3461 tobackup.add(abs)
3461 tobackup.add(abs)
3462 elif backup <= dobackup or wctx[abs].cmp(ctx[abs]):
3462 elif backup <= dobackup or wctx[abs].cmp(ctx[abs]):
3463 absbakname = scmutil.backuppath(ui, repo, abs)
3463 absbakname = scmutil.backuppath(ui, repo, abs)
3464 bakname = os.path.relpath(
3464 bakname = os.path.relpath(
3465 absbakname, start=repo.root
3465 absbakname, start=repo.root
3466 )
3466 )
3467 ui.note(
3467 ui.note(
3468 _(b'saving current version of %s as %s\n')
3468 _(b'saving current version of %s as %s\n')
3469 % (uipathfn(abs), uipathfn(bakname))
3469 % (uipathfn(abs), uipathfn(bakname))
3470 )
3470 )
3471 if not opts.get(b'dry_run'):
3471 if not opts.get(b'dry_run'):
3472 if interactive:
3472 if interactive:
3473 util.copyfile(target, absbakname)
3473 util.copyfile(target, absbakname)
3474 else:
3474 else:
3475 util.rename(target, absbakname)
3475 util.rename(target, absbakname)
3476 if opts.get(b'dry_run'):
3476 if opts.get(b'dry_run'):
3477 if ui.verbose or not exact:
3477 if ui.verbose or not exact:
3478 ui.status(msg % uipathfn(abs))
3478 ui.status(msg % uipathfn(abs))
3479 elif exact:
3479 elif exact:
3480 ui.warn(msg % uipathfn(abs))
3480 ui.warn(msg % uipathfn(abs))
3481 break
3481 break
3482
3482
3483 if not opts.get(b'dry_run'):
3483 if not opts.get(b'dry_run'):
3484 needdata = (b'revert', b'add', b'undelete')
3484 needdata = (b'revert', b'add', b'undelete')
3485 oplist = [actions[name][0] for name in needdata]
3485 oplist = [actions[name][0] for name in needdata]
3486 prefetch = scmutil.prefetchfiles
3486 prefetch = scmutil.prefetchfiles
3487 matchfiles = scmutil.matchfiles(
3487 matchfiles = scmutil.matchfiles(
3488 repo, [f for sublist in oplist for f in sublist]
3488 repo, [f for sublist in oplist for f in sublist]
3489 )
3489 )
3490 prefetch(
3490 prefetch(
3491 repo,
3491 repo,
3492 [(ctx.rev(), matchfiles)],
3492 [(ctx.rev(), matchfiles)],
3493 )
3493 )
3494 match = scmutil.match(repo[None], pats)
3494 match = scmutil.match(repo[None], pats)
3495 _performrevert(
3495 _performrevert(
3496 repo,
3496 repo,
3497 ctx,
3497 ctx,
3498 names,
3498 names,
3499 uipathfn,
3499 uipathfn,
3500 actions,
3500 actions,
3501 match,
3501 match,
3502 interactive,
3502 interactive,
3503 tobackup,
3503 tobackup,
3504 )
3504 )
3505
3505
3506 if targetsubs:
3506 if targetsubs:
3507 # Revert the subrepos on the revert list
3507 # Revert the subrepos on the revert list
3508 for sub in targetsubs:
3508 for sub in targetsubs:
3509 try:
3509 try:
3510 wctx.sub(sub).revert(
3510 wctx.sub(sub).revert(
3511 ctx.substate[sub], *pats, **pycompat.strkwargs(opts)
3511 ctx.substate[sub], *pats, **pycompat.strkwargs(opts)
3512 )
3512 )
3513 except KeyError:
3513 except KeyError:
3514 raise error.Abort(
3514 raise error.Abort(
3515 b"subrepository '%s' does not exist in %s!"
3515 b"subrepository '%s' does not exist in %s!"
3516 % (sub, short(ctx.node()))
3516 % (sub, short(ctx.node()))
3517 )
3517 )
3518
3518
3519
3519
3520 def _performrevert(
3520 def _performrevert(
3521 repo,
3521 repo,
3522 ctx,
3522 ctx,
3523 names,
3523 names,
3524 uipathfn,
3524 uipathfn,
3525 actions,
3525 actions,
3526 match,
3526 match,
3527 interactive=False,
3527 interactive=False,
3528 tobackup=None,
3528 tobackup=None,
3529 ):
3529 ):
3530 """function that actually perform all the actions computed for revert
3530 """function that actually perform all the actions computed for revert
3531
3531
3532 This is an independent function to let extension to plug in and react to
3532 This is an independent function to let extension to plug in and react to
3533 the imminent revert.
3533 the imminent revert.
3534
3534
3535 Make sure you have the working directory locked when calling this function.
3535 Make sure you have the working directory locked when calling this function.
3536 """
3536 """
3537 parent, p2 = repo.dirstate.parents()
3537 parent, p2 = repo.dirstate.parents()
3538 node = ctx.node()
3538 node = ctx.node()
3539 excluded_files = []
3539 excluded_files = []
3540
3540
3541 def checkout(f):
3541 def checkout(f):
3542 fc = ctx[f]
3542 fc = ctx[f]
3543 repo.wwrite(f, fc.data(), fc.flags())
3543 repo.wwrite(f, fc.data(), fc.flags())
3544
3544
3545 def doremove(f):
3545 def doremove(f):
3546 try:
3546 try:
3547 rmdir = repo.ui.configbool(b'experimental', b'removeemptydirs')
3547 rmdir = repo.ui.configbool(b'experimental', b'removeemptydirs')
3548 repo.wvfs.unlinkpath(f, rmdir=rmdir)
3548 repo.wvfs.unlinkpath(f, rmdir=rmdir)
3549 except OSError:
3549 except OSError:
3550 pass
3550 pass
3551 repo.dirstate.remove(f)
3551 repo.dirstate.remove(f)
3552
3552
3553 def prntstatusmsg(action, f):
3553 def prntstatusmsg(action, f):
3554 exact = names[f]
3554 exact = names[f]
3555 if repo.ui.verbose or not exact:
3555 if repo.ui.verbose or not exact:
3556 repo.ui.status(actions[action][1] % uipathfn(f))
3556 repo.ui.status(actions[action][1] % uipathfn(f))
3557
3557
3558 audit_path = pathutil.pathauditor(repo.root, cached=True)
3558 audit_path = pathutil.pathauditor(repo.root, cached=True)
3559 for f in actions[b'forget'][0]:
3559 for f in actions[b'forget'][0]:
3560 if interactive:
3560 if interactive:
3561 choice = repo.ui.promptchoice(
3561 choice = repo.ui.promptchoice(
3562 _(b"forget added file %s (Yn)?$$ &Yes $$ &No") % uipathfn(f)
3562 _(b"forget added file %s (Yn)?$$ &Yes $$ &No") % uipathfn(f)
3563 )
3563 )
3564 if choice == 0:
3564 if choice == 0:
3565 prntstatusmsg(b'forget', f)
3565 prntstatusmsg(b'forget', f)
3566 repo.dirstate.drop(f)
3566 repo.dirstate.drop(f)
3567 else:
3567 else:
3568 excluded_files.append(f)
3568 excluded_files.append(f)
3569 else:
3569 else:
3570 prntstatusmsg(b'forget', f)
3570 prntstatusmsg(b'forget', f)
3571 repo.dirstate.drop(f)
3571 repo.dirstate.drop(f)
3572 for f in actions[b'remove'][0]:
3572 for f in actions[b'remove'][0]:
3573 audit_path(f)
3573 audit_path(f)
3574 if interactive:
3574 if interactive:
3575 choice = repo.ui.promptchoice(
3575 choice = repo.ui.promptchoice(
3576 _(b"remove added file %s (Yn)?$$ &Yes $$ &No") % uipathfn(f)
3576 _(b"remove added file %s (Yn)?$$ &Yes $$ &No") % uipathfn(f)
3577 )
3577 )
3578 if choice == 0:
3578 if choice == 0:
3579 prntstatusmsg(b'remove', f)
3579 prntstatusmsg(b'remove', f)
3580 doremove(f)
3580 doremove(f)
3581 else:
3581 else:
3582 excluded_files.append(f)
3582 excluded_files.append(f)
3583 else:
3583 else:
3584 prntstatusmsg(b'remove', f)
3584 prntstatusmsg(b'remove', f)
3585 doremove(f)
3585 doremove(f)
3586 for f in actions[b'drop'][0]:
3586 for f in actions[b'drop'][0]:
3587 audit_path(f)
3587 audit_path(f)
3588 prntstatusmsg(b'drop', f)
3588 prntstatusmsg(b'drop', f)
3589 repo.dirstate.remove(f)
3589 repo.dirstate.remove(f)
3590
3590
3591 normal = None
3591 normal = None
3592 if node == parent:
3592 if node == parent:
3593 # We're reverting to our parent. If possible, we'd like status
3593 # We're reverting to our parent. If possible, we'd like status
3594 # to report the file as clean. We have to use normallookup for
3594 # to report the file as clean. We have to use normallookup for
3595 # merges to avoid losing information about merged/dirty files.
3595 # merges to avoid losing information about merged/dirty files.
3596 if p2 != nullid:
3596 if p2 != nullid:
3597 normal = repo.dirstate.normallookup
3597 normal = repo.dirstate.normallookup
3598 else:
3598 else:
3599 normal = repo.dirstate.normal
3599 normal = repo.dirstate.normal
3600
3600
3601 newlyaddedandmodifiedfiles = set()
3601 newlyaddedandmodifiedfiles = set()
3602 if interactive:
3602 if interactive:
3603 # Prompt the user for changes to revert
3603 # Prompt the user for changes to revert
3604 torevert = [f for f in actions[b'revert'][0] if f not in excluded_files]
3604 torevert = [f for f in actions[b'revert'][0] if f not in excluded_files]
3605 m = scmutil.matchfiles(repo, torevert)
3605 m = scmutil.matchfiles(repo, torevert)
3606 diffopts = patch.difffeatureopts(
3606 diffopts = patch.difffeatureopts(
3607 repo.ui,
3607 repo.ui,
3608 whitespace=True,
3608 whitespace=True,
3609 section=b'commands',
3609 section=b'commands',
3610 configprefix=b'revert.interactive.',
3610 configprefix=b'revert.interactive.',
3611 )
3611 )
3612 diffopts.nodates = True
3612 diffopts.nodates = True
3613 diffopts.git = True
3613 diffopts.git = True
3614 operation = b'apply'
3614 operation = b'apply'
3615 if node == parent:
3615 if node == parent:
3616 if repo.ui.configbool(
3616 if repo.ui.configbool(
3617 b'experimental', b'revert.interactive.select-to-keep'
3617 b'experimental', b'revert.interactive.select-to-keep'
3618 ):
3618 ):
3619 operation = b'keep'
3619 operation = b'keep'
3620 else:
3620 else:
3621 operation = b'discard'
3621 operation = b'discard'
3622
3622
3623 if operation == b'apply':
3623 if operation == b'apply':
3624 diff = patch.diff(repo, None, ctx.node(), m, opts=diffopts)
3624 diff = patch.diff(repo, None, ctx.node(), m, opts=diffopts)
3625 else:
3625 else:
3626 diff = patch.diff(repo, ctx.node(), None, m, opts=diffopts)
3626 diff = patch.diff(repo, ctx.node(), None, m, opts=diffopts)
3627 originalchunks = patch.parsepatch(diff)
3627 originalchunks = patch.parsepatch(diff)
3628
3628
3629 try:
3629 try:
3630
3630
3631 chunks, opts = recordfilter(
3631 chunks, opts = recordfilter(
3632 repo.ui, originalchunks, match, operation=operation
3632 repo.ui, originalchunks, match, operation=operation
3633 )
3633 )
3634 if operation == b'discard':
3634 if operation == b'discard':
3635 chunks = patch.reversehunks(chunks)
3635 chunks = patch.reversehunks(chunks)
3636
3636
3637 except error.PatchError as err:
3637 except error.PatchError as err:
3638 raise error.Abort(_(b'error parsing patch: %s') % err)
3638 raise error.Abort(_(b'error parsing patch: %s') % err)
3639
3639
3640 # FIXME: when doing an interactive revert of a copy, there's no way of
3640 # FIXME: when doing an interactive revert of a copy, there's no way of
3641 # performing a partial revert of the added file, the only option is
3641 # performing a partial revert of the added file, the only option is
3642 # "remove added file <name> (Yn)?", so we don't need to worry about the
3642 # "remove added file <name> (Yn)?", so we don't need to worry about the
3643 # alsorestore value. Ideally we'd be able to partially revert
3643 # alsorestore value. Ideally we'd be able to partially revert
3644 # copied/renamed files.
3644 # copied/renamed files.
3645 newlyaddedandmodifiedfiles, unusedalsorestore = newandmodified(
3645 newlyaddedandmodifiedfiles, unusedalsorestore = newandmodified(
3646 chunks, originalchunks
3646 chunks, originalchunks
3647 )
3647 )
3648 if tobackup is None:
3648 if tobackup is None:
3649 tobackup = set()
3649 tobackup = set()
3650 # Apply changes
3650 # Apply changes
3651 fp = stringio()
3651 fp = stringio()
3652 # chunks are serialized per file, but files aren't sorted
3652 # chunks are serialized per file, but files aren't sorted
3653 for f in sorted({c.header.filename() for c in chunks if ishunk(c)}):
3653 for f in sorted({c.header.filename() for c in chunks if ishunk(c)}):
3654 prntstatusmsg(b'revert', f)
3654 prntstatusmsg(b'revert', f)
3655 files = set()
3655 files = set()
3656 for c in chunks:
3656 for c in chunks:
3657 if ishunk(c):
3657 if ishunk(c):
3658 abs = c.header.filename()
3658 abs = c.header.filename()
3659 # Create a backup file only if this hunk should be backed up
3659 # Create a backup file only if this hunk should be backed up
3660 if c.header.filename() in tobackup:
3660 if c.header.filename() in tobackup:
3661 target = repo.wjoin(abs)
3661 target = repo.wjoin(abs)
3662 bakname = scmutil.backuppath(repo.ui, repo, abs)
3662 bakname = scmutil.backuppath(repo.ui, repo, abs)
3663 util.copyfile(target, bakname)
3663 util.copyfile(target, bakname)
3664 tobackup.remove(abs)
3664 tobackup.remove(abs)
3665 if abs not in files:
3665 if abs not in files:
3666 files.add(abs)
3666 files.add(abs)
3667 if operation == b'keep':
3667 if operation == b'keep':
3668 checkout(abs)
3668 checkout(abs)
3669 c.write(fp)
3669 c.write(fp)
3670 dopatch = fp.tell()
3670 dopatch = fp.tell()
3671 fp.seek(0)
3671 fp.seek(0)
3672 if dopatch:
3672 if dopatch:
3673 try:
3673 try:
3674 patch.internalpatch(repo.ui, repo, fp, 1, eolmode=None)
3674 patch.internalpatch(repo.ui, repo, fp, 1, eolmode=None)
3675 except error.PatchError as err:
3675 except error.PatchError as err:
3676 raise error.Abort(pycompat.bytestr(err))
3676 raise error.Abort(pycompat.bytestr(err))
3677 del fp
3677 del fp
3678 else:
3678 else:
3679 for f in actions[b'revert'][0]:
3679 for f in actions[b'revert'][0]:
3680 prntstatusmsg(b'revert', f)
3680 prntstatusmsg(b'revert', f)
3681 checkout(f)
3681 checkout(f)
3682 if normal:
3682 if normal:
3683 normal(f)
3683 normal(f)
3684
3684
3685 for f in actions[b'add'][0]:
3685 for f in actions[b'add'][0]:
3686 # Don't checkout modified files, they are already created by the diff
3686 # Don't checkout modified files, they are already created by the diff
3687 if f not in newlyaddedandmodifiedfiles:
3687 if f not in newlyaddedandmodifiedfiles:
3688 prntstatusmsg(b'add', f)
3688 prntstatusmsg(b'add', f)
3689 checkout(f)
3689 checkout(f)
3690 repo.dirstate.add(f)
3690 repo.dirstate.add(f)
3691
3691
3692 normal = repo.dirstate.normallookup
3692 normal = repo.dirstate.normallookup
3693 if node == parent and p2 == nullid:
3693 if node == parent and p2 == nullid:
3694 normal = repo.dirstate.normal
3694 normal = repo.dirstate.normal
3695 for f in actions[b'undelete'][0]:
3695 for f in actions[b'undelete'][0]:
3696 if interactive:
3696 if interactive:
3697 choice = repo.ui.promptchoice(
3697 choice = repo.ui.promptchoice(
3698 _(b"add back removed file %s (Yn)?$$ &Yes $$ &No") % f
3698 _(b"add back removed file %s (Yn)?$$ &Yes $$ &No") % f
3699 )
3699 )
3700 if choice == 0:
3700 if choice == 0:
3701 prntstatusmsg(b'undelete', f)
3701 prntstatusmsg(b'undelete', f)
3702 checkout(f)
3702 checkout(f)
3703 normal(f)
3703 normal(f)
3704 else:
3704 else:
3705 excluded_files.append(f)
3705 excluded_files.append(f)
3706 else:
3706 else:
3707 prntstatusmsg(b'undelete', f)
3707 prntstatusmsg(b'undelete', f)
3708 checkout(f)
3708 checkout(f)
3709 normal(f)
3709 normal(f)
3710
3710
3711 copied = copies.pathcopies(repo[parent], ctx)
3711 copied = copies.pathcopies(repo[parent], ctx)
3712
3712
3713 for f in (
3713 for f in (
3714 actions[b'add'][0] + actions[b'undelete'][0] + actions[b'revert'][0]
3714 actions[b'add'][0] + actions[b'undelete'][0] + actions[b'revert'][0]
3715 ):
3715 ):
3716 if f in copied:
3716 if f in copied:
3717 repo.dirstate.copy(copied[f], f)
3717 repo.dirstate.copy(copied[f], f)
3718
3718
3719
3719
3720 # a list of (ui, repo, otherpeer, opts, missing) functions called by
3720 # a list of (ui, repo, otherpeer, opts, missing) functions called by
3721 # commands.outgoing. "missing" is "missing" of the result of
3721 # commands.outgoing. "missing" is "missing" of the result of
3722 # "findcommonoutgoing()"
3722 # "findcommonoutgoing()"
3723 outgoinghooks = util.hooks()
3723 outgoinghooks = util.hooks()
3724
3724
3725 # a list of (ui, repo) functions called by commands.summary
3725 # a list of (ui, repo) functions called by commands.summary
3726 summaryhooks = util.hooks()
3726 summaryhooks = util.hooks()
3727
3727
3728 # a list of (ui, repo, opts, changes) functions called by commands.summary.
3728 # a list of (ui, repo, opts, changes) functions called by commands.summary.
3729 #
3729 #
3730 # functions should return tuple of booleans below, if 'changes' is None:
3730 # functions should return tuple of booleans below, if 'changes' is None:
3731 # (whether-incomings-are-needed, whether-outgoings-are-needed)
3731 # (whether-incomings-are-needed, whether-outgoings-are-needed)
3732 #
3732 #
3733 # otherwise, 'changes' is a tuple of tuples below:
3733 # otherwise, 'changes' is a tuple of tuples below:
3734 # - (sourceurl, sourcebranch, sourcepeer, incoming)
3734 # - (sourceurl, sourcebranch, sourcepeer, incoming)
3735 # - (desturl, destbranch, destpeer, outgoing)
3735 # - (desturl, destbranch, destpeer, outgoing)
3736 summaryremotehooks = util.hooks()
3736 summaryremotehooks = util.hooks()
3737
3737
3738
3738
3739 def checkunfinished(repo, commit=False, skipmerge=False):
3739 def checkunfinished(repo, commit=False, skipmerge=False):
3740 """Look for an unfinished multistep operation, like graft, and abort
3740 """Look for an unfinished multistep operation, like graft, and abort
3741 if found. It's probably good to check this right before
3741 if found. It's probably good to check this right before
3742 bailifchanged().
3742 bailifchanged().
3743 """
3743 """
3744 # Check for non-clearable states first, so things like rebase will take
3744 # Check for non-clearable states first, so things like rebase will take
3745 # precedence over update.
3745 # precedence over update.
3746 for state in statemod._unfinishedstates:
3746 for state in statemod._unfinishedstates:
3747 if (
3747 if (
3748 state._clearable
3748 state._clearable
3749 or (commit and state._allowcommit)
3749 or (commit and state._allowcommit)
3750 or state._reportonly
3750 or state._reportonly
3751 ):
3751 ):
3752 continue
3752 continue
3753 if state.isunfinished(repo):
3753 if state.isunfinished(repo):
3754 raise error.StateError(state.msg(), hint=state.hint())
3754 raise error.StateError(state.msg(), hint=state.hint())
3755
3755
3756 for s in statemod._unfinishedstates:
3756 for s in statemod._unfinishedstates:
3757 if (
3757 if (
3758 not s._clearable
3758 not s._clearable
3759 or (commit and s._allowcommit)
3759 or (commit and s._allowcommit)
3760 or (s._opname == b'merge' and skipmerge)
3760 or (s._opname == b'merge' and skipmerge)
3761 or s._reportonly
3761 or s._reportonly
3762 ):
3762 ):
3763 continue
3763 continue
3764 if s.isunfinished(repo):
3764 if s.isunfinished(repo):
3765 raise error.StateError(s.msg(), hint=s.hint())
3765 raise error.StateError(s.msg(), hint=s.hint())
3766
3766
3767
3767
3768 def clearunfinished(repo):
3768 def clearunfinished(repo):
3769 """Check for unfinished operations (as above), and clear the ones
3769 """Check for unfinished operations (as above), and clear the ones
3770 that are clearable.
3770 that are clearable.
3771 """
3771 """
3772 for state in statemod._unfinishedstates:
3772 for state in statemod._unfinishedstates:
3773 if state._reportonly:
3773 if state._reportonly:
3774 continue
3774 continue
3775 if not state._clearable and state.isunfinished(repo):
3775 if not state._clearable and state.isunfinished(repo):
3776 raise error.StateError(state.msg(), hint=state.hint())
3776 raise error.StateError(state.msg(), hint=state.hint())
3777
3777
3778 for s in statemod._unfinishedstates:
3778 for s in statemod._unfinishedstates:
3779 if s._opname == b'merge' or state._reportonly:
3779 if s._opname == b'merge' or s._reportonly:
3780 continue
3780 continue
3781 if s._clearable and s.isunfinished(repo):
3781 if s._clearable and s.isunfinished(repo):
3782 util.unlink(repo.vfs.join(s._fname))
3782 util.unlink(repo.vfs.join(s._fname))
3783
3783
3784
3784
3785 def getunfinishedstate(repo):
3785 def getunfinishedstate(repo):
3786 """Checks for unfinished operations and returns statecheck object
3786 """Checks for unfinished operations and returns statecheck object
3787 for it"""
3787 for it"""
3788 for state in statemod._unfinishedstates:
3788 for state in statemod._unfinishedstates:
3789 if state.isunfinished(repo):
3789 if state.isunfinished(repo):
3790 return state
3790 return state
3791 return None
3791 return None
3792
3792
3793
3793
3794 def howtocontinue(repo):
3794 def howtocontinue(repo):
3795 """Check for an unfinished operation and return the command to finish
3795 """Check for an unfinished operation and return the command to finish
3796 it.
3796 it.
3797
3797
3798 statemod._unfinishedstates list is checked for an unfinished operation
3798 statemod._unfinishedstates list is checked for an unfinished operation
3799 and the corresponding message to finish it is generated if a method to
3799 and the corresponding message to finish it is generated if a method to
3800 continue is supported by the operation.
3800 continue is supported by the operation.
3801
3801
3802 Returns a (msg, warning) tuple. 'msg' is a string and 'warning' is
3802 Returns a (msg, warning) tuple. 'msg' is a string and 'warning' is
3803 a boolean.
3803 a boolean.
3804 """
3804 """
3805 contmsg = _(b"continue: %s")
3805 contmsg = _(b"continue: %s")
3806 for state in statemod._unfinishedstates:
3806 for state in statemod._unfinishedstates:
3807 if not state._continueflag:
3807 if not state._continueflag:
3808 continue
3808 continue
3809 if state.isunfinished(repo):
3809 if state.isunfinished(repo):
3810 return contmsg % state.continuemsg(), True
3810 return contmsg % state.continuemsg(), True
3811 if repo[None].dirty(missing=True, merge=False, branch=False):
3811 if repo[None].dirty(missing=True, merge=False, branch=False):
3812 return contmsg % _(b"hg commit"), False
3812 return contmsg % _(b"hg commit"), False
3813 return None, None
3813 return None, None
3814
3814
3815
3815
3816 def checkafterresolved(repo):
3816 def checkafterresolved(repo):
3817 """Inform the user about the next action after completing hg resolve
3817 """Inform the user about the next action after completing hg resolve
3818
3818
3819 If there's a an unfinished operation that supports continue flag,
3819 If there's a an unfinished operation that supports continue flag,
3820 howtocontinue will yield repo.ui.warn as the reporter.
3820 howtocontinue will yield repo.ui.warn as the reporter.
3821
3821
3822 Otherwise, it will yield repo.ui.note.
3822 Otherwise, it will yield repo.ui.note.
3823 """
3823 """
3824 msg, warning = howtocontinue(repo)
3824 msg, warning = howtocontinue(repo)
3825 if msg is not None:
3825 if msg is not None:
3826 if warning:
3826 if warning:
3827 repo.ui.warn(b"%s\n" % msg)
3827 repo.ui.warn(b"%s\n" % msg)
3828 else:
3828 else:
3829 repo.ui.note(b"%s\n" % msg)
3829 repo.ui.note(b"%s\n" % msg)
3830
3830
3831
3831
3832 def wrongtooltocontinue(repo, task):
3832 def wrongtooltocontinue(repo, task):
3833 """Raise an abort suggesting how to properly continue if there is an
3833 """Raise an abort suggesting how to properly continue if there is an
3834 active task.
3834 active task.
3835
3835
3836 Uses howtocontinue() to find the active task.
3836 Uses howtocontinue() to find the active task.
3837
3837
3838 If there's no task (repo.ui.note for 'hg commit'), it does not offer
3838 If there's no task (repo.ui.note for 'hg commit'), it does not offer
3839 a hint.
3839 a hint.
3840 """
3840 """
3841 after = howtocontinue(repo)
3841 after = howtocontinue(repo)
3842 hint = None
3842 hint = None
3843 if after[1]:
3843 if after[1]:
3844 hint = after[0]
3844 hint = after[0]
3845 raise error.StateError(_(b'no %s in progress') % task, hint=hint)
3845 raise error.StateError(_(b'no %s in progress') % task, hint=hint)
3846
3846
3847
3847
3848 def abortgraft(ui, repo, graftstate):
3848 def abortgraft(ui, repo, graftstate):
3849 """abort the interrupted graft and rollbacks to the state before interrupted
3849 """abort the interrupted graft and rollbacks to the state before interrupted
3850 graft"""
3850 graft"""
3851 if not graftstate.exists():
3851 if not graftstate.exists():
3852 raise error.StateError(_(b"no interrupted graft to abort"))
3852 raise error.StateError(_(b"no interrupted graft to abort"))
3853 statedata = readgraftstate(repo, graftstate)
3853 statedata = readgraftstate(repo, graftstate)
3854 newnodes = statedata.get(b'newnodes')
3854 newnodes = statedata.get(b'newnodes')
3855 if newnodes is None:
3855 if newnodes is None:
3856 # and old graft state which does not have all the data required to abort
3856 # and old graft state which does not have all the data required to abort
3857 # the graft
3857 # the graft
3858 raise error.Abort(_(b"cannot abort using an old graftstate"))
3858 raise error.Abort(_(b"cannot abort using an old graftstate"))
3859
3859
3860 # changeset from which graft operation was started
3860 # changeset from which graft operation was started
3861 if len(newnodes) > 0:
3861 if len(newnodes) > 0:
3862 startctx = repo[newnodes[0]].p1()
3862 startctx = repo[newnodes[0]].p1()
3863 else:
3863 else:
3864 startctx = repo[b'.']
3864 startctx = repo[b'.']
3865 # whether to strip or not
3865 # whether to strip or not
3866 cleanup = False
3866 cleanup = False
3867
3867
3868 if newnodes:
3868 if newnodes:
3869 newnodes = [repo[r].rev() for r in newnodes]
3869 newnodes = [repo[r].rev() for r in newnodes]
3870 cleanup = True
3870 cleanup = True
3871 # checking that none of the newnodes turned public or is public
3871 # checking that none of the newnodes turned public or is public
3872 immutable = [c for c in newnodes if not repo[c].mutable()]
3872 immutable = [c for c in newnodes if not repo[c].mutable()]
3873 if immutable:
3873 if immutable:
3874 repo.ui.warn(
3874 repo.ui.warn(
3875 _(b"cannot clean up public changesets %s\n")
3875 _(b"cannot clean up public changesets %s\n")
3876 % b', '.join(bytes(repo[r]) for r in immutable),
3876 % b', '.join(bytes(repo[r]) for r in immutable),
3877 hint=_(b"see 'hg help phases' for details"),
3877 hint=_(b"see 'hg help phases' for details"),
3878 )
3878 )
3879 cleanup = False
3879 cleanup = False
3880
3880
3881 # checking that no new nodes are created on top of grafted revs
3881 # checking that no new nodes are created on top of grafted revs
3882 desc = set(repo.changelog.descendants(newnodes))
3882 desc = set(repo.changelog.descendants(newnodes))
3883 if desc - set(newnodes):
3883 if desc - set(newnodes):
3884 repo.ui.warn(
3884 repo.ui.warn(
3885 _(
3885 _(
3886 b"new changesets detected on destination "
3886 b"new changesets detected on destination "
3887 b"branch, can't strip\n"
3887 b"branch, can't strip\n"
3888 )
3888 )
3889 )
3889 )
3890 cleanup = False
3890 cleanup = False
3891
3891
3892 if cleanup:
3892 if cleanup:
3893 with repo.wlock(), repo.lock():
3893 with repo.wlock(), repo.lock():
3894 mergemod.clean_update(startctx)
3894 mergemod.clean_update(startctx)
3895 # stripping the new nodes created
3895 # stripping the new nodes created
3896 strippoints = [
3896 strippoints = [
3897 c.node() for c in repo.set(b"roots(%ld)", newnodes)
3897 c.node() for c in repo.set(b"roots(%ld)", newnodes)
3898 ]
3898 ]
3899 repair.strip(repo.ui, repo, strippoints, backup=False)
3899 repair.strip(repo.ui, repo, strippoints, backup=False)
3900
3900
3901 if not cleanup:
3901 if not cleanup:
3902 # we don't update to the startnode if we can't strip
3902 # we don't update to the startnode if we can't strip
3903 startctx = repo[b'.']
3903 startctx = repo[b'.']
3904 mergemod.clean_update(startctx)
3904 mergemod.clean_update(startctx)
3905
3905
3906 ui.status(_(b"graft aborted\n"))
3906 ui.status(_(b"graft aborted\n"))
3907 ui.status(_(b"working directory is now at %s\n") % startctx.hex()[:12])
3907 ui.status(_(b"working directory is now at %s\n") % startctx.hex()[:12])
3908 graftstate.delete()
3908 graftstate.delete()
3909 return 0
3909 return 0
3910
3910
3911
3911
3912 def readgraftstate(repo, graftstate):
3912 def readgraftstate(repo, graftstate):
3913 # type: (Any, statemod.cmdstate) -> Dict[bytes, Any]
3913 # type: (Any, statemod.cmdstate) -> Dict[bytes, Any]
3914 """read the graft state file and return a dict of the data stored in it"""
3914 """read the graft state file and return a dict of the data stored in it"""
3915 try:
3915 try:
3916 return graftstate.read()
3916 return graftstate.read()
3917 except error.CorruptedState:
3917 except error.CorruptedState:
3918 nodes = repo.vfs.read(b'graftstate').splitlines()
3918 nodes = repo.vfs.read(b'graftstate').splitlines()
3919 return {b'nodes': nodes}
3919 return {b'nodes': nodes}
3920
3920
3921
3921
3922 def hgabortgraft(ui, repo):
3922 def hgabortgraft(ui, repo):
3923 """ abort logic for aborting graft using 'hg abort'"""
3923 """ abort logic for aborting graft using 'hg abort'"""
3924 with repo.wlock():
3924 with repo.wlock():
3925 graftstate = statemod.cmdstate(repo, b'graftstate')
3925 graftstate = statemod.cmdstate(repo, b'graftstate')
3926 return abortgraft(ui, repo, graftstate)
3926 return abortgraft(ui, repo, graftstate)
General Comments 0
You need to be logged in to leave comments. Login now