##// END OF EJS Templates
forget: pass around uipathfn and use instead of m.rel() (API)...
Martin von Zweigbergk -
r41802:16a49c77 default
parent child Browse files
Show More
@@ -1,1516 +1,1516 b''
1 1 # Copyright 2009-2010 Gregory P. Ward
2 2 # Copyright 2009-2010 Intelerad Medical Systems Incorporated
3 3 # Copyright 2010-2011 Fog Creek Software
4 4 # Copyright 2010-2011 Unity Technologies
5 5 #
6 6 # This software may be used and distributed according to the terms of the
7 7 # GNU General Public License version 2 or any later version.
8 8
9 9 '''Overridden Mercurial commands and functions for the largefiles extension'''
10 10 from __future__ import absolute_import
11 11
12 12 import copy
13 13 import os
14 14
15 15 from mercurial.i18n import _
16 16
17 17 from mercurial.hgweb import (
18 18 webcommands,
19 19 )
20 20
21 21 from mercurial import (
22 22 archival,
23 23 cmdutil,
24 24 copies as copiesmod,
25 25 error,
26 26 exchange,
27 27 extensions,
28 28 exthelper,
29 29 filemerge,
30 30 hg,
31 31 logcmdutil,
32 32 match as matchmod,
33 33 merge,
34 34 pathutil,
35 35 pycompat,
36 36 scmutil,
37 37 smartset,
38 38 subrepo,
39 39 upgrade,
40 40 url as urlmod,
41 41 util,
42 42 )
43 43
44 44 from . import (
45 45 lfcommands,
46 46 lfutil,
47 47 storefactory,
48 48 )
49 49
50 50 eh = exthelper.exthelper()
51 51
52 52 # -- Utility functions: commonly/repeatedly needed functionality ---------------
53 53
54 54 def composelargefilematcher(match, manifest):
55 55 '''create a matcher that matches only the largefiles in the original
56 56 matcher'''
57 57 m = copy.copy(match)
58 58 lfile = lambda f: lfutil.standin(f) in manifest
59 59 m._files = [lf for lf in m._files if lfile(lf)]
60 60 m._fileset = set(m._files)
61 61 m.always = lambda: False
62 62 origmatchfn = m.matchfn
63 63 m.matchfn = lambda f: lfile(f) and origmatchfn(f)
64 64 return m
65 65
66 66 def composenormalfilematcher(match, manifest, exclude=None):
67 67 excluded = set()
68 68 if exclude is not None:
69 69 excluded.update(exclude)
70 70
71 71 m = copy.copy(match)
72 72 notlfile = lambda f: not (lfutil.isstandin(f) or lfutil.standin(f) in
73 73 manifest or f in excluded)
74 74 m._files = [lf for lf in m._files if notlfile(lf)]
75 75 m._fileset = set(m._files)
76 76 m.always = lambda: False
77 77 origmatchfn = m.matchfn
78 78 m.matchfn = lambda f: notlfile(f) and origmatchfn(f)
79 79 return m
80 80
81 81 def addlargefiles(ui, repo, isaddremove, matcher, **opts):
82 82 large = opts.get(r'large')
83 83 lfsize = lfutil.getminsize(
84 84 ui, lfutil.islfilesrepo(repo), opts.get(r'lfsize'))
85 85
86 86 lfmatcher = None
87 87 if lfutil.islfilesrepo(repo):
88 88 lfpats = ui.configlist(lfutil.longname, 'patterns')
89 89 if lfpats:
90 90 lfmatcher = matchmod.match(repo.root, '', list(lfpats))
91 91
92 92 lfnames = []
93 93 m = matcher
94 94
95 95 wctx = repo[None]
96 96 for f in wctx.walk(matchmod.badmatch(m, lambda x, y: None)):
97 97 exact = m.exact(f)
98 98 lfile = lfutil.standin(f) in wctx
99 99 nfile = f in wctx
100 100 exists = lfile or nfile
101 101
102 102 # addremove in core gets fancy with the name, add doesn't
103 103 if isaddremove:
104 104 name = m.uipath(f)
105 105 else:
106 106 name = m.rel(f)
107 107
108 108 # Don't warn the user when they attempt to add a normal tracked file.
109 109 # The normal add code will do that for us.
110 110 if exact and exists:
111 111 if lfile:
112 112 ui.warn(_('%s already a largefile\n') % name)
113 113 continue
114 114
115 115 if (exact or not exists) and not lfutil.isstandin(f):
116 116 # In case the file was removed previously, but not committed
117 117 # (issue3507)
118 118 if not repo.wvfs.exists(f):
119 119 continue
120 120
121 121 abovemin = (lfsize and
122 122 repo.wvfs.lstat(f).st_size >= lfsize * 1024 * 1024)
123 123 if large or abovemin or (lfmatcher and lfmatcher(f)):
124 124 lfnames.append(f)
125 125 if ui.verbose or not exact:
126 126 ui.status(_('adding %s as a largefile\n') % name)
127 127
128 128 bad = []
129 129
130 130 # Need to lock, otherwise there could be a race condition between
131 131 # when standins are created and added to the repo.
132 132 with repo.wlock():
133 133 if not opts.get(r'dry_run'):
134 134 standins = []
135 135 lfdirstate = lfutil.openlfdirstate(ui, repo)
136 136 for f in lfnames:
137 137 standinname = lfutil.standin(f)
138 138 lfutil.writestandin(repo, standinname, hash='',
139 139 executable=lfutil.getexecutable(repo.wjoin(f)))
140 140 standins.append(standinname)
141 141 if lfdirstate[f] == 'r':
142 142 lfdirstate.normallookup(f)
143 143 else:
144 144 lfdirstate.add(f)
145 145 lfdirstate.write()
146 146 bad += [lfutil.splitstandin(f)
147 147 for f in repo[None].add(standins)
148 148 if f in m.files()]
149 149
150 150 added = [f for f in lfnames if f not in bad]
151 151 return added, bad
152 152
153 153 def removelargefiles(ui, repo, isaddremove, matcher, dryrun, **opts):
154 154 after = opts.get(r'after')
155 155 m = composelargefilematcher(matcher, repo[None].manifest())
156 156 try:
157 157 repo.lfstatus = True
158 158 s = repo.status(match=m, clean=not isaddremove)
159 159 finally:
160 160 repo.lfstatus = False
161 161 manifest = repo[None].manifest()
162 162 modified, added, deleted, clean = [[f for f in list
163 163 if lfutil.standin(f) in manifest]
164 164 for list in (s.modified, s.added,
165 165 s.deleted, s.clean)]
166 166
167 167 def warn(files, msg):
168 168 for f in files:
169 169 ui.warn(msg % m.rel(f))
170 170 return int(len(files) > 0)
171 171
172 172 if after:
173 173 remove = deleted
174 174 result = warn(modified + added + clean,
175 175 _('not removing %s: file still exists\n'))
176 176 else:
177 177 remove = deleted + clean
178 178 result = warn(modified, _('not removing %s: file is modified (use -f'
179 179 ' to force removal)\n'))
180 180 result = warn(added, _('not removing %s: file has been marked for add'
181 181 ' (use forget to undo)\n')) or result
182 182
183 183 # Need to lock because standin files are deleted then removed from the
184 184 # repository and we could race in-between.
185 185 with repo.wlock():
186 186 lfdirstate = lfutil.openlfdirstate(ui, repo)
187 187 for f in sorted(remove):
188 188 if ui.verbose or not m.exact(f):
189 189 # addremove in core gets fancy with the name, remove doesn't
190 190 if isaddremove:
191 191 name = m.uipath(f)
192 192 else:
193 193 name = m.rel(f)
194 194 ui.status(_('removing %s\n') % name)
195 195
196 196 if not dryrun:
197 197 if not after:
198 198 repo.wvfs.unlinkpath(f, ignoremissing=True)
199 199
200 200 if dryrun:
201 201 return result
202 202
203 203 remove = [lfutil.standin(f) for f in remove]
204 204 # If this is being called by addremove, let the original addremove
205 205 # function handle this.
206 206 if not isaddremove:
207 207 for f in remove:
208 208 repo.wvfs.unlinkpath(f, ignoremissing=True)
209 209 repo[None].forget(remove)
210 210
211 211 for f in remove:
212 212 lfutil.synclfdirstate(repo, lfdirstate, lfutil.splitstandin(f),
213 213 False)
214 214
215 215 lfdirstate.write()
216 216
217 217 return result
218 218
219 219 # For overriding mercurial.hgweb.webcommands so that largefiles will
220 220 # appear at their right place in the manifests.
221 221 @eh.wrapfunction(webcommands, 'decodepath')
222 222 def decodepath(orig, path):
223 223 return lfutil.splitstandin(path) or path
224 224
225 225 # -- Wrappers: modify existing commands --------------------------------
226 226
227 227 @eh.wrapcommand('add',
228 228 opts=[('', 'large', None, _('add as largefile')),
229 229 ('', 'normal', None, _('add as normal file')),
230 230 ('', 'lfsize', '', _('add all files above this size (in megabytes) '
231 231 'as largefiles (default: 10)'))])
232 232 def overrideadd(orig, ui, repo, *pats, **opts):
233 233 if opts.get(r'normal') and opts.get(r'large'):
234 234 raise error.Abort(_('--normal cannot be used with --large'))
235 235 return orig(ui, repo, *pats, **opts)
236 236
237 237 @eh.wrapfunction(cmdutil, 'add')
238 238 def cmdutiladd(orig, ui, repo, matcher, prefix, uipathfn, explicitonly, **opts):
239 239 # The --normal flag short circuits this override
240 240 if opts.get(r'normal'):
241 241 return orig(ui, repo, matcher, prefix, uipathfn, explicitonly, **opts)
242 242
243 243 ladded, lbad = addlargefiles(ui, repo, False, matcher, **opts)
244 244 normalmatcher = composenormalfilematcher(matcher, repo[None].manifest(),
245 245 ladded)
246 246 bad = orig(ui, repo, normalmatcher, prefix, uipathfn, explicitonly, **opts)
247 247
248 248 bad.extend(f for f in lbad)
249 249 return bad
250 250
251 251 @eh.wrapfunction(cmdutil, 'remove')
252 252 def cmdutilremove(orig, ui, repo, matcher, prefix, uipathfn, after, force,
253 253 subrepos, dryrun):
254 254 normalmatcher = composenormalfilematcher(matcher, repo[None].manifest())
255 255 result = orig(ui, repo, normalmatcher, prefix, uipathfn, after, force,
256 256 subrepos, dryrun)
257 257 return removelargefiles(ui, repo, False, matcher, dryrun, after=after,
258 258 force=force) or result
259 259
260 260 @eh.wrapfunction(subrepo.hgsubrepo, 'status')
261 261 def overridestatusfn(orig, repo, rev2, **opts):
262 262 try:
263 263 repo._repo.lfstatus = True
264 264 return orig(repo, rev2, **opts)
265 265 finally:
266 266 repo._repo.lfstatus = False
267 267
268 268 @eh.wrapcommand('status')
269 269 def overridestatus(orig, ui, repo, *pats, **opts):
270 270 try:
271 271 repo.lfstatus = True
272 272 return orig(ui, repo, *pats, **opts)
273 273 finally:
274 274 repo.lfstatus = False
275 275
276 276 @eh.wrapfunction(subrepo.hgsubrepo, 'dirty')
277 277 def overridedirty(orig, repo, ignoreupdate=False, missing=False):
278 278 try:
279 279 repo._repo.lfstatus = True
280 280 return orig(repo, ignoreupdate=ignoreupdate, missing=missing)
281 281 finally:
282 282 repo._repo.lfstatus = False
283 283
284 284 @eh.wrapcommand('log')
285 285 def overridelog(orig, ui, repo, *pats, **opts):
286 286 def overridematchandpats(orig, ctx, pats=(), opts=None, globbed=False,
287 287 default='relpath', badfn=None):
288 288 """Matcher that merges root directory with .hglf, suitable for log.
289 289 It is still possible to match .hglf directly.
290 290 For any listed files run log on the standin too.
291 291 matchfn tries both the given filename and with .hglf stripped.
292 292 """
293 293 if opts is None:
294 294 opts = {}
295 295 matchandpats = orig(ctx, pats, opts, globbed, default, badfn=badfn)
296 296 m, p = copy.copy(matchandpats)
297 297
298 298 if m.always():
299 299 # We want to match everything anyway, so there's no benefit trying
300 300 # to add standins.
301 301 return matchandpats
302 302
303 303 pats = set(p)
304 304
305 305 def fixpats(pat, tostandin=lfutil.standin):
306 306 if pat.startswith('set:'):
307 307 return pat
308 308
309 309 kindpat = matchmod._patsplit(pat, None)
310 310
311 311 if kindpat[0] is not None:
312 312 return kindpat[0] + ':' + tostandin(kindpat[1])
313 313 return tostandin(kindpat[1])
314 314
315 315 if m._cwd:
316 316 hglf = lfutil.shortname
317 317 back = util.pconvert(m.rel(hglf)[:-len(hglf)])
318 318
319 319 def tostandin(f):
320 320 # The file may already be a standin, so truncate the back
321 321 # prefix and test before mangling it. This avoids turning
322 322 # 'glob:../.hglf/foo*' into 'glob:../.hglf/../.hglf/foo*'.
323 323 if f.startswith(back) and lfutil.splitstandin(f[len(back):]):
324 324 return f
325 325
326 326 # An absolute path is from outside the repo, so truncate the
327 327 # path to the root before building the standin. Otherwise cwd
328 328 # is somewhere in the repo, relative to root, and needs to be
329 329 # prepended before building the standin.
330 330 if os.path.isabs(m._cwd):
331 331 f = f[len(back):]
332 332 else:
333 333 f = m._cwd + '/' + f
334 334 return back + lfutil.standin(f)
335 335 else:
336 336 def tostandin(f):
337 337 if lfutil.isstandin(f):
338 338 return f
339 339 return lfutil.standin(f)
340 340 pats.update(fixpats(f, tostandin) for f in p)
341 341
342 342 for i in range(0, len(m._files)):
343 343 # Don't add '.hglf' to m.files, since that is already covered by '.'
344 344 if m._files[i] == '.':
345 345 continue
346 346 standin = lfutil.standin(m._files[i])
347 347 # If the "standin" is a directory, append instead of replace to
348 348 # support naming a directory on the command line with only
349 349 # largefiles. The original directory is kept to support normal
350 350 # files.
351 351 if standin in ctx:
352 352 m._files[i] = standin
353 353 elif m._files[i] not in ctx and repo.wvfs.isdir(standin):
354 354 m._files.append(standin)
355 355
356 356 m._fileset = set(m._files)
357 357 m.always = lambda: False
358 358 origmatchfn = m.matchfn
359 359 def lfmatchfn(f):
360 360 lf = lfutil.splitstandin(f)
361 361 if lf is not None and origmatchfn(lf):
362 362 return True
363 363 r = origmatchfn(f)
364 364 return r
365 365 m.matchfn = lfmatchfn
366 366
367 367 ui.debug('updated patterns: %s\n' % ', '.join(sorted(pats)))
368 368 return m, pats
369 369
370 370 # For hg log --patch, the match object is used in two different senses:
371 371 # (1) to determine what revisions should be printed out, and
372 372 # (2) to determine what files to print out diffs for.
373 373 # The magic matchandpats override should be used for case (1) but not for
374 374 # case (2).
375 375 oldmatchandpats = scmutil.matchandpats
376 376 def overridemakefilematcher(orig, repo, pats, opts, badfn=None):
377 377 wctx = repo[None]
378 378 match, pats = oldmatchandpats(wctx, pats, opts, badfn=badfn)
379 379 return lambda ctx: match
380 380
381 381 wrappedmatchandpats = extensions.wrappedfunction(scmutil, 'matchandpats',
382 382 overridematchandpats)
383 383 wrappedmakefilematcher = extensions.wrappedfunction(
384 384 logcmdutil, '_makenofollowfilematcher', overridemakefilematcher)
385 385 with wrappedmatchandpats, wrappedmakefilematcher:
386 386 return orig(ui, repo, *pats, **opts)
387 387
388 388 @eh.wrapcommand('verify',
389 389 opts=[('', 'large', None,
390 390 _('verify that all largefiles in current revision exists')),
391 391 ('', 'lfa', None,
392 392 _('verify largefiles in all revisions, not just current')),
393 393 ('', 'lfc', None,
394 394 _('verify local largefile contents, not just existence'))])
395 395 def overrideverify(orig, ui, repo, *pats, **opts):
396 396 large = opts.pop(r'large', False)
397 397 all = opts.pop(r'lfa', False)
398 398 contents = opts.pop(r'lfc', False)
399 399
400 400 result = orig(ui, repo, *pats, **opts)
401 401 if large or all or contents:
402 402 result = result or lfcommands.verifylfiles(ui, repo, all, contents)
403 403 return result
404 404
405 405 @eh.wrapcommand('debugstate',
406 406 opts=[('', 'large', None, _('display largefiles dirstate'))])
407 407 def overridedebugstate(orig, ui, repo, *pats, **opts):
408 408 large = opts.pop(r'large', False)
409 409 if large:
410 410 class fakerepo(object):
411 411 dirstate = lfutil.openlfdirstate(ui, repo)
412 412 orig(ui, fakerepo, *pats, **opts)
413 413 else:
414 414 orig(ui, repo, *pats, **opts)
415 415
416 416 # Before starting the manifest merge, merge.updates will call
417 417 # _checkunknownfile to check if there are any files in the merged-in
418 418 # changeset that collide with unknown files in the working copy.
419 419 #
420 420 # The largefiles are seen as unknown, so this prevents us from merging
421 421 # in a file 'foo' if we already have a largefile with the same name.
422 422 #
423 423 # The overridden function filters the unknown files by removing any
424 424 # largefiles. This makes the merge proceed and we can then handle this
425 425 # case further in the overridden calculateupdates function below.
426 426 @eh.wrapfunction(merge, '_checkunknownfile')
427 427 def overridecheckunknownfile(origfn, repo, wctx, mctx, f, f2=None):
428 428 if lfutil.standin(repo.dirstate.normalize(f)) in wctx:
429 429 return False
430 430 return origfn(repo, wctx, mctx, f, f2)
431 431
432 432 # The manifest merge handles conflicts on the manifest level. We want
433 433 # to handle changes in largefile-ness of files at this level too.
434 434 #
435 435 # The strategy is to run the original calculateupdates and then process
436 436 # the action list it outputs. There are two cases we need to deal with:
437 437 #
438 438 # 1. Normal file in p1, largefile in p2. Here the largefile is
439 439 # detected via its standin file, which will enter the working copy
440 440 # with a "get" action. It is not "merge" since the standin is all
441 441 # Mercurial is concerned with at this level -- the link to the
442 442 # existing normal file is not relevant here.
443 443 #
444 444 # 2. Largefile in p1, normal file in p2. Here we get a "merge" action
445 445 # since the largefile will be present in the working copy and
446 446 # different from the normal file in p2. Mercurial therefore
447 447 # triggers a merge action.
448 448 #
449 449 # In both cases, we prompt the user and emit new actions to either
450 450 # remove the standin (if the normal file was kept) or to remove the
451 451 # normal file and get the standin (if the largefile was kept). The
452 452 # default prompt answer is to use the largefile version since it was
453 453 # presumably changed on purpose.
454 454 #
455 455 # Finally, the merge.applyupdates function will then take care of
456 456 # writing the files into the working copy and lfcommands.updatelfiles
457 457 # will update the largefiles.
458 458 @eh.wrapfunction(merge, 'calculateupdates')
459 459 def overridecalculateupdates(origfn, repo, p1, p2, pas, branchmerge, force,
460 460 acceptremote, *args, **kwargs):
461 461 overwrite = force and not branchmerge
462 462 actions, diverge, renamedelete = origfn(
463 463 repo, p1, p2, pas, branchmerge, force, acceptremote, *args, **kwargs)
464 464
465 465 if overwrite:
466 466 return actions, diverge, renamedelete
467 467
468 468 # Convert to dictionary with filename as key and action as value.
469 469 lfiles = set()
470 470 for f in actions:
471 471 splitstandin = lfutil.splitstandin(f)
472 472 if splitstandin in p1:
473 473 lfiles.add(splitstandin)
474 474 elif lfutil.standin(f) in p1:
475 475 lfiles.add(f)
476 476
477 477 for lfile in sorted(lfiles):
478 478 standin = lfutil.standin(lfile)
479 479 (lm, largs, lmsg) = actions.get(lfile, (None, None, None))
480 480 (sm, sargs, smsg) = actions.get(standin, (None, None, None))
481 481 if sm in ('g', 'dc') and lm != 'r':
482 482 if sm == 'dc':
483 483 f1, f2, fa, move, anc = sargs
484 484 sargs = (p2[f2].flags(), False)
485 485 # Case 1: normal file in the working copy, largefile in
486 486 # the second parent
487 487 usermsg = _('remote turned local normal file %s into a largefile\n'
488 488 'use (l)argefile or keep (n)ormal file?'
489 489 '$$ &Largefile $$ &Normal file') % lfile
490 490 if repo.ui.promptchoice(usermsg, 0) == 0: # pick remote largefile
491 491 actions[lfile] = ('r', None, 'replaced by standin')
492 492 actions[standin] = ('g', sargs, 'replaces standin')
493 493 else: # keep local normal file
494 494 actions[lfile] = ('k', None, 'replaces standin')
495 495 if branchmerge:
496 496 actions[standin] = ('k', None, 'replaced by non-standin')
497 497 else:
498 498 actions[standin] = ('r', None, 'replaced by non-standin')
499 499 elif lm in ('g', 'dc') and sm != 'r':
500 500 if lm == 'dc':
501 501 f1, f2, fa, move, anc = largs
502 502 largs = (p2[f2].flags(), False)
503 503 # Case 2: largefile in the working copy, normal file in
504 504 # the second parent
505 505 usermsg = _('remote turned local largefile %s into a normal file\n'
506 506 'keep (l)argefile or use (n)ormal file?'
507 507 '$$ &Largefile $$ &Normal file') % lfile
508 508 if repo.ui.promptchoice(usermsg, 0) == 0: # keep local largefile
509 509 if branchmerge:
510 510 # largefile can be restored from standin safely
511 511 actions[lfile] = ('k', None, 'replaced by standin')
512 512 actions[standin] = ('k', None, 'replaces standin')
513 513 else:
514 514 # "lfile" should be marked as "removed" without
515 515 # removal of itself
516 516 actions[lfile] = ('lfmr', None,
517 517 'forget non-standin largefile')
518 518
519 519 # linear-merge should treat this largefile as 're-added'
520 520 actions[standin] = ('a', None, 'keep standin')
521 521 else: # pick remote normal file
522 522 actions[lfile] = ('g', largs, 'replaces standin')
523 523 actions[standin] = ('r', None, 'replaced by non-standin')
524 524
525 525 return actions, diverge, renamedelete
526 526
527 527 @eh.wrapfunction(merge, 'recordupdates')
528 528 def mergerecordupdates(orig, repo, actions, branchmerge):
529 529 if 'lfmr' in actions:
530 530 lfdirstate = lfutil.openlfdirstate(repo.ui, repo)
531 531 for lfile, args, msg in actions['lfmr']:
532 532 # this should be executed before 'orig', to execute 'remove'
533 533 # before all other actions
534 534 repo.dirstate.remove(lfile)
535 535 # make sure lfile doesn't get synclfdirstate'd as normal
536 536 lfdirstate.add(lfile)
537 537 lfdirstate.write()
538 538
539 539 return orig(repo, actions, branchmerge)
540 540
541 541 # Override filemerge to prompt the user about how they wish to merge
542 542 # largefiles. This will handle identical edits without prompting the user.
543 543 @eh.wrapfunction(filemerge, '_filemerge')
544 544 def overridefilemerge(origfn, premerge, repo, wctx, mynode, orig, fcd, fco, fca,
545 545 labels=None):
546 546 if not lfutil.isstandin(orig) or fcd.isabsent() or fco.isabsent():
547 547 return origfn(premerge, repo, wctx, mynode, orig, fcd, fco, fca,
548 548 labels=labels)
549 549
550 550 ahash = lfutil.readasstandin(fca).lower()
551 551 dhash = lfutil.readasstandin(fcd).lower()
552 552 ohash = lfutil.readasstandin(fco).lower()
553 553 if (ohash != ahash and
554 554 ohash != dhash and
555 555 (dhash == ahash or
556 556 repo.ui.promptchoice(
557 557 _('largefile %s has a merge conflict\nancestor was %s\n'
558 558 'keep (l)ocal %s or\ntake (o)ther %s?'
559 559 '$$ &Local $$ &Other') %
560 560 (lfutil.splitstandin(orig), ahash, dhash, ohash),
561 561 0) == 1)):
562 562 repo.wwrite(fcd.path(), fco.data(), fco.flags())
563 563 return True, 0, False
564 564
565 565 @eh.wrapfunction(copiesmod, 'pathcopies')
566 566 def copiespathcopies(orig, ctx1, ctx2, match=None):
567 567 copies = orig(ctx1, ctx2, match=match)
568 568 updated = {}
569 569
570 570 for k, v in copies.iteritems():
571 571 updated[lfutil.splitstandin(k) or k] = lfutil.splitstandin(v) or v
572 572
573 573 return updated
574 574
575 575 # Copy first changes the matchers to match standins instead of
576 576 # largefiles. Then it overrides util.copyfile in that function it
577 577 # checks if the destination largefile already exists. It also keeps a
578 578 # list of copied files so that the largefiles can be copied and the
579 579 # dirstate updated.
580 580 @eh.wrapfunction(cmdutil, 'copy')
581 581 def overridecopy(orig, ui, repo, pats, opts, rename=False):
582 582 # doesn't remove largefile on rename
583 583 if len(pats) < 2:
584 584 # this isn't legal, let the original function deal with it
585 585 return orig(ui, repo, pats, opts, rename)
586 586
587 587 # This could copy both lfiles and normal files in one command,
588 588 # but we don't want to do that. First replace their matcher to
589 589 # only match normal files and run it, then replace it to just
590 590 # match largefiles and run it again.
591 591 nonormalfiles = False
592 592 nolfiles = False
593 593 manifest = repo[None].manifest()
594 594 def normalfilesmatchfn(orig, ctx, pats=(), opts=None, globbed=False,
595 595 default='relpath', badfn=None):
596 596 if opts is None:
597 597 opts = {}
598 598 match = orig(ctx, pats, opts, globbed, default, badfn=badfn)
599 599 return composenormalfilematcher(match, manifest)
600 600 with extensions.wrappedfunction(scmutil, 'match', normalfilesmatchfn):
601 601 try:
602 602 result = orig(ui, repo, pats, opts, rename)
603 603 except error.Abort as e:
604 604 if pycompat.bytestr(e) != _('no files to copy'):
605 605 raise e
606 606 else:
607 607 nonormalfiles = True
608 608 result = 0
609 609
610 610 # The first rename can cause our current working directory to be removed.
611 611 # In that case there is nothing left to copy/rename so just quit.
612 612 try:
613 613 repo.getcwd()
614 614 except OSError:
615 615 return result
616 616
617 617 def makestandin(relpath):
618 618 path = pathutil.canonpath(repo.root, repo.getcwd(), relpath)
619 619 return repo.wvfs.join(lfutil.standin(path))
620 620
621 621 fullpats = scmutil.expandpats(pats)
622 622 dest = fullpats[-1]
623 623
624 624 if os.path.isdir(dest):
625 625 if not os.path.isdir(makestandin(dest)):
626 626 os.makedirs(makestandin(dest))
627 627
628 628 try:
629 629 # When we call orig below it creates the standins but we don't add
630 630 # them to the dir state until later so lock during that time.
631 631 wlock = repo.wlock()
632 632
633 633 manifest = repo[None].manifest()
634 634 def overridematch(orig, ctx, pats=(), opts=None, globbed=False,
635 635 default='relpath', badfn=None):
636 636 if opts is None:
637 637 opts = {}
638 638 newpats = []
639 639 # The patterns were previously mangled to add the standin
640 640 # directory; we need to remove that now
641 641 for pat in pats:
642 642 if matchmod.patkind(pat) is None and lfutil.shortname in pat:
643 643 newpats.append(pat.replace(lfutil.shortname, ''))
644 644 else:
645 645 newpats.append(pat)
646 646 match = orig(ctx, newpats, opts, globbed, default, badfn=badfn)
647 647 m = copy.copy(match)
648 648 lfile = lambda f: lfutil.standin(f) in manifest
649 649 m._files = [lfutil.standin(f) for f in m._files if lfile(f)]
650 650 m._fileset = set(m._files)
651 651 origmatchfn = m.matchfn
652 652 def matchfn(f):
653 653 lfile = lfutil.splitstandin(f)
654 654 return (lfile is not None and
655 655 (f in manifest) and
656 656 origmatchfn(lfile) or
657 657 None)
658 658 m.matchfn = matchfn
659 659 return m
660 660 listpats = []
661 661 for pat in pats:
662 662 if matchmod.patkind(pat) is not None:
663 663 listpats.append(pat)
664 664 else:
665 665 listpats.append(makestandin(pat))
666 666
667 667 copiedfiles = []
668 668 def overridecopyfile(orig, src, dest, *args, **kwargs):
669 669 if (lfutil.shortname in src and
670 670 dest.startswith(repo.wjoin(lfutil.shortname))):
671 671 destlfile = dest.replace(lfutil.shortname, '')
672 672 if not opts['force'] and os.path.exists(destlfile):
673 673 raise IOError('',
674 674 _('destination largefile already exists'))
675 675 copiedfiles.append((src, dest))
676 676 orig(src, dest, *args, **kwargs)
677 677 with extensions.wrappedfunction(util, 'copyfile', overridecopyfile), \
678 678 extensions.wrappedfunction(scmutil, 'match', overridematch):
679 679 result += orig(ui, repo, listpats, opts, rename)
680 680
681 681 lfdirstate = lfutil.openlfdirstate(ui, repo)
682 682 for (src, dest) in copiedfiles:
683 683 if (lfutil.shortname in src and
684 684 dest.startswith(repo.wjoin(lfutil.shortname))):
685 685 srclfile = src.replace(repo.wjoin(lfutil.standin('')), '')
686 686 destlfile = dest.replace(repo.wjoin(lfutil.standin('')), '')
687 687 destlfiledir = repo.wvfs.dirname(repo.wjoin(destlfile)) or '.'
688 688 if not os.path.isdir(destlfiledir):
689 689 os.makedirs(destlfiledir)
690 690 if rename:
691 691 os.rename(repo.wjoin(srclfile), repo.wjoin(destlfile))
692 692
693 693 # The file is gone, but this deletes any empty parent
694 694 # directories as a side-effect.
695 695 repo.wvfs.unlinkpath(srclfile, ignoremissing=True)
696 696 lfdirstate.remove(srclfile)
697 697 else:
698 698 util.copyfile(repo.wjoin(srclfile),
699 699 repo.wjoin(destlfile))
700 700
701 701 lfdirstate.add(destlfile)
702 702 lfdirstate.write()
703 703 except error.Abort as e:
704 704 if pycompat.bytestr(e) != _('no files to copy'):
705 705 raise e
706 706 else:
707 707 nolfiles = True
708 708 finally:
709 709 wlock.release()
710 710
711 711 if nolfiles and nonormalfiles:
712 712 raise error.Abort(_('no files to copy'))
713 713
714 714 return result
715 715
716 716 # When the user calls revert, we have to be careful to not revert any
717 717 # changes to other largefiles accidentally. This means we have to keep
718 718 # track of the largefiles that are being reverted so we only pull down
719 719 # the necessary largefiles.
720 720 #
721 721 # Standins are only updated (to match the hash of largefiles) before
722 722 # commits. Update the standins then run the original revert, changing
723 723 # the matcher to hit standins instead of largefiles. Based on the
724 724 # resulting standins update the largefiles.
725 725 @eh.wrapfunction(cmdutil, 'revert')
726 726 def overriderevert(orig, ui, repo, ctx, parents, *pats, **opts):
727 727 # Because we put the standins in a bad state (by updating them)
728 728 # and then return them to a correct state we need to lock to
729 729 # prevent others from changing them in their incorrect state.
730 730 with repo.wlock():
731 731 lfdirstate = lfutil.openlfdirstate(ui, repo)
732 732 s = lfutil.lfdirstatestatus(lfdirstate, repo)
733 733 lfdirstate.write()
734 734 for lfile in s.modified:
735 735 lfutil.updatestandin(repo, lfile, lfutil.standin(lfile))
736 736 for lfile in s.deleted:
737 737 fstandin = lfutil.standin(lfile)
738 738 if (repo.wvfs.exists(fstandin)):
739 739 repo.wvfs.unlink(fstandin)
740 740
741 741 oldstandins = lfutil.getstandinsstate(repo)
742 742
743 743 def overridematch(orig, mctx, pats=(), opts=None, globbed=False,
744 744 default='relpath', badfn=None):
745 745 if opts is None:
746 746 opts = {}
747 747 match = orig(mctx, pats, opts, globbed, default, badfn=badfn)
748 748 m = copy.copy(match)
749 749
750 750 # revert supports recursing into subrepos, and though largefiles
751 751 # currently doesn't work correctly in that case, this match is
752 752 # called, so the lfdirstate above may not be the correct one for
753 753 # this invocation of match.
754 754 lfdirstate = lfutil.openlfdirstate(mctx.repo().ui, mctx.repo(),
755 755 False)
756 756
757 757 wctx = repo[None]
758 758 matchfiles = []
759 759 for f in m._files:
760 760 standin = lfutil.standin(f)
761 761 if standin in ctx or standin in mctx:
762 762 matchfiles.append(standin)
763 763 elif standin in wctx or lfdirstate[f] == 'r':
764 764 continue
765 765 else:
766 766 matchfiles.append(f)
767 767 m._files = matchfiles
768 768 m._fileset = set(m._files)
769 769 origmatchfn = m.matchfn
770 770 def matchfn(f):
771 771 lfile = lfutil.splitstandin(f)
772 772 if lfile is not None:
773 773 return (origmatchfn(lfile) and
774 774 (f in ctx or f in mctx))
775 775 return origmatchfn(f)
776 776 m.matchfn = matchfn
777 777 return m
778 778 with extensions.wrappedfunction(scmutil, 'match', overridematch):
779 779 orig(ui, repo, ctx, parents, *pats, **opts)
780 780
781 781 newstandins = lfutil.getstandinsstate(repo)
782 782 filelist = lfutil.getlfilestoupdate(oldstandins, newstandins)
783 783 # lfdirstate should be 'normallookup'-ed for updated files,
784 784 # because reverting doesn't touch dirstate for 'normal' files
785 785 # when target revision is explicitly specified: in such case,
786 786 # 'n' and valid timestamp in dirstate doesn't ensure 'clean'
787 787 # of target (standin) file.
788 788 lfcommands.updatelfiles(ui, repo, filelist, printmessage=False,
789 789 normallookup=True)
790 790
791 791 # after pulling changesets, we need to take some extra care to get
792 792 # largefiles updated remotely
793 793 @eh.wrapcommand('pull',
794 794 opts=[('', 'all-largefiles', None,
795 795 _('download all pulled versions of largefiles (DEPRECATED)')),
796 796 ('', 'lfrev', [],
797 797 _('download largefiles for these revisions'), _('REV'))])
798 798 def overridepull(orig, ui, repo, source=None, **opts):
799 799 revsprepull = len(repo)
800 800 if not source:
801 801 source = 'default'
802 802 repo.lfpullsource = source
803 803 result = orig(ui, repo, source, **opts)
804 804 revspostpull = len(repo)
805 805 lfrevs = opts.get(r'lfrev', [])
806 806 if opts.get(r'all_largefiles'):
807 807 lfrevs.append('pulled()')
808 808 if lfrevs and revspostpull > revsprepull:
809 809 numcached = 0
810 810 repo.firstpulled = revsprepull # for pulled() revset expression
811 811 try:
812 812 for rev in scmutil.revrange(repo, lfrevs):
813 813 ui.note(_('pulling largefiles for revision %d\n') % rev)
814 814 (cached, missing) = lfcommands.cachelfiles(ui, repo, rev)
815 815 numcached += len(cached)
816 816 finally:
817 817 del repo.firstpulled
818 818 ui.status(_("%d largefiles cached\n") % numcached)
819 819 return result
820 820
821 821 @eh.wrapcommand('push',
822 822 opts=[('', 'lfrev', [],
823 823 _('upload largefiles for these revisions'), _('REV'))])
824 824 def overridepush(orig, ui, repo, *args, **kwargs):
825 825 """Override push command and store --lfrev parameters in opargs"""
826 826 lfrevs = kwargs.pop(r'lfrev', None)
827 827 if lfrevs:
828 828 opargs = kwargs.setdefault(r'opargs', {})
829 829 opargs['lfrevs'] = scmutil.revrange(repo, lfrevs)
830 830 return orig(ui, repo, *args, **kwargs)
831 831
832 832 @eh.wrapfunction(exchange, 'pushoperation')
833 833 def exchangepushoperation(orig, *args, **kwargs):
834 834 """Override pushoperation constructor and store lfrevs parameter"""
835 835 lfrevs = kwargs.pop(r'lfrevs', None)
836 836 pushop = orig(*args, **kwargs)
837 837 pushop.lfrevs = lfrevs
838 838 return pushop
839 839
840 840 @eh.revsetpredicate('pulled()')
841 841 def pulledrevsetsymbol(repo, subset, x):
842 842 """Changesets that just has been pulled.
843 843
844 844 Only available with largefiles from pull --lfrev expressions.
845 845
846 846 .. container:: verbose
847 847
848 848 Some examples:
849 849
850 850 - pull largefiles for all new changesets::
851 851
852 852 hg pull -lfrev "pulled()"
853 853
854 854 - pull largefiles for all new branch heads::
855 855
856 856 hg pull -lfrev "head(pulled()) and not closed()"
857 857
858 858 """
859 859
860 860 try:
861 861 firstpulled = repo.firstpulled
862 862 except AttributeError:
863 863 raise error.Abort(_("pulled() only available in --lfrev"))
864 864 return smartset.baseset([r for r in subset if r >= firstpulled])
865 865
866 866 @eh.wrapcommand('clone',
867 867 opts=[('', 'all-largefiles', None,
868 868 _('download all versions of all largefiles'))])
869 869 def overrideclone(orig, ui, source, dest=None, **opts):
870 870 d = dest
871 871 if d is None:
872 872 d = hg.defaultdest(source)
873 873 if opts.get(r'all_largefiles') and not hg.islocal(d):
874 874 raise error.Abort(_(
875 875 '--all-largefiles is incompatible with non-local destination %s') %
876 876 d)
877 877
878 878 return orig(ui, source, dest, **opts)
879 879
880 880 @eh.wrapfunction(hg, 'clone')
881 881 def hgclone(orig, ui, opts, *args, **kwargs):
882 882 result = orig(ui, opts, *args, **kwargs)
883 883
884 884 if result is not None:
885 885 sourcerepo, destrepo = result
886 886 repo = destrepo.local()
887 887
888 888 # When cloning to a remote repo (like through SSH), no repo is available
889 889 # from the peer. Therefore the largefiles can't be downloaded and the
890 890 # hgrc can't be updated.
891 891 if not repo:
892 892 return result
893 893
894 894 # Caching is implicitly limited to 'rev' option, since the dest repo was
895 895 # truncated at that point. The user may expect a download count with
896 896 # this option, so attempt whether or not this is a largefile repo.
897 897 if opts.get('all_largefiles'):
898 898 success, missing = lfcommands.downloadlfiles(ui, repo, None)
899 899
900 900 if missing != 0:
901 901 return None
902 902
903 903 return result
904 904
905 905 @eh.wrapcommand('rebase', extension='rebase')
906 906 def overriderebase(orig, ui, repo, **opts):
907 907 if not util.safehasattr(repo, '_largefilesenabled'):
908 908 return orig(ui, repo, **opts)
909 909
910 910 resuming = opts.get(r'continue')
911 911 repo._lfcommithooks.append(lfutil.automatedcommithook(resuming))
912 912 repo._lfstatuswriters.append(lambda *msg, **opts: None)
913 913 try:
914 914 return orig(ui, repo, **opts)
915 915 finally:
916 916 repo._lfstatuswriters.pop()
917 917 repo._lfcommithooks.pop()
918 918
919 919 @eh.wrapcommand('archive')
920 920 def overridearchivecmd(orig, ui, repo, dest, **opts):
921 921 repo.unfiltered().lfstatus = True
922 922
923 923 try:
924 924 return orig(ui, repo.unfiltered(), dest, **opts)
925 925 finally:
926 926 repo.unfiltered().lfstatus = False
927 927
928 928 @eh.wrapfunction(webcommands, 'archive')
929 929 def hgwebarchive(orig, web):
930 930 web.repo.lfstatus = True
931 931
932 932 try:
933 933 return orig(web)
934 934 finally:
935 935 web.repo.lfstatus = False
936 936
937 937 @eh.wrapfunction(archival, 'archive')
938 938 def overridearchive(orig, repo, dest, node, kind, decode=True, match=None,
939 939 prefix='', mtime=None, subrepos=None):
940 940 # For some reason setting repo.lfstatus in hgwebarchive only changes the
941 941 # unfiltered repo's attr, so check that as well.
942 942 if not repo.lfstatus and not repo.unfiltered().lfstatus:
943 943 return orig(repo, dest, node, kind, decode, match, prefix, mtime,
944 944 subrepos)
945 945
946 946 # No need to lock because we are only reading history and
947 947 # largefile caches, neither of which are modified.
948 948 if node is not None:
949 949 lfcommands.cachelfiles(repo.ui, repo, node)
950 950
951 951 if kind not in archival.archivers:
952 952 raise error.Abort(_("unknown archive type '%s'") % kind)
953 953
954 954 ctx = repo[node]
955 955
956 956 if kind == 'files':
957 957 if prefix:
958 958 raise error.Abort(
959 959 _('cannot give prefix when archiving to files'))
960 960 else:
961 961 prefix = archival.tidyprefix(dest, kind, prefix)
962 962
963 963 def write(name, mode, islink, getdata):
964 964 if match and not match(name):
965 965 return
966 966 data = getdata()
967 967 if decode:
968 968 data = repo.wwritedata(name, data)
969 969 archiver.addfile(prefix + name, mode, islink, data)
970 970
971 971 archiver = archival.archivers[kind](dest, mtime or ctx.date()[0])
972 972
973 973 if repo.ui.configbool("ui", "archivemeta"):
974 974 write('.hg_archival.txt', 0o644, False,
975 975 lambda: archival.buildmetadata(ctx))
976 976
977 977 for f in ctx:
978 978 ff = ctx.flags(f)
979 979 getdata = ctx[f].data
980 980 lfile = lfutil.splitstandin(f)
981 981 if lfile is not None:
982 982 if node is not None:
983 983 path = lfutil.findfile(repo, getdata().strip())
984 984
985 985 if path is None:
986 986 raise error.Abort(
987 987 _('largefile %s not found in repo store or system cache')
988 988 % lfile)
989 989 else:
990 990 path = lfile
991 991
992 992 f = lfile
993 993
994 994 getdata = lambda: util.readfile(path)
995 995 write(f, 'x' in ff and 0o755 or 0o644, 'l' in ff, getdata)
996 996
997 997 if subrepos:
998 998 for subpath in sorted(ctx.substate):
999 999 sub = ctx.workingsub(subpath)
1000 1000 submatch = matchmod.subdirmatcher(subpath, match)
1001 1001 subprefix = prefix + subpath + '/'
1002 1002 sub._repo.lfstatus = True
1003 1003 sub.archive(archiver, subprefix, submatch)
1004 1004
1005 1005 archiver.done()
1006 1006
1007 1007 @eh.wrapfunction(subrepo.hgsubrepo, 'archive')
1008 1008 def hgsubrepoarchive(orig, repo, archiver, prefix, match=None, decode=True):
1009 1009 lfenabled = util.safehasattr(repo._repo, '_largefilesenabled')
1010 1010 if not lfenabled or not repo._repo.lfstatus:
1011 1011 return orig(repo, archiver, prefix, match, decode)
1012 1012
1013 1013 repo._get(repo._state + ('hg',))
1014 1014 rev = repo._state[1]
1015 1015 ctx = repo._repo[rev]
1016 1016
1017 1017 if ctx.node() is not None:
1018 1018 lfcommands.cachelfiles(repo.ui, repo._repo, ctx.node())
1019 1019
1020 1020 def write(name, mode, islink, getdata):
1021 1021 # At this point, the standin has been replaced with the largefile name,
1022 1022 # so the normal matcher works here without the lfutil variants.
1023 1023 if match and not match(f):
1024 1024 return
1025 1025 data = getdata()
1026 1026 if decode:
1027 1027 data = repo._repo.wwritedata(name, data)
1028 1028
1029 1029 archiver.addfile(prefix + name, mode, islink, data)
1030 1030
1031 1031 for f in ctx:
1032 1032 ff = ctx.flags(f)
1033 1033 getdata = ctx[f].data
1034 1034 lfile = lfutil.splitstandin(f)
1035 1035 if lfile is not None:
1036 1036 if ctx.node() is not None:
1037 1037 path = lfutil.findfile(repo._repo, getdata().strip())
1038 1038
1039 1039 if path is None:
1040 1040 raise error.Abort(
1041 1041 _('largefile %s not found in repo store or system cache')
1042 1042 % lfile)
1043 1043 else:
1044 1044 path = lfile
1045 1045
1046 1046 f = lfile
1047 1047
1048 1048 getdata = lambda: util.readfile(os.path.join(prefix, path))
1049 1049
1050 1050 write(f, 'x' in ff and 0o755 or 0o644, 'l' in ff, getdata)
1051 1051
1052 1052 for subpath in sorted(ctx.substate):
1053 1053 sub = ctx.workingsub(subpath)
1054 1054 submatch = matchmod.subdirmatcher(subpath, match)
1055 1055 subprefix = prefix + subpath + '/'
1056 1056 sub._repo.lfstatus = True
1057 1057 sub.archive(archiver, subprefix, submatch, decode)
1058 1058
1059 1059 # If a largefile is modified, the change is not reflected in its
1060 1060 # standin until a commit. cmdutil.bailifchanged() raises an exception
1061 1061 # if the repo has uncommitted changes. Wrap it to also check if
1062 1062 # largefiles were changed. This is used by bisect, backout and fetch.
1063 1063 @eh.wrapfunction(cmdutil, 'bailifchanged')
1064 1064 def overridebailifchanged(orig, repo, *args, **kwargs):
1065 1065 orig(repo, *args, **kwargs)
1066 1066 repo.lfstatus = True
1067 1067 s = repo.status()
1068 1068 repo.lfstatus = False
1069 1069 if s.modified or s.added or s.removed or s.deleted:
1070 1070 raise error.Abort(_('uncommitted changes'))
1071 1071
1072 1072 @eh.wrapfunction(cmdutil, 'postcommitstatus')
1073 1073 def postcommitstatus(orig, repo, *args, **kwargs):
1074 1074 repo.lfstatus = True
1075 1075 try:
1076 1076 return orig(repo, *args, **kwargs)
1077 1077 finally:
1078 1078 repo.lfstatus = False
1079 1079
1080 1080 @eh.wrapfunction(cmdutil, 'forget')
1081 def cmdutilforget(orig, ui, repo, match, prefix, explicitonly, dryrun,
1081 def cmdutilforget(orig, ui, repo, match, prefix, uipathfn, explicitonly, dryrun,
1082 1082 interactive):
1083 1083 normalmatcher = composenormalfilematcher(match, repo[None].manifest())
1084 bad, forgot = orig(ui, repo, normalmatcher, prefix, explicitonly, dryrun,
1085 interactive)
1084 bad, forgot = orig(ui, repo, normalmatcher, prefix, uipathfn, explicitonly,
1085 dryrun, interactive)
1086 1086 m = composelargefilematcher(match, repo[None].manifest())
1087 1087
1088 1088 try:
1089 1089 repo.lfstatus = True
1090 1090 s = repo.status(match=m, clean=True)
1091 1091 finally:
1092 1092 repo.lfstatus = False
1093 1093 manifest = repo[None].manifest()
1094 1094 forget = sorted(s.modified + s.added + s.deleted + s.clean)
1095 1095 forget = [f for f in forget if lfutil.standin(f) in manifest]
1096 1096
1097 1097 for f in forget:
1098 1098 fstandin = lfutil.standin(f)
1099 1099 if fstandin not in repo.dirstate and not repo.wvfs.isdir(fstandin):
1100 1100 ui.warn(_('not removing %s: file is already untracked\n')
1101 % m.rel(f))
1101 % uipathfn(f))
1102 1102 bad.append(f)
1103 1103
1104 1104 for f in forget:
1105 1105 if ui.verbose or not m.exact(f):
1106 ui.status(_('removing %s\n') % m.rel(f))
1106 ui.status(_('removing %s\n') % uipathfn(f))
1107 1107
1108 1108 # Need to lock because standin files are deleted then removed from the
1109 1109 # repository and we could race in-between.
1110 1110 with repo.wlock():
1111 1111 lfdirstate = lfutil.openlfdirstate(ui, repo)
1112 1112 for f in forget:
1113 1113 if lfdirstate[f] == 'a':
1114 1114 lfdirstate.drop(f)
1115 1115 else:
1116 1116 lfdirstate.remove(f)
1117 1117 lfdirstate.write()
1118 1118 standins = [lfutil.standin(f) for f in forget]
1119 1119 for f in standins:
1120 1120 repo.wvfs.unlinkpath(f, ignoremissing=True)
1121 1121 rejected = repo[None].forget(standins)
1122 1122
1123 1123 bad.extend(f for f in rejected if f in m.files())
1124 1124 forgot.extend(f for f in forget if f not in rejected)
1125 1125 return bad, forgot
1126 1126
1127 1127 def _getoutgoings(repo, other, missing, addfunc):
1128 1128 """get pairs of filename and largefile hash in outgoing revisions
1129 1129 in 'missing'.
1130 1130
1131 1131 largefiles already existing on 'other' repository are ignored.
1132 1132
1133 1133 'addfunc' is invoked with each unique pairs of filename and
1134 1134 largefile hash value.
1135 1135 """
1136 1136 knowns = set()
1137 1137 lfhashes = set()
1138 1138 def dedup(fn, lfhash):
1139 1139 k = (fn, lfhash)
1140 1140 if k not in knowns:
1141 1141 knowns.add(k)
1142 1142 lfhashes.add(lfhash)
1143 1143 lfutil.getlfilestoupload(repo, missing, dedup)
1144 1144 if lfhashes:
1145 1145 lfexists = storefactory.openstore(repo, other).exists(lfhashes)
1146 1146 for fn, lfhash in knowns:
1147 1147 if not lfexists[lfhash]: # lfhash doesn't exist on "other"
1148 1148 addfunc(fn, lfhash)
1149 1149
1150 1150 def outgoinghook(ui, repo, other, opts, missing):
1151 1151 if opts.pop('large', None):
1152 1152 lfhashes = set()
1153 1153 if ui.debugflag:
1154 1154 toupload = {}
1155 1155 def addfunc(fn, lfhash):
1156 1156 if fn not in toupload:
1157 1157 toupload[fn] = []
1158 1158 toupload[fn].append(lfhash)
1159 1159 lfhashes.add(lfhash)
1160 1160 def showhashes(fn):
1161 1161 for lfhash in sorted(toupload[fn]):
1162 1162 ui.debug(' %s\n' % (lfhash))
1163 1163 else:
1164 1164 toupload = set()
1165 1165 def addfunc(fn, lfhash):
1166 1166 toupload.add(fn)
1167 1167 lfhashes.add(lfhash)
1168 1168 def showhashes(fn):
1169 1169 pass
1170 1170 _getoutgoings(repo, other, missing, addfunc)
1171 1171
1172 1172 if not toupload:
1173 1173 ui.status(_('largefiles: no files to upload\n'))
1174 1174 else:
1175 1175 ui.status(_('largefiles to upload (%d entities):\n')
1176 1176 % (len(lfhashes)))
1177 1177 for file in sorted(toupload):
1178 1178 ui.status(lfutil.splitstandin(file) + '\n')
1179 1179 showhashes(file)
1180 1180 ui.status('\n')
1181 1181
1182 1182 @eh.wrapcommand('outgoing',
1183 1183 opts=[('', 'large', None, _('display outgoing largefiles'))])
1184 1184 def _outgoingcmd(orig, *args, **kwargs):
1185 1185 # Nothing to do here other than add the extra help option- the hook above
1186 1186 # processes it.
1187 1187 return orig(*args, **kwargs)
1188 1188
1189 1189 def summaryremotehook(ui, repo, opts, changes):
1190 1190 largeopt = opts.get('large', False)
1191 1191 if changes is None:
1192 1192 if largeopt:
1193 1193 return (False, True) # only outgoing check is needed
1194 1194 else:
1195 1195 return (False, False)
1196 1196 elif largeopt:
1197 1197 url, branch, peer, outgoing = changes[1]
1198 1198 if peer is None:
1199 1199 # i18n: column positioning for "hg summary"
1200 1200 ui.status(_('largefiles: (no remote repo)\n'))
1201 1201 return
1202 1202
1203 1203 toupload = set()
1204 1204 lfhashes = set()
1205 1205 def addfunc(fn, lfhash):
1206 1206 toupload.add(fn)
1207 1207 lfhashes.add(lfhash)
1208 1208 _getoutgoings(repo, peer, outgoing.missing, addfunc)
1209 1209
1210 1210 if not toupload:
1211 1211 # i18n: column positioning for "hg summary"
1212 1212 ui.status(_('largefiles: (no files to upload)\n'))
1213 1213 else:
1214 1214 # i18n: column positioning for "hg summary"
1215 1215 ui.status(_('largefiles: %d entities for %d files to upload\n')
1216 1216 % (len(lfhashes), len(toupload)))
1217 1217
1218 1218 @eh.wrapcommand('summary',
1219 1219 opts=[('', 'large', None, _('display outgoing largefiles'))])
1220 1220 def overridesummary(orig, ui, repo, *pats, **opts):
1221 1221 try:
1222 1222 repo.lfstatus = True
1223 1223 orig(ui, repo, *pats, **opts)
1224 1224 finally:
1225 1225 repo.lfstatus = False
1226 1226
1227 1227 @eh.wrapfunction(scmutil, 'addremove')
1228 1228 def scmutiladdremove(orig, repo, matcher, prefix, uipathfn, opts=None):
1229 1229 if opts is None:
1230 1230 opts = {}
1231 1231 if not lfutil.islfilesrepo(repo):
1232 1232 return orig(repo, matcher, prefix, uipathfn, opts)
1233 1233 # Get the list of missing largefiles so we can remove them
1234 1234 lfdirstate = lfutil.openlfdirstate(repo.ui, repo)
1235 1235 unsure, s = lfdirstate.status(matchmod.always(repo.root, repo.getcwd()),
1236 1236 subrepos=[], ignored=False, clean=False,
1237 1237 unknown=False)
1238 1238
1239 1239 # Call into the normal remove code, but the removing of the standin, we want
1240 1240 # to have handled by original addremove. Monkey patching here makes sure
1241 1241 # we don't remove the standin in the largefiles code, preventing a very
1242 1242 # confused state later.
1243 1243 if s.deleted:
1244 1244 m = copy.copy(matcher)
1245 1245
1246 1246 # The m._files and m._map attributes are not changed to the deleted list
1247 1247 # because that affects the m.exact() test, which in turn governs whether
1248 1248 # or not the file name is printed, and how. Simply limit the original
1249 1249 # matches to those in the deleted status list.
1250 1250 matchfn = m.matchfn
1251 1251 m.matchfn = lambda f: f in s.deleted and matchfn(f)
1252 1252
1253 1253 removelargefiles(repo.ui, repo, True, m, opts.get('dry_run'),
1254 1254 **pycompat.strkwargs(opts))
1255 1255 # Call into the normal add code, and any files that *should* be added as
1256 1256 # largefiles will be
1257 1257 added, bad = addlargefiles(repo.ui, repo, True, matcher,
1258 1258 **pycompat.strkwargs(opts))
1259 1259 # Now that we've handled largefiles, hand off to the original addremove
1260 1260 # function to take care of the rest. Make sure it doesn't do anything with
1261 1261 # largefiles by passing a matcher that will ignore them.
1262 1262 matcher = composenormalfilematcher(matcher, repo[None].manifest(), added)
1263 1263 return orig(repo, matcher, prefix, uipathfn, opts)
1264 1264
1265 1265 # Calling purge with --all will cause the largefiles to be deleted.
1266 1266 # Override repo.status to prevent this from happening.
1267 1267 @eh.wrapcommand('purge', extension='purge')
1268 1268 def overridepurge(orig, ui, repo, *dirs, **opts):
1269 1269 # XXX Monkey patching a repoview will not work. The assigned attribute will
1270 1270 # be set on the unfiltered repo, but we will only lookup attributes in the
1271 1271 # unfiltered repo if the lookup in the repoview object itself fails. As the
1272 1272 # monkey patched method exists on the repoview class the lookup will not
1273 1273 # fail. As a result, the original version will shadow the monkey patched
1274 1274 # one, defeating the monkey patch.
1275 1275 #
1276 1276 # As a work around we use an unfiltered repo here. We should do something
1277 1277 # cleaner instead.
1278 1278 repo = repo.unfiltered()
1279 1279 oldstatus = repo.status
1280 1280 def overridestatus(node1='.', node2=None, match=None, ignored=False,
1281 1281 clean=False, unknown=False, listsubrepos=False):
1282 1282 r = oldstatus(node1, node2, match, ignored, clean, unknown,
1283 1283 listsubrepos)
1284 1284 lfdirstate = lfutil.openlfdirstate(ui, repo)
1285 1285 unknown = [f for f in r.unknown if lfdirstate[f] == '?']
1286 1286 ignored = [f for f in r.ignored if lfdirstate[f] == '?']
1287 1287 return scmutil.status(r.modified, r.added, r.removed, r.deleted,
1288 1288 unknown, ignored, r.clean)
1289 1289 repo.status = overridestatus
1290 1290 orig(ui, repo, *dirs, **opts)
1291 1291 repo.status = oldstatus
1292 1292
1293 1293 @eh.wrapcommand('rollback')
1294 1294 def overriderollback(orig, ui, repo, **opts):
1295 1295 with repo.wlock():
1296 1296 before = repo.dirstate.parents()
1297 1297 orphans = set(f for f in repo.dirstate
1298 1298 if lfutil.isstandin(f) and repo.dirstate[f] != 'r')
1299 1299 result = orig(ui, repo, **opts)
1300 1300 after = repo.dirstate.parents()
1301 1301 if before == after:
1302 1302 return result # no need to restore standins
1303 1303
1304 1304 pctx = repo['.']
1305 1305 for f in repo.dirstate:
1306 1306 if lfutil.isstandin(f):
1307 1307 orphans.discard(f)
1308 1308 if repo.dirstate[f] == 'r':
1309 1309 repo.wvfs.unlinkpath(f, ignoremissing=True)
1310 1310 elif f in pctx:
1311 1311 fctx = pctx[f]
1312 1312 repo.wwrite(f, fctx.data(), fctx.flags())
1313 1313 else:
1314 1314 # content of standin is not so important in 'a',
1315 1315 # 'm' or 'n' (coming from the 2nd parent) cases
1316 1316 lfutil.writestandin(repo, f, '', False)
1317 1317 for standin in orphans:
1318 1318 repo.wvfs.unlinkpath(standin, ignoremissing=True)
1319 1319
1320 1320 lfdirstate = lfutil.openlfdirstate(ui, repo)
1321 1321 orphans = set(lfdirstate)
1322 1322 lfiles = lfutil.listlfiles(repo)
1323 1323 for file in lfiles:
1324 1324 lfutil.synclfdirstate(repo, lfdirstate, file, True)
1325 1325 orphans.discard(file)
1326 1326 for lfile in orphans:
1327 1327 lfdirstate.drop(lfile)
1328 1328 lfdirstate.write()
1329 1329 return result
1330 1330
1331 1331 @eh.wrapcommand('transplant', extension='transplant')
1332 1332 def overridetransplant(orig, ui, repo, *revs, **opts):
1333 1333 resuming = opts.get(r'continue')
1334 1334 repo._lfcommithooks.append(lfutil.automatedcommithook(resuming))
1335 1335 repo._lfstatuswriters.append(lambda *msg, **opts: None)
1336 1336 try:
1337 1337 result = orig(ui, repo, *revs, **opts)
1338 1338 finally:
1339 1339 repo._lfstatuswriters.pop()
1340 1340 repo._lfcommithooks.pop()
1341 1341 return result
1342 1342
1343 1343 @eh.wrapcommand('cat')
1344 1344 def overridecat(orig, ui, repo, file1, *pats, **opts):
1345 1345 opts = pycompat.byteskwargs(opts)
1346 1346 ctx = scmutil.revsingle(repo, opts.get('rev'))
1347 1347 err = 1
1348 1348 notbad = set()
1349 1349 m = scmutil.match(ctx, (file1,) + pats, opts)
1350 1350 origmatchfn = m.matchfn
1351 1351 def lfmatchfn(f):
1352 1352 if origmatchfn(f):
1353 1353 return True
1354 1354 lf = lfutil.splitstandin(f)
1355 1355 if lf is None:
1356 1356 return False
1357 1357 notbad.add(lf)
1358 1358 return origmatchfn(lf)
1359 1359 m.matchfn = lfmatchfn
1360 1360 origbadfn = m.bad
1361 1361 def lfbadfn(f, msg):
1362 1362 if not f in notbad:
1363 1363 origbadfn(f, msg)
1364 1364 m.bad = lfbadfn
1365 1365
1366 1366 origvisitdirfn = m.visitdir
1367 1367 def lfvisitdirfn(dir):
1368 1368 if dir == lfutil.shortname:
1369 1369 return True
1370 1370 ret = origvisitdirfn(dir)
1371 1371 if ret:
1372 1372 return ret
1373 1373 lf = lfutil.splitstandin(dir)
1374 1374 if lf is None:
1375 1375 return False
1376 1376 return origvisitdirfn(lf)
1377 1377 m.visitdir = lfvisitdirfn
1378 1378
1379 1379 for f in ctx.walk(m):
1380 1380 with cmdutil.makefileobj(ctx, opts.get('output'), pathname=f) as fp:
1381 1381 lf = lfutil.splitstandin(f)
1382 1382 if lf is None or origmatchfn(f):
1383 1383 # duplicating unreachable code from commands.cat
1384 1384 data = ctx[f].data()
1385 1385 if opts.get('decode'):
1386 1386 data = repo.wwritedata(f, data)
1387 1387 fp.write(data)
1388 1388 else:
1389 1389 hash = lfutil.readasstandin(ctx[f])
1390 1390 if not lfutil.inusercache(repo.ui, hash):
1391 1391 store = storefactory.openstore(repo)
1392 1392 success, missing = store.get([(lf, hash)])
1393 1393 if len(success) != 1:
1394 1394 raise error.Abort(
1395 1395 _('largefile %s is not in cache and could not be '
1396 1396 'downloaded') % lf)
1397 1397 path = lfutil.usercachepath(repo.ui, hash)
1398 1398 with open(path, "rb") as fpin:
1399 1399 for chunk in util.filechunkiter(fpin):
1400 1400 fp.write(chunk)
1401 1401 err = 0
1402 1402 return err
1403 1403
1404 1404 @eh.wrapfunction(merge, 'update')
1405 1405 def mergeupdate(orig, repo, node, branchmerge, force,
1406 1406 *args, **kwargs):
1407 1407 matcher = kwargs.get(r'matcher', None)
1408 1408 # note if this is a partial update
1409 1409 partial = matcher and not matcher.always()
1410 1410 with repo.wlock():
1411 1411 # branch | | |
1412 1412 # merge | force | partial | action
1413 1413 # -------+-------+---------+--------------
1414 1414 # x | x | x | linear-merge
1415 1415 # o | x | x | branch-merge
1416 1416 # x | o | x | overwrite (as clean update)
1417 1417 # o | o | x | force-branch-merge (*1)
1418 1418 # x | x | o | (*)
1419 1419 # o | x | o | (*)
1420 1420 # x | o | o | overwrite (as revert)
1421 1421 # o | o | o | (*)
1422 1422 #
1423 1423 # (*) don't care
1424 1424 # (*1) deprecated, but used internally (e.g: "rebase --collapse")
1425 1425
1426 1426 lfdirstate = lfutil.openlfdirstate(repo.ui, repo)
1427 1427 unsure, s = lfdirstate.status(matchmod.always(repo.root,
1428 1428 repo.getcwd()),
1429 1429 subrepos=[], ignored=False,
1430 1430 clean=True, unknown=False)
1431 1431 oldclean = set(s.clean)
1432 1432 pctx = repo['.']
1433 1433 dctx = repo[node]
1434 1434 for lfile in unsure + s.modified:
1435 1435 lfileabs = repo.wvfs.join(lfile)
1436 1436 if not repo.wvfs.exists(lfileabs):
1437 1437 continue
1438 1438 lfhash = lfutil.hashfile(lfileabs)
1439 1439 standin = lfutil.standin(lfile)
1440 1440 lfutil.writestandin(repo, standin, lfhash,
1441 1441 lfutil.getexecutable(lfileabs))
1442 1442 if (standin in pctx and
1443 1443 lfhash == lfutil.readasstandin(pctx[standin])):
1444 1444 oldclean.add(lfile)
1445 1445 for lfile in s.added:
1446 1446 fstandin = lfutil.standin(lfile)
1447 1447 if fstandin not in dctx:
1448 1448 # in this case, content of standin file is meaningless
1449 1449 # (in dctx, lfile is unknown, or normal file)
1450 1450 continue
1451 1451 lfutil.updatestandin(repo, lfile, fstandin)
1452 1452 # mark all clean largefiles as dirty, just in case the update gets
1453 1453 # interrupted before largefiles and lfdirstate are synchronized
1454 1454 for lfile in oldclean:
1455 1455 lfdirstate.normallookup(lfile)
1456 1456 lfdirstate.write()
1457 1457
1458 1458 oldstandins = lfutil.getstandinsstate(repo)
1459 1459 # Make sure the merge runs on disk, not in-memory. largefiles is not a
1460 1460 # good candidate for in-memory merge (large files, custom dirstate,
1461 1461 # matcher usage).
1462 1462 kwargs[r'wc'] = repo[None]
1463 1463 result = orig(repo, node, branchmerge, force, *args, **kwargs)
1464 1464
1465 1465 newstandins = lfutil.getstandinsstate(repo)
1466 1466 filelist = lfutil.getlfilestoupdate(oldstandins, newstandins)
1467 1467
1468 1468 # to avoid leaving all largefiles as dirty and thus rehash them, mark
1469 1469 # all the ones that didn't change as clean
1470 1470 for lfile in oldclean.difference(filelist):
1471 1471 lfdirstate.normal(lfile)
1472 1472 lfdirstate.write()
1473 1473
1474 1474 if branchmerge or force or partial:
1475 1475 filelist.extend(s.deleted + s.removed)
1476 1476
1477 1477 lfcommands.updatelfiles(repo.ui, repo, filelist=filelist,
1478 1478 normallookup=partial)
1479 1479
1480 1480 return result
1481 1481
1482 1482 @eh.wrapfunction(scmutil, 'marktouched')
1483 1483 def scmutilmarktouched(orig, repo, files, *args, **kwargs):
1484 1484 result = orig(repo, files, *args, **kwargs)
1485 1485
1486 1486 filelist = []
1487 1487 for f in files:
1488 1488 lf = lfutil.splitstandin(f)
1489 1489 if lf is not None:
1490 1490 filelist.append(lf)
1491 1491 if filelist:
1492 1492 lfcommands.updatelfiles(repo.ui, repo, filelist=filelist,
1493 1493 printmessage=False, normallookup=True)
1494 1494
1495 1495 return result
1496 1496
1497 1497 @eh.wrapfunction(upgrade, 'preservedrequirements')
1498 1498 @eh.wrapfunction(upgrade, 'supporteddestrequirements')
1499 1499 def upgraderequirements(orig, repo):
1500 1500 reqs = orig(repo)
1501 1501 if 'largefiles' in repo.requirements:
1502 1502 reqs.add('largefiles')
1503 1503 return reqs
1504 1504
1505 1505 _lfscheme = 'largefile://'
1506 1506
1507 1507 @eh.wrapfunction(urlmod, 'open')
1508 1508 def openlargefile(orig, ui, url_, data=None):
1509 1509 if url_.startswith(_lfscheme):
1510 1510 if data:
1511 1511 msg = "cannot use data on a 'largefile://' url"
1512 1512 raise error.ProgrammingError(msg)
1513 1513 lfid = url_[len(_lfscheme):]
1514 1514 return storefactory.getlfile(ui, lfid)
1515 1515 else:
1516 1516 return orig(ui, url_, data=data)
@@ -1,3342 +1,3345 b''
1 1 # cmdutil.py - help for command processing in mercurial
2 2 #
3 3 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
4 4 #
5 5 # This software may be used and distributed according to the terms of the
6 6 # GNU General Public License version 2 or any later version.
7 7
8 8 from __future__ import absolute_import
9 9
10 10 import errno
11 11 import os
12 12 import re
13 13
14 14 from .i18n import _
15 15 from .node import (
16 16 hex,
17 17 nullid,
18 18 nullrev,
19 19 short,
20 20 )
21 21
22 22 from . import (
23 23 bookmarks,
24 24 changelog,
25 25 copies,
26 26 crecord as crecordmod,
27 27 dirstateguard,
28 28 encoding,
29 29 error,
30 30 formatter,
31 31 logcmdutil,
32 32 match as matchmod,
33 33 merge as mergemod,
34 34 mergeutil,
35 35 obsolete,
36 36 patch,
37 37 pathutil,
38 38 phases,
39 39 pycompat,
40 40 revlog,
41 41 rewriteutil,
42 42 scmutil,
43 43 smartset,
44 44 subrepoutil,
45 45 templatekw,
46 46 templater,
47 47 util,
48 48 vfs as vfsmod,
49 49 )
50 50
51 51 from .utils import (
52 52 dateutil,
53 53 stringutil,
54 54 )
55 55
56 56 stringio = util.stringio
57 57
58 58 # templates of common command options
59 59
60 60 dryrunopts = [
61 61 ('n', 'dry-run', None,
62 62 _('do not perform actions, just print output')),
63 63 ]
64 64
65 65 confirmopts = [
66 66 ('', 'confirm', None,
67 67 _('ask before applying actions')),
68 68 ]
69 69
70 70 remoteopts = [
71 71 ('e', 'ssh', '',
72 72 _('specify ssh command to use'), _('CMD')),
73 73 ('', 'remotecmd', '',
74 74 _('specify hg command to run on the remote side'), _('CMD')),
75 75 ('', 'insecure', None,
76 76 _('do not verify server certificate (ignoring web.cacerts config)')),
77 77 ]
78 78
79 79 walkopts = [
80 80 ('I', 'include', [],
81 81 _('include names matching the given patterns'), _('PATTERN')),
82 82 ('X', 'exclude', [],
83 83 _('exclude names matching the given patterns'), _('PATTERN')),
84 84 ]
85 85
86 86 commitopts = [
87 87 ('m', 'message', '',
88 88 _('use text as commit message'), _('TEXT')),
89 89 ('l', 'logfile', '',
90 90 _('read commit message from file'), _('FILE')),
91 91 ]
92 92
93 93 commitopts2 = [
94 94 ('d', 'date', '',
95 95 _('record the specified date as commit date'), _('DATE')),
96 96 ('u', 'user', '',
97 97 _('record the specified user as committer'), _('USER')),
98 98 ]
99 99
100 100 formatteropts = [
101 101 ('T', 'template', '',
102 102 _('display with template'), _('TEMPLATE')),
103 103 ]
104 104
105 105 templateopts = [
106 106 ('', 'style', '',
107 107 _('display using template map file (DEPRECATED)'), _('STYLE')),
108 108 ('T', 'template', '',
109 109 _('display with template'), _('TEMPLATE')),
110 110 ]
111 111
112 112 logopts = [
113 113 ('p', 'patch', None, _('show patch')),
114 114 ('g', 'git', None, _('use git extended diff format')),
115 115 ('l', 'limit', '',
116 116 _('limit number of changes displayed'), _('NUM')),
117 117 ('M', 'no-merges', None, _('do not show merges')),
118 118 ('', 'stat', None, _('output diffstat-style summary of changes')),
119 119 ('G', 'graph', None, _("show the revision DAG")),
120 120 ] + templateopts
121 121
122 122 diffopts = [
123 123 ('a', 'text', None, _('treat all files as text')),
124 124 ('g', 'git', None, _('use git extended diff format')),
125 125 ('', 'binary', None, _('generate binary diffs in git mode (default)')),
126 126 ('', 'nodates', None, _('omit dates from diff headers'))
127 127 ]
128 128
129 129 diffwsopts = [
130 130 ('w', 'ignore-all-space', None,
131 131 _('ignore white space when comparing lines')),
132 132 ('b', 'ignore-space-change', None,
133 133 _('ignore changes in the amount of white space')),
134 134 ('B', 'ignore-blank-lines', None,
135 135 _('ignore changes whose lines are all blank')),
136 136 ('Z', 'ignore-space-at-eol', None,
137 137 _('ignore changes in whitespace at EOL')),
138 138 ]
139 139
140 140 diffopts2 = [
141 141 ('', 'noprefix', None, _('omit a/ and b/ prefixes from filenames')),
142 142 ('p', 'show-function', None, _('show which function each change is in')),
143 143 ('', 'reverse', None, _('produce a diff that undoes the changes')),
144 144 ] + diffwsopts + [
145 145 ('U', 'unified', '',
146 146 _('number of lines of context to show'), _('NUM')),
147 147 ('', 'stat', None, _('output diffstat-style summary of changes')),
148 148 ('', 'root', '', _('produce diffs relative to subdirectory'), _('DIR')),
149 149 ]
150 150
151 151 mergetoolopts = [
152 152 ('t', 'tool', '', _('specify merge tool'), _('TOOL')),
153 153 ]
154 154
155 155 similarityopts = [
156 156 ('s', 'similarity', '',
157 157 _('guess renamed files by similarity (0<=s<=100)'), _('SIMILARITY'))
158 158 ]
159 159
160 160 subrepoopts = [
161 161 ('S', 'subrepos', None,
162 162 _('recurse into subrepositories'))
163 163 ]
164 164
165 165 debugrevlogopts = [
166 166 ('c', 'changelog', False, _('open changelog')),
167 167 ('m', 'manifest', False, _('open manifest')),
168 168 ('', 'dir', '', _('open directory manifest')),
169 169 ]
170 170
171 171 # special string such that everything below this line will be ingored in the
172 172 # editor text
173 173 _linebelow = "^HG: ------------------------ >8 ------------------------$"
174 174
175 175 def ishunk(x):
176 176 hunkclasses = (crecordmod.uihunk, patch.recordhunk)
177 177 return isinstance(x, hunkclasses)
178 178
179 179 def newandmodified(chunks, originalchunks):
180 180 newlyaddedandmodifiedfiles = set()
181 181 for chunk in chunks:
182 182 if ishunk(chunk) and chunk.header.isnewfile() and chunk not in \
183 183 originalchunks:
184 184 newlyaddedandmodifiedfiles.add(chunk.header.filename())
185 185 return newlyaddedandmodifiedfiles
186 186
187 187 def parsealiases(cmd):
188 188 return cmd.split("|")
189 189
190 190 def setupwrapcolorwrite(ui):
191 191 # wrap ui.write so diff output can be labeled/colorized
192 192 def wrapwrite(orig, *args, **kw):
193 193 label = kw.pop(r'label', '')
194 194 for chunk, l in patch.difflabel(lambda: args):
195 195 orig(chunk, label=label + l)
196 196
197 197 oldwrite = ui.write
198 198 def wrap(*args, **kwargs):
199 199 return wrapwrite(oldwrite, *args, **kwargs)
200 200 setattr(ui, 'write', wrap)
201 201 return oldwrite
202 202
203 203 def filterchunks(ui, originalhunks, usecurses, testfile, operation=None):
204 204 try:
205 205 if usecurses:
206 206 if testfile:
207 207 recordfn = crecordmod.testdecorator(
208 208 testfile, crecordmod.testchunkselector)
209 209 else:
210 210 recordfn = crecordmod.chunkselector
211 211
212 212 return crecordmod.filterpatch(ui, originalhunks, recordfn,
213 213 operation)
214 214 except crecordmod.fallbackerror as e:
215 215 ui.warn('%s\n' % e.message)
216 216 ui.warn(_('falling back to text mode\n'))
217 217
218 218 return patch.filterpatch(ui, originalhunks, operation)
219 219
220 220 def recordfilter(ui, originalhunks, operation=None):
221 221 """ Prompts the user to filter the originalhunks and return a list of
222 222 selected hunks.
223 223 *operation* is used for to build ui messages to indicate the user what
224 224 kind of filtering they are doing: reverting, committing, shelving, etc.
225 225 (see patch.filterpatch).
226 226 """
227 227 usecurses = crecordmod.checkcurses(ui)
228 228 testfile = ui.config('experimental', 'crecordtest')
229 229 oldwrite = setupwrapcolorwrite(ui)
230 230 try:
231 231 newchunks, newopts = filterchunks(ui, originalhunks, usecurses,
232 232 testfile, operation)
233 233 finally:
234 234 ui.write = oldwrite
235 235 return newchunks, newopts
236 236
237 237 def dorecord(ui, repo, commitfunc, cmdsuggest, backupall,
238 238 filterfn, *pats, **opts):
239 239 opts = pycompat.byteskwargs(opts)
240 240 if not ui.interactive():
241 241 if cmdsuggest:
242 242 msg = _('running non-interactively, use %s instead') % cmdsuggest
243 243 else:
244 244 msg = _('running non-interactively')
245 245 raise error.Abort(msg)
246 246
247 247 # make sure username is set before going interactive
248 248 if not opts.get('user'):
249 249 ui.username() # raise exception, username not provided
250 250
251 251 def recordfunc(ui, repo, message, match, opts):
252 252 """This is generic record driver.
253 253
254 254 Its job is to interactively filter local changes, and
255 255 accordingly prepare working directory into a state in which the
256 256 job can be delegated to a non-interactive commit command such as
257 257 'commit' or 'qrefresh'.
258 258
259 259 After the actual job is done by non-interactive command, the
260 260 working directory is restored to its original state.
261 261
262 262 In the end we'll record interesting changes, and everything else
263 263 will be left in place, so the user can continue working.
264 264 """
265 265
266 266 checkunfinished(repo, commit=True)
267 267 wctx = repo[None]
268 268 merge = len(wctx.parents()) > 1
269 269 if merge:
270 270 raise error.Abort(_('cannot partially commit a merge '
271 271 '(use "hg commit" instead)'))
272 272
273 273 def fail(f, msg):
274 274 raise error.Abort('%s: %s' % (f, msg))
275 275
276 276 force = opts.get('force')
277 277 if not force:
278 278 vdirs = []
279 279 match.explicitdir = vdirs.append
280 280 match.bad = fail
281 281
282 282 status = repo.status(match=match)
283 283 if not force:
284 284 repo.checkcommitpatterns(wctx, vdirs, match, status, fail)
285 285 diffopts = patch.difffeatureopts(ui, opts=opts, whitespace=True,
286 286 section='commands',
287 287 configprefix='commit.interactive.')
288 288 diffopts.nodates = True
289 289 diffopts.git = True
290 290 diffopts.showfunc = True
291 291 originaldiff = patch.diff(repo, changes=status, opts=diffopts)
292 292 originalchunks = patch.parsepatch(originaldiff)
293 293
294 294 # 1. filter patch, since we are intending to apply subset of it
295 295 try:
296 296 chunks, newopts = filterfn(ui, originalchunks)
297 297 except error.PatchError as err:
298 298 raise error.Abort(_('error parsing patch: %s') % err)
299 299 opts.update(newopts)
300 300
301 301 # We need to keep a backup of files that have been newly added and
302 302 # modified during the recording process because there is a previous
303 303 # version without the edit in the workdir
304 304 newlyaddedandmodifiedfiles = newandmodified(chunks, originalchunks)
305 305 contenders = set()
306 306 for h in chunks:
307 307 try:
308 308 contenders.update(set(h.files()))
309 309 except AttributeError:
310 310 pass
311 311
312 312 changed = status.modified + status.added + status.removed
313 313 newfiles = [f for f in changed if f in contenders]
314 314 if not newfiles:
315 315 ui.status(_('no changes to record\n'))
316 316 return 0
317 317
318 318 modified = set(status.modified)
319 319
320 320 # 2. backup changed files, so we can restore them in the end
321 321
322 322 if backupall:
323 323 tobackup = changed
324 324 else:
325 325 tobackup = [f for f in newfiles if f in modified or f in \
326 326 newlyaddedandmodifiedfiles]
327 327 backups = {}
328 328 if tobackup:
329 329 backupdir = repo.vfs.join('record-backups')
330 330 try:
331 331 os.mkdir(backupdir)
332 332 except OSError as err:
333 333 if err.errno != errno.EEXIST:
334 334 raise
335 335 try:
336 336 # backup continues
337 337 for f in tobackup:
338 338 fd, tmpname = pycompat.mkstemp(prefix=f.replace('/', '_') + '.',
339 339 dir=backupdir)
340 340 os.close(fd)
341 341 ui.debug('backup %r as %r\n' % (f, tmpname))
342 342 util.copyfile(repo.wjoin(f), tmpname, copystat=True)
343 343 backups[f] = tmpname
344 344
345 345 fp = stringio()
346 346 for c in chunks:
347 347 fname = c.filename()
348 348 if fname in backups:
349 349 c.write(fp)
350 350 dopatch = fp.tell()
351 351 fp.seek(0)
352 352
353 353 # 2.5 optionally review / modify patch in text editor
354 354 if opts.get('review', False):
355 355 patchtext = (crecordmod.diffhelptext
356 356 + crecordmod.patchhelptext
357 357 + fp.read())
358 358 reviewedpatch = ui.edit(patchtext, "",
359 359 action="diff",
360 360 repopath=repo.path)
361 361 fp.truncate(0)
362 362 fp.write(reviewedpatch)
363 363 fp.seek(0)
364 364
365 365 [os.unlink(repo.wjoin(c)) for c in newlyaddedandmodifiedfiles]
366 366 # 3a. apply filtered patch to clean repo (clean)
367 367 if backups:
368 368 # Equivalent to hg.revert
369 369 m = scmutil.matchfiles(repo, backups.keys())
370 370 mergemod.update(repo, repo.dirstate.p1(), branchmerge=False,
371 371 force=True, matcher=m)
372 372
373 373 # 3b. (apply)
374 374 if dopatch:
375 375 try:
376 376 ui.debug('applying patch\n')
377 377 ui.debug(fp.getvalue())
378 378 patch.internalpatch(ui, repo, fp, 1, eolmode=None)
379 379 except error.PatchError as err:
380 380 raise error.Abort(pycompat.bytestr(err))
381 381 del fp
382 382
383 383 # 4. We prepared working directory according to filtered
384 384 # patch. Now is the time to delegate the job to
385 385 # commit/qrefresh or the like!
386 386
387 387 # Make all of the pathnames absolute.
388 388 newfiles = [repo.wjoin(nf) for nf in newfiles]
389 389 return commitfunc(ui, repo, *newfiles, **pycompat.strkwargs(opts))
390 390 finally:
391 391 # 5. finally restore backed-up files
392 392 try:
393 393 dirstate = repo.dirstate
394 394 for realname, tmpname in backups.iteritems():
395 395 ui.debug('restoring %r to %r\n' % (tmpname, realname))
396 396
397 397 if dirstate[realname] == 'n':
398 398 # without normallookup, restoring timestamp
399 399 # may cause partially committed files
400 400 # to be treated as unmodified
401 401 dirstate.normallookup(realname)
402 402
403 403 # copystat=True here and above are a hack to trick any
404 404 # editors that have f open that we haven't modified them.
405 405 #
406 406 # Also note that this racy as an editor could notice the
407 407 # file's mtime before we've finished writing it.
408 408 util.copyfile(tmpname, repo.wjoin(realname), copystat=True)
409 409 os.unlink(tmpname)
410 410 if tobackup:
411 411 os.rmdir(backupdir)
412 412 except OSError:
413 413 pass
414 414
415 415 def recordinwlock(ui, repo, message, match, opts):
416 416 with repo.wlock():
417 417 return recordfunc(ui, repo, message, match, opts)
418 418
419 419 return commit(ui, repo, recordinwlock, pats, opts)
420 420
421 421 class dirnode(object):
422 422 """
423 423 Represent a directory in user working copy with information required for
424 424 the purpose of tersing its status.
425 425
426 426 path is the path to the directory, without a trailing '/'
427 427
428 428 statuses is a set of statuses of all files in this directory (this includes
429 429 all the files in all the subdirectories too)
430 430
431 431 files is a list of files which are direct child of this directory
432 432
433 433 subdirs is a dictionary of sub-directory name as the key and it's own
434 434 dirnode object as the value
435 435 """
436 436
437 437 def __init__(self, dirpath):
438 438 self.path = dirpath
439 439 self.statuses = set([])
440 440 self.files = []
441 441 self.subdirs = {}
442 442
443 443 def _addfileindir(self, filename, status):
444 444 """Add a file in this directory as a direct child."""
445 445 self.files.append((filename, status))
446 446
447 447 def addfile(self, filename, status):
448 448 """
449 449 Add a file to this directory or to its direct parent directory.
450 450
451 451 If the file is not direct child of this directory, we traverse to the
452 452 directory of which this file is a direct child of and add the file
453 453 there.
454 454 """
455 455
456 456 # the filename contains a path separator, it means it's not the direct
457 457 # child of this directory
458 458 if '/' in filename:
459 459 subdir, filep = filename.split('/', 1)
460 460
461 461 # does the dirnode object for subdir exists
462 462 if subdir not in self.subdirs:
463 463 subdirpath = pathutil.join(self.path, subdir)
464 464 self.subdirs[subdir] = dirnode(subdirpath)
465 465
466 466 # try adding the file in subdir
467 467 self.subdirs[subdir].addfile(filep, status)
468 468
469 469 else:
470 470 self._addfileindir(filename, status)
471 471
472 472 if status not in self.statuses:
473 473 self.statuses.add(status)
474 474
475 475 def iterfilepaths(self):
476 476 """Yield (status, path) for files directly under this directory."""
477 477 for f, st in self.files:
478 478 yield st, pathutil.join(self.path, f)
479 479
480 480 def tersewalk(self, terseargs):
481 481 """
482 482 Yield (status, path) obtained by processing the status of this
483 483 dirnode.
484 484
485 485 terseargs is the string of arguments passed by the user with `--terse`
486 486 flag.
487 487
488 488 Following are the cases which can happen:
489 489
490 490 1) All the files in the directory (including all the files in its
491 491 subdirectories) share the same status and the user has asked us to terse
492 492 that status. -> yield (status, dirpath). dirpath will end in '/'.
493 493
494 494 2) Otherwise, we do following:
495 495
496 496 a) Yield (status, filepath) for all the files which are in this
497 497 directory (only the ones in this directory, not the subdirs)
498 498
499 499 b) Recurse the function on all the subdirectories of this
500 500 directory
501 501 """
502 502
503 503 if len(self.statuses) == 1:
504 504 onlyst = self.statuses.pop()
505 505
506 506 # Making sure we terse only when the status abbreviation is
507 507 # passed as terse argument
508 508 if onlyst in terseargs:
509 509 yield onlyst, self.path + '/'
510 510 return
511 511
512 512 # add the files to status list
513 513 for st, fpath in self.iterfilepaths():
514 514 yield st, fpath
515 515
516 516 #recurse on the subdirs
517 517 for dirobj in self.subdirs.values():
518 518 for st, fpath in dirobj.tersewalk(terseargs):
519 519 yield st, fpath
520 520
521 521 def tersedir(statuslist, terseargs):
522 522 """
523 523 Terse the status if all the files in a directory shares the same status.
524 524
525 525 statuslist is scmutil.status() object which contains a list of files for
526 526 each status.
527 527 terseargs is string which is passed by the user as the argument to `--terse`
528 528 flag.
529 529
530 530 The function makes a tree of objects of dirnode class, and at each node it
531 531 stores the information required to know whether we can terse a certain
532 532 directory or not.
533 533 """
534 534 # the order matters here as that is used to produce final list
535 535 allst = ('m', 'a', 'r', 'd', 'u', 'i', 'c')
536 536
537 537 # checking the argument validity
538 538 for s in pycompat.bytestr(terseargs):
539 539 if s not in allst:
540 540 raise error.Abort(_("'%s' not recognized") % s)
541 541
542 542 # creating a dirnode object for the root of the repo
543 543 rootobj = dirnode('')
544 544 pstatus = ('modified', 'added', 'deleted', 'clean', 'unknown',
545 545 'ignored', 'removed')
546 546
547 547 tersedict = {}
548 548 for attrname in pstatus:
549 549 statuschar = attrname[0:1]
550 550 for f in getattr(statuslist, attrname):
551 551 rootobj.addfile(f, statuschar)
552 552 tersedict[statuschar] = []
553 553
554 554 # we won't be tersing the root dir, so add files in it
555 555 for st, fpath in rootobj.iterfilepaths():
556 556 tersedict[st].append(fpath)
557 557
558 558 # process each sub-directory and build tersedict
559 559 for subdir in rootobj.subdirs.values():
560 560 for st, f in subdir.tersewalk(terseargs):
561 561 tersedict[st].append(f)
562 562
563 563 tersedlist = []
564 564 for st in allst:
565 565 tersedict[st].sort()
566 566 tersedlist.append(tersedict[st])
567 567
568 568 return tersedlist
569 569
570 570 def _commentlines(raw):
571 571 '''Surround lineswith a comment char and a new line'''
572 572 lines = raw.splitlines()
573 573 commentedlines = ['# %s' % line for line in lines]
574 574 return '\n'.join(commentedlines) + '\n'
575 575
576 576 def _conflictsmsg(repo):
577 577 mergestate = mergemod.mergestate.read(repo)
578 578 if not mergestate.active():
579 579 return
580 580
581 581 m = scmutil.match(repo[None])
582 582 unresolvedlist = [f for f in mergestate.unresolved() if m(f)]
583 583 if unresolvedlist:
584 584 mergeliststr = '\n'.join(
585 585 [' %s' % util.pathto(repo.root, encoding.getcwd(), path)
586 586 for path in sorted(unresolvedlist)])
587 587 msg = _('''Unresolved merge conflicts:
588 588
589 589 %s
590 590
591 591 To mark files as resolved: hg resolve --mark FILE''') % mergeliststr
592 592 else:
593 593 msg = _('No unresolved merge conflicts.')
594 594
595 595 return _commentlines(msg)
596 596
597 597 def _helpmessage(continuecmd, abortcmd):
598 598 msg = _('To continue: %s\n'
599 599 'To abort: %s') % (continuecmd, abortcmd)
600 600 return _commentlines(msg)
601 601
602 602 def _rebasemsg():
603 603 return _helpmessage('hg rebase --continue', 'hg rebase --abort')
604 604
605 605 def _histeditmsg():
606 606 return _helpmessage('hg histedit --continue', 'hg histedit --abort')
607 607
608 608 def _unshelvemsg():
609 609 return _helpmessage('hg unshelve --continue', 'hg unshelve --abort')
610 610
611 611 def _graftmsg():
612 612 return _helpmessage('hg graft --continue', 'hg graft --abort')
613 613
614 614 def _mergemsg():
615 615 return _helpmessage('hg commit', 'hg merge --abort')
616 616
617 617 def _bisectmsg():
618 618 msg = _('To mark the changeset good: hg bisect --good\n'
619 619 'To mark the changeset bad: hg bisect --bad\n'
620 620 'To abort: hg bisect --reset\n')
621 621 return _commentlines(msg)
622 622
623 623 def fileexistspredicate(filename):
624 624 return lambda repo: repo.vfs.exists(filename)
625 625
626 626 def _mergepredicate(repo):
627 627 return len(repo[None].parents()) > 1
628 628
629 629 STATES = (
630 630 # (state, predicate to detect states, helpful message function)
631 631 ('histedit', fileexistspredicate('histedit-state'), _histeditmsg),
632 632 ('bisect', fileexistspredicate('bisect.state'), _bisectmsg),
633 633 ('graft', fileexistspredicate('graftstate'), _graftmsg),
634 634 ('unshelve', fileexistspredicate('shelvedstate'), _unshelvemsg),
635 635 ('rebase', fileexistspredicate('rebasestate'), _rebasemsg),
636 636 # The merge state is part of a list that will be iterated over.
637 637 # They need to be last because some of the other unfinished states may also
638 638 # be in a merge or update state (eg. rebase, histedit, graft, etc).
639 639 # We want those to have priority.
640 640 ('merge', _mergepredicate, _mergemsg),
641 641 )
642 642
643 643 def _getrepostate(repo):
644 644 # experimental config: commands.status.skipstates
645 645 skip = set(repo.ui.configlist('commands', 'status.skipstates'))
646 646 for state, statedetectionpredicate, msgfn in STATES:
647 647 if state in skip:
648 648 continue
649 649 if statedetectionpredicate(repo):
650 650 return (state, statedetectionpredicate, msgfn)
651 651
652 652 def morestatus(repo, fm):
653 653 statetuple = _getrepostate(repo)
654 654 label = 'status.morestatus'
655 655 if statetuple:
656 656 state, statedetectionpredicate, helpfulmsg = statetuple
657 657 statemsg = _('The repository is in an unfinished *%s* state.') % state
658 658 fm.plain('%s\n' % _commentlines(statemsg), label=label)
659 659 conmsg = _conflictsmsg(repo)
660 660 if conmsg:
661 661 fm.plain('%s\n' % conmsg, label=label)
662 662 if helpfulmsg:
663 663 helpmsg = helpfulmsg()
664 664 fm.plain('%s\n' % helpmsg, label=label)
665 665
666 666 def findpossible(cmd, table, strict=False):
667 667 """
668 668 Return cmd -> (aliases, command table entry)
669 669 for each matching command.
670 670 Return debug commands (or their aliases) only if no normal command matches.
671 671 """
672 672 choice = {}
673 673 debugchoice = {}
674 674
675 675 if cmd in table:
676 676 # short-circuit exact matches, "log" alias beats "log|history"
677 677 keys = [cmd]
678 678 else:
679 679 keys = table.keys()
680 680
681 681 allcmds = []
682 682 for e in keys:
683 683 aliases = parsealiases(e)
684 684 allcmds.extend(aliases)
685 685 found = None
686 686 if cmd in aliases:
687 687 found = cmd
688 688 elif not strict:
689 689 for a in aliases:
690 690 if a.startswith(cmd):
691 691 found = a
692 692 break
693 693 if found is not None:
694 694 if aliases[0].startswith("debug") or found.startswith("debug"):
695 695 debugchoice[found] = (aliases, table[e])
696 696 else:
697 697 choice[found] = (aliases, table[e])
698 698
699 699 if not choice and debugchoice:
700 700 choice = debugchoice
701 701
702 702 return choice, allcmds
703 703
704 704 def findcmd(cmd, table, strict=True):
705 705 """Return (aliases, command table entry) for command string."""
706 706 choice, allcmds = findpossible(cmd, table, strict)
707 707
708 708 if cmd in choice:
709 709 return choice[cmd]
710 710
711 711 if len(choice) > 1:
712 712 clist = sorted(choice)
713 713 raise error.AmbiguousCommand(cmd, clist)
714 714
715 715 if choice:
716 716 return list(choice.values())[0]
717 717
718 718 raise error.UnknownCommand(cmd, allcmds)
719 719
720 720 def changebranch(ui, repo, revs, label):
721 721 """ Change the branch name of given revs to label """
722 722
723 723 with repo.wlock(), repo.lock(), repo.transaction('branches'):
724 724 # abort in case of uncommitted merge or dirty wdir
725 725 bailifchanged(repo)
726 726 revs = scmutil.revrange(repo, revs)
727 727 if not revs:
728 728 raise error.Abort("empty revision set")
729 729 roots = repo.revs('roots(%ld)', revs)
730 730 if len(roots) > 1:
731 731 raise error.Abort(_("cannot change branch of non-linear revisions"))
732 732 rewriteutil.precheck(repo, revs, 'change branch of')
733 733
734 734 root = repo[roots.first()]
735 735 rpb = {parent.branch() for parent in root.parents()}
736 736 if label not in rpb and label in repo.branchmap():
737 737 raise error.Abort(_("a branch of the same name already exists"))
738 738
739 739 if repo.revs('obsolete() and %ld', revs):
740 740 raise error.Abort(_("cannot change branch of a obsolete changeset"))
741 741
742 742 # make sure only topological heads
743 743 if repo.revs('heads(%ld) - head()', revs):
744 744 raise error.Abort(_("cannot change branch in middle of a stack"))
745 745
746 746 replacements = {}
747 747 # avoid import cycle mercurial.cmdutil -> mercurial.context ->
748 748 # mercurial.subrepo -> mercurial.cmdutil
749 749 from . import context
750 750 for rev in revs:
751 751 ctx = repo[rev]
752 752 oldbranch = ctx.branch()
753 753 # check if ctx has same branch
754 754 if oldbranch == label:
755 755 continue
756 756
757 757 def filectxfn(repo, newctx, path):
758 758 try:
759 759 return ctx[path]
760 760 except error.ManifestLookupError:
761 761 return None
762 762
763 763 ui.debug("changing branch of '%s' from '%s' to '%s'\n"
764 764 % (hex(ctx.node()), oldbranch, label))
765 765 extra = ctx.extra()
766 766 extra['branch_change'] = hex(ctx.node())
767 767 # While changing branch of set of linear commits, make sure that
768 768 # we base our commits on new parent rather than old parent which
769 769 # was obsoleted while changing the branch
770 770 p1 = ctx.p1().node()
771 771 p2 = ctx.p2().node()
772 772 if p1 in replacements:
773 773 p1 = replacements[p1][0]
774 774 if p2 in replacements:
775 775 p2 = replacements[p2][0]
776 776
777 777 mc = context.memctx(repo, (p1, p2),
778 778 ctx.description(),
779 779 ctx.files(),
780 780 filectxfn,
781 781 user=ctx.user(),
782 782 date=ctx.date(),
783 783 extra=extra,
784 784 branch=label)
785 785
786 786 newnode = repo.commitctx(mc)
787 787 replacements[ctx.node()] = (newnode,)
788 788 ui.debug('new node id is %s\n' % hex(newnode))
789 789
790 790 # create obsmarkers and move bookmarks
791 791 scmutil.cleanupnodes(repo, replacements, 'branch-change', fixphase=True)
792 792
793 793 # move the working copy too
794 794 wctx = repo[None]
795 795 # in-progress merge is a bit too complex for now.
796 796 if len(wctx.parents()) == 1:
797 797 newid = replacements.get(wctx.p1().node())
798 798 if newid is not None:
799 799 # avoid import cycle mercurial.cmdutil -> mercurial.hg ->
800 800 # mercurial.cmdutil
801 801 from . import hg
802 802 hg.update(repo, newid[0], quietempty=True)
803 803
804 804 ui.status(_("changed branch on %d changesets\n") % len(replacements))
805 805
806 806 def findrepo(p):
807 807 while not os.path.isdir(os.path.join(p, ".hg")):
808 808 oldp, p = p, os.path.dirname(p)
809 809 if p == oldp:
810 810 return None
811 811
812 812 return p
813 813
814 814 def bailifchanged(repo, merge=True, hint=None):
815 815 """ enforce the precondition that working directory must be clean.
816 816
817 817 'merge' can be set to false if a pending uncommitted merge should be
818 818 ignored (such as when 'update --check' runs).
819 819
820 820 'hint' is the usual hint given to Abort exception.
821 821 """
822 822
823 823 if merge and repo.dirstate.p2() != nullid:
824 824 raise error.Abort(_('outstanding uncommitted merge'), hint=hint)
825 825 modified, added, removed, deleted = repo.status()[:4]
826 826 if modified or added or removed or deleted:
827 827 raise error.Abort(_('uncommitted changes'), hint=hint)
828 828 ctx = repo[None]
829 829 for s in sorted(ctx.substate):
830 830 ctx.sub(s).bailifchanged(hint=hint)
831 831
832 832 def logmessage(ui, opts):
833 833 """ get the log message according to -m and -l option """
834 834 message = opts.get('message')
835 835 logfile = opts.get('logfile')
836 836
837 837 if message and logfile:
838 838 raise error.Abort(_('options --message and --logfile are mutually '
839 839 'exclusive'))
840 840 if not message and logfile:
841 841 try:
842 842 if isstdiofilename(logfile):
843 843 message = ui.fin.read()
844 844 else:
845 845 message = '\n'.join(util.readfile(logfile).splitlines())
846 846 except IOError as inst:
847 847 raise error.Abort(_("can't read commit message '%s': %s") %
848 848 (logfile, encoding.strtolocal(inst.strerror)))
849 849 return message
850 850
851 851 def mergeeditform(ctxorbool, baseformname):
852 852 """return appropriate editform name (referencing a committemplate)
853 853
854 854 'ctxorbool' is either a ctx to be committed, or a bool indicating whether
855 855 merging is committed.
856 856
857 857 This returns baseformname with '.merge' appended if it is a merge,
858 858 otherwise '.normal' is appended.
859 859 """
860 860 if isinstance(ctxorbool, bool):
861 861 if ctxorbool:
862 862 return baseformname + ".merge"
863 863 elif len(ctxorbool.parents()) > 1:
864 864 return baseformname + ".merge"
865 865
866 866 return baseformname + ".normal"
867 867
868 868 def getcommiteditor(edit=False, finishdesc=None, extramsg=None,
869 869 editform='', **opts):
870 870 """get appropriate commit message editor according to '--edit' option
871 871
872 872 'finishdesc' is a function to be called with edited commit message
873 873 (= 'description' of the new changeset) just after editing, but
874 874 before checking empty-ness. It should return actual text to be
875 875 stored into history. This allows to change description before
876 876 storing.
877 877
878 878 'extramsg' is a extra message to be shown in the editor instead of
879 879 'Leave message empty to abort commit' line. 'HG: ' prefix and EOL
880 880 is automatically added.
881 881
882 882 'editform' is a dot-separated list of names, to distinguish
883 883 the purpose of commit text editing.
884 884
885 885 'getcommiteditor' returns 'commitforceeditor' regardless of
886 886 'edit', if one of 'finishdesc' or 'extramsg' is specified, because
887 887 they are specific for usage in MQ.
888 888 """
889 889 if edit or finishdesc or extramsg:
890 890 return lambda r, c, s: commitforceeditor(r, c, s,
891 891 finishdesc=finishdesc,
892 892 extramsg=extramsg,
893 893 editform=editform)
894 894 elif editform:
895 895 return lambda r, c, s: commiteditor(r, c, s, editform=editform)
896 896 else:
897 897 return commiteditor
898 898
899 899 def _escapecommandtemplate(tmpl):
900 900 parts = []
901 901 for typ, start, end in templater.scantemplate(tmpl, raw=True):
902 902 if typ == b'string':
903 903 parts.append(stringutil.escapestr(tmpl[start:end]))
904 904 else:
905 905 parts.append(tmpl[start:end])
906 906 return b''.join(parts)
907 907
908 908 def rendercommandtemplate(ui, tmpl, props):
909 909 r"""Expand a literal template 'tmpl' in a way suitable for command line
910 910
911 911 '\' in outermost string is not taken as an escape character because it
912 912 is a directory separator on Windows.
913 913
914 914 >>> from . import ui as uimod
915 915 >>> ui = uimod.ui()
916 916 >>> rendercommandtemplate(ui, b'c:\\{path}', {b'path': b'foo'})
917 917 'c:\\foo'
918 918 >>> rendercommandtemplate(ui, b'{"c:\\{path}"}', {'path': b'foo'})
919 919 'c:{path}'
920 920 """
921 921 if not tmpl:
922 922 return tmpl
923 923 t = formatter.maketemplater(ui, _escapecommandtemplate(tmpl))
924 924 return t.renderdefault(props)
925 925
926 926 def rendertemplate(ctx, tmpl, props=None):
927 927 """Expand a literal template 'tmpl' byte-string against one changeset
928 928
929 929 Each props item must be a stringify-able value or a callable returning
930 930 such value, i.e. no bare list nor dict should be passed.
931 931 """
932 932 repo = ctx.repo()
933 933 tres = formatter.templateresources(repo.ui, repo)
934 934 t = formatter.maketemplater(repo.ui, tmpl, defaults=templatekw.keywords,
935 935 resources=tres)
936 936 mapping = {'ctx': ctx}
937 937 if props:
938 938 mapping.update(props)
939 939 return t.renderdefault(mapping)
940 940
941 941 def _buildfntemplate(pat, total=None, seqno=None, revwidth=None, pathname=None):
942 942 r"""Convert old-style filename format string to template string
943 943
944 944 >>> _buildfntemplate(b'foo-%b-%n.patch', seqno=0)
945 945 'foo-{reporoot|basename}-{seqno}.patch'
946 946 >>> _buildfntemplate(b'%R{tags % "{tag}"}%H')
947 947 '{rev}{tags % "{tag}"}{node}'
948 948
949 949 '\' in outermost strings has to be escaped because it is a directory
950 950 separator on Windows:
951 951
952 952 >>> _buildfntemplate(b'c:\\tmp\\%R\\%n.patch', seqno=0)
953 953 'c:\\\\tmp\\\\{rev}\\\\{seqno}.patch'
954 954 >>> _buildfntemplate(b'\\\\foo\\bar.patch')
955 955 '\\\\\\\\foo\\\\bar.patch'
956 956 >>> _buildfntemplate(b'\\{tags % "{tag}"}')
957 957 '\\\\{tags % "{tag}"}'
958 958
959 959 but inner strings follow the template rules (i.e. '\' is taken as an
960 960 escape character):
961 961
962 962 >>> _buildfntemplate(br'{"c:\tmp"}', seqno=0)
963 963 '{"c:\\tmp"}'
964 964 """
965 965 expander = {
966 966 b'H': b'{node}',
967 967 b'R': b'{rev}',
968 968 b'h': b'{node|short}',
969 969 b'm': br'{sub(r"[^\w]", "_", desc|firstline)}',
970 970 b'r': b'{if(revwidth, pad(rev, revwidth, "0", left=True), rev)}',
971 971 b'%': b'%',
972 972 b'b': b'{reporoot|basename}',
973 973 }
974 974 if total is not None:
975 975 expander[b'N'] = b'{total}'
976 976 if seqno is not None:
977 977 expander[b'n'] = b'{seqno}'
978 978 if total is not None and seqno is not None:
979 979 expander[b'n'] = b'{pad(seqno, total|stringify|count, "0", left=True)}'
980 980 if pathname is not None:
981 981 expander[b's'] = b'{pathname|basename}'
982 982 expander[b'd'] = b'{if(pathname|dirname, pathname|dirname, ".")}'
983 983 expander[b'p'] = b'{pathname}'
984 984
985 985 newname = []
986 986 for typ, start, end in templater.scantemplate(pat, raw=True):
987 987 if typ != b'string':
988 988 newname.append(pat[start:end])
989 989 continue
990 990 i = start
991 991 while i < end:
992 992 n = pat.find(b'%', i, end)
993 993 if n < 0:
994 994 newname.append(stringutil.escapestr(pat[i:end]))
995 995 break
996 996 newname.append(stringutil.escapestr(pat[i:n]))
997 997 if n + 2 > end:
998 998 raise error.Abort(_("incomplete format spec in output "
999 999 "filename"))
1000 1000 c = pat[n + 1:n + 2]
1001 1001 i = n + 2
1002 1002 try:
1003 1003 newname.append(expander[c])
1004 1004 except KeyError:
1005 1005 raise error.Abort(_("invalid format spec '%%%s' in output "
1006 1006 "filename") % c)
1007 1007 return ''.join(newname)
1008 1008
1009 1009 def makefilename(ctx, pat, **props):
1010 1010 if not pat:
1011 1011 return pat
1012 1012 tmpl = _buildfntemplate(pat, **props)
1013 1013 # BUG: alias expansion shouldn't be made against template fragments
1014 1014 # rewritten from %-format strings, but we have no easy way to partially
1015 1015 # disable the expansion.
1016 1016 return rendertemplate(ctx, tmpl, pycompat.byteskwargs(props))
1017 1017
1018 1018 def isstdiofilename(pat):
1019 1019 """True if the given pat looks like a filename denoting stdin/stdout"""
1020 1020 return not pat or pat == '-'
1021 1021
1022 1022 class _unclosablefile(object):
1023 1023 def __init__(self, fp):
1024 1024 self._fp = fp
1025 1025
1026 1026 def close(self):
1027 1027 pass
1028 1028
1029 1029 def __iter__(self):
1030 1030 return iter(self._fp)
1031 1031
1032 1032 def __getattr__(self, attr):
1033 1033 return getattr(self._fp, attr)
1034 1034
1035 1035 def __enter__(self):
1036 1036 return self
1037 1037
1038 1038 def __exit__(self, exc_type, exc_value, exc_tb):
1039 1039 pass
1040 1040
1041 1041 def makefileobj(ctx, pat, mode='wb', **props):
1042 1042 writable = mode not in ('r', 'rb')
1043 1043
1044 1044 if isstdiofilename(pat):
1045 1045 repo = ctx.repo()
1046 1046 if writable:
1047 1047 fp = repo.ui.fout
1048 1048 else:
1049 1049 fp = repo.ui.fin
1050 1050 return _unclosablefile(fp)
1051 1051 fn = makefilename(ctx, pat, **props)
1052 1052 return open(fn, mode)
1053 1053
1054 1054 def openstorage(repo, cmd, file_, opts, returnrevlog=False):
1055 1055 """opens the changelog, manifest, a filelog or a given revlog"""
1056 1056 cl = opts['changelog']
1057 1057 mf = opts['manifest']
1058 1058 dir = opts['dir']
1059 1059 msg = None
1060 1060 if cl and mf:
1061 1061 msg = _('cannot specify --changelog and --manifest at the same time')
1062 1062 elif cl and dir:
1063 1063 msg = _('cannot specify --changelog and --dir at the same time')
1064 1064 elif cl or mf or dir:
1065 1065 if file_:
1066 1066 msg = _('cannot specify filename with --changelog or --manifest')
1067 1067 elif not repo:
1068 1068 msg = _('cannot specify --changelog or --manifest or --dir '
1069 1069 'without a repository')
1070 1070 if msg:
1071 1071 raise error.Abort(msg)
1072 1072
1073 1073 r = None
1074 1074 if repo:
1075 1075 if cl:
1076 1076 r = repo.unfiltered().changelog
1077 1077 elif dir:
1078 1078 if 'treemanifest' not in repo.requirements:
1079 1079 raise error.Abort(_("--dir can only be used on repos with "
1080 1080 "treemanifest enabled"))
1081 1081 if not dir.endswith('/'):
1082 1082 dir = dir + '/'
1083 1083 dirlog = repo.manifestlog.getstorage(dir)
1084 1084 if len(dirlog):
1085 1085 r = dirlog
1086 1086 elif mf:
1087 1087 r = repo.manifestlog.getstorage(b'')
1088 1088 elif file_:
1089 1089 filelog = repo.file(file_)
1090 1090 if len(filelog):
1091 1091 r = filelog
1092 1092
1093 1093 # Not all storage may be revlogs. If requested, try to return an actual
1094 1094 # revlog instance.
1095 1095 if returnrevlog:
1096 1096 if isinstance(r, revlog.revlog):
1097 1097 pass
1098 1098 elif util.safehasattr(r, '_revlog'):
1099 1099 r = r._revlog
1100 1100 elif r is not None:
1101 1101 raise error.Abort(_('%r does not appear to be a revlog') % r)
1102 1102
1103 1103 if not r:
1104 1104 if not returnrevlog:
1105 1105 raise error.Abort(_('cannot give path to non-revlog'))
1106 1106
1107 1107 if not file_:
1108 1108 raise error.CommandError(cmd, _('invalid arguments'))
1109 1109 if not os.path.isfile(file_):
1110 1110 raise error.Abort(_("revlog '%s' not found") % file_)
1111 1111 r = revlog.revlog(vfsmod.vfs(encoding.getcwd(), audit=False),
1112 1112 file_[:-2] + ".i")
1113 1113 return r
1114 1114
1115 1115 def openrevlog(repo, cmd, file_, opts):
1116 1116 """Obtain a revlog backing storage of an item.
1117 1117
1118 1118 This is similar to ``openstorage()`` except it always returns a revlog.
1119 1119
1120 1120 In most cases, a caller cares about the main storage object - not the
1121 1121 revlog backing it. Therefore, this function should only be used by code
1122 1122 that needs to examine low-level revlog implementation details. e.g. debug
1123 1123 commands.
1124 1124 """
1125 1125 return openstorage(repo, cmd, file_, opts, returnrevlog=True)
1126 1126
1127 1127 def copy(ui, repo, pats, opts, rename=False):
1128 1128 # called with the repo lock held
1129 1129 #
1130 1130 # hgsep => pathname that uses "/" to separate directories
1131 1131 # ossep => pathname that uses os.sep to separate directories
1132 1132 cwd = repo.getcwd()
1133 1133 targets = {}
1134 1134 after = opts.get("after")
1135 1135 dryrun = opts.get("dry_run")
1136 1136 wctx = repo[None]
1137 1137
1138 1138 def walkpat(pat):
1139 1139 srcs = []
1140 1140 if after:
1141 1141 badstates = '?'
1142 1142 else:
1143 1143 badstates = '?r'
1144 1144 m = scmutil.match(wctx, [pat], opts, globbed=True)
1145 1145 for abs in wctx.walk(m):
1146 1146 state = repo.dirstate[abs]
1147 1147 rel = m.rel(abs)
1148 1148 exact = m.exact(abs)
1149 1149 if state in badstates:
1150 1150 if exact and state == '?':
1151 1151 ui.warn(_('%s: not copying - file is not managed\n') % rel)
1152 1152 if exact and state == 'r':
1153 1153 ui.warn(_('%s: not copying - file has been marked for'
1154 1154 ' remove\n') % rel)
1155 1155 continue
1156 1156 # abs: hgsep
1157 1157 # rel: ossep
1158 1158 srcs.append((abs, rel, exact))
1159 1159 return srcs
1160 1160
1161 1161 # abssrc: hgsep
1162 1162 # relsrc: ossep
1163 1163 # otarget: ossep
1164 1164 def copyfile(abssrc, relsrc, otarget, exact):
1165 1165 abstarget = pathutil.canonpath(repo.root, cwd, otarget)
1166 1166 if '/' in abstarget:
1167 1167 # We cannot normalize abstarget itself, this would prevent
1168 1168 # case only renames, like a => A.
1169 1169 abspath, absname = abstarget.rsplit('/', 1)
1170 1170 abstarget = repo.dirstate.normalize(abspath) + '/' + absname
1171 1171 reltarget = repo.pathto(abstarget, cwd)
1172 1172 target = repo.wjoin(abstarget)
1173 1173 src = repo.wjoin(abssrc)
1174 1174 state = repo.dirstate[abstarget]
1175 1175
1176 1176 scmutil.checkportable(ui, abstarget)
1177 1177
1178 1178 # check for collisions
1179 1179 prevsrc = targets.get(abstarget)
1180 1180 if prevsrc is not None:
1181 1181 ui.warn(_('%s: not overwriting - %s collides with %s\n') %
1182 1182 (reltarget, repo.pathto(abssrc, cwd),
1183 1183 repo.pathto(prevsrc, cwd)))
1184 1184 return True # report a failure
1185 1185
1186 1186 # check for overwrites
1187 1187 exists = os.path.lexists(target)
1188 1188 samefile = False
1189 1189 if exists and abssrc != abstarget:
1190 1190 if (repo.dirstate.normalize(abssrc) ==
1191 1191 repo.dirstate.normalize(abstarget)):
1192 1192 if not rename:
1193 1193 ui.warn(_("%s: can't copy - same file\n") % reltarget)
1194 1194 return True # report a failure
1195 1195 exists = False
1196 1196 samefile = True
1197 1197
1198 1198 if not after and exists or after and state in 'mn':
1199 1199 if not opts['force']:
1200 1200 if state in 'mn':
1201 1201 msg = _('%s: not overwriting - file already committed\n')
1202 1202 if after:
1203 1203 flags = '--after --force'
1204 1204 else:
1205 1205 flags = '--force'
1206 1206 if rename:
1207 1207 hint = _("('hg rename %s' to replace the file by "
1208 1208 'recording a rename)\n') % flags
1209 1209 else:
1210 1210 hint = _("('hg copy %s' to replace the file by "
1211 1211 'recording a copy)\n') % flags
1212 1212 else:
1213 1213 msg = _('%s: not overwriting - file exists\n')
1214 1214 if rename:
1215 1215 hint = _("('hg rename --after' to record the rename)\n")
1216 1216 else:
1217 1217 hint = _("('hg copy --after' to record the copy)\n")
1218 1218 ui.warn(msg % reltarget)
1219 1219 ui.warn(hint)
1220 1220 return True # report a failure
1221 1221
1222 1222 if after:
1223 1223 if not exists:
1224 1224 if rename:
1225 1225 ui.warn(_('%s: not recording move - %s does not exist\n') %
1226 1226 (relsrc, reltarget))
1227 1227 else:
1228 1228 ui.warn(_('%s: not recording copy - %s does not exist\n') %
1229 1229 (relsrc, reltarget))
1230 1230 return True # report a failure
1231 1231 elif not dryrun:
1232 1232 try:
1233 1233 if exists:
1234 1234 os.unlink(target)
1235 1235 targetdir = os.path.dirname(target) or '.'
1236 1236 if not os.path.isdir(targetdir):
1237 1237 os.makedirs(targetdir)
1238 1238 if samefile:
1239 1239 tmp = target + "~hgrename"
1240 1240 os.rename(src, tmp)
1241 1241 os.rename(tmp, target)
1242 1242 else:
1243 1243 # Preserve stat info on renames, not on copies; this matches
1244 1244 # Linux CLI behavior.
1245 1245 util.copyfile(src, target, copystat=rename)
1246 1246 srcexists = True
1247 1247 except IOError as inst:
1248 1248 if inst.errno == errno.ENOENT:
1249 1249 ui.warn(_('%s: deleted in working directory\n') % relsrc)
1250 1250 srcexists = False
1251 1251 else:
1252 1252 ui.warn(_('%s: cannot copy - %s\n') %
1253 1253 (relsrc, encoding.strtolocal(inst.strerror)))
1254 1254 return True # report a failure
1255 1255
1256 1256 if ui.verbose or not exact:
1257 1257 if rename:
1258 1258 ui.status(_('moving %s to %s\n') % (relsrc, reltarget))
1259 1259 else:
1260 1260 ui.status(_('copying %s to %s\n') % (relsrc, reltarget))
1261 1261
1262 1262 targets[abstarget] = abssrc
1263 1263
1264 1264 # fix up dirstate
1265 1265 scmutil.dirstatecopy(ui, repo, wctx, abssrc, abstarget,
1266 1266 dryrun=dryrun, cwd=cwd)
1267 1267 if rename and not dryrun:
1268 1268 if not after and srcexists and not samefile:
1269 1269 rmdir = repo.ui.configbool('experimental', 'removeemptydirs')
1270 1270 repo.wvfs.unlinkpath(abssrc, rmdir=rmdir)
1271 1271 wctx.forget([abssrc])
1272 1272
1273 1273 # pat: ossep
1274 1274 # dest ossep
1275 1275 # srcs: list of (hgsep, hgsep, ossep, bool)
1276 1276 # return: function that takes hgsep and returns ossep
1277 1277 def targetpathfn(pat, dest, srcs):
1278 1278 if os.path.isdir(pat):
1279 1279 abspfx = pathutil.canonpath(repo.root, cwd, pat)
1280 1280 abspfx = util.localpath(abspfx)
1281 1281 if destdirexists:
1282 1282 striplen = len(os.path.split(abspfx)[0])
1283 1283 else:
1284 1284 striplen = len(abspfx)
1285 1285 if striplen:
1286 1286 striplen += len(pycompat.ossep)
1287 1287 res = lambda p: os.path.join(dest, util.localpath(p)[striplen:])
1288 1288 elif destdirexists:
1289 1289 res = lambda p: os.path.join(dest,
1290 1290 os.path.basename(util.localpath(p)))
1291 1291 else:
1292 1292 res = lambda p: dest
1293 1293 return res
1294 1294
1295 1295 # pat: ossep
1296 1296 # dest ossep
1297 1297 # srcs: list of (hgsep, hgsep, ossep, bool)
1298 1298 # return: function that takes hgsep and returns ossep
1299 1299 def targetpathafterfn(pat, dest, srcs):
1300 1300 if matchmod.patkind(pat):
1301 1301 # a mercurial pattern
1302 1302 res = lambda p: os.path.join(dest,
1303 1303 os.path.basename(util.localpath(p)))
1304 1304 else:
1305 1305 abspfx = pathutil.canonpath(repo.root, cwd, pat)
1306 1306 if len(abspfx) < len(srcs[0][0]):
1307 1307 # A directory. Either the target path contains the last
1308 1308 # component of the source path or it does not.
1309 1309 def evalpath(striplen):
1310 1310 score = 0
1311 1311 for s in srcs:
1312 1312 t = os.path.join(dest, util.localpath(s[0])[striplen:])
1313 1313 if os.path.lexists(t):
1314 1314 score += 1
1315 1315 return score
1316 1316
1317 1317 abspfx = util.localpath(abspfx)
1318 1318 striplen = len(abspfx)
1319 1319 if striplen:
1320 1320 striplen += len(pycompat.ossep)
1321 1321 if os.path.isdir(os.path.join(dest, os.path.split(abspfx)[1])):
1322 1322 score = evalpath(striplen)
1323 1323 striplen1 = len(os.path.split(abspfx)[0])
1324 1324 if striplen1:
1325 1325 striplen1 += len(pycompat.ossep)
1326 1326 if evalpath(striplen1) > score:
1327 1327 striplen = striplen1
1328 1328 res = lambda p: os.path.join(dest,
1329 1329 util.localpath(p)[striplen:])
1330 1330 else:
1331 1331 # a file
1332 1332 if destdirexists:
1333 1333 res = lambda p: os.path.join(dest,
1334 1334 os.path.basename(util.localpath(p)))
1335 1335 else:
1336 1336 res = lambda p: dest
1337 1337 return res
1338 1338
1339 1339 pats = scmutil.expandpats(pats)
1340 1340 if not pats:
1341 1341 raise error.Abort(_('no source or destination specified'))
1342 1342 if len(pats) == 1:
1343 1343 raise error.Abort(_('no destination specified'))
1344 1344 dest = pats.pop()
1345 1345 destdirexists = os.path.isdir(dest) and not os.path.islink(dest)
1346 1346 if not destdirexists:
1347 1347 if len(pats) > 1 or matchmod.patkind(pats[0]):
1348 1348 raise error.Abort(_('with multiple sources, destination must be an '
1349 1349 'existing directory'))
1350 1350 if util.endswithsep(dest):
1351 1351 raise error.Abort(_('destination %s is not a directory') % dest)
1352 1352
1353 1353 tfn = targetpathfn
1354 1354 if after:
1355 1355 tfn = targetpathafterfn
1356 1356 copylist = []
1357 1357 for pat in pats:
1358 1358 srcs = walkpat(pat)
1359 1359 if not srcs:
1360 1360 continue
1361 1361 copylist.append((tfn(pat, dest, srcs), srcs))
1362 1362 if not copylist:
1363 1363 raise error.Abort(_('no files to copy'))
1364 1364
1365 1365 errors = 0
1366 1366 for targetpath, srcs in copylist:
1367 1367 for abssrc, relsrc, exact in srcs:
1368 1368 if copyfile(abssrc, relsrc, targetpath(abssrc), exact):
1369 1369 errors += 1
1370 1370
1371 1371 return errors != 0
1372 1372
1373 1373 ## facility to let extension process additional data into an import patch
1374 1374 # list of identifier to be executed in order
1375 1375 extrapreimport = [] # run before commit
1376 1376 extrapostimport = [] # run after commit
1377 1377 # mapping from identifier to actual import function
1378 1378 #
1379 1379 # 'preimport' are run before the commit is made and are provided the following
1380 1380 # arguments:
1381 1381 # - repo: the localrepository instance,
1382 1382 # - patchdata: data extracted from patch header (cf m.patch.patchheadermap),
1383 1383 # - extra: the future extra dictionary of the changeset, please mutate it,
1384 1384 # - opts: the import options.
1385 1385 # XXX ideally, we would just pass an ctx ready to be computed, that would allow
1386 1386 # mutation of in memory commit and more. Feel free to rework the code to get
1387 1387 # there.
1388 1388 extrapreimportmap = {}
1389 1389 # 'postimport' are run after the commit is made and are provided the following
1390 1390 # argument:
1391 1391 # - ctx: the changectx created by import.
1392 1392 extrapostimportmap = {}
1393 1393
1394 1394 def tryimportone(ui, repo, patchdata, parents, opts, msgs, updatefunc):
1395 1395 """Utility function used by commands.import to import a single patch
1396 1396
1397 1397 This function is explicitly defined here to help the evolve extension to
1398 1398 wrap this part of the import logic.
1399 1399
1400 1400 The API is currently a bit ugly because it a simple code translation from
1401 1401 the import command. Feel free to make it better.
1402 1402
1403 1403 :patchdata: a dictionary containing parsed patch data (such as from
1404 1404 ``patch.extract()``)
1405 1405 :parents: nodes that will be parent of the created commit
1406 1406 :opts: the full dict of option passed to the import command
1407 1407 :msgs: list to save commit message to.
1408 1408 (used in case we need to save it when failing)
1409 1409 :updatefunc: a function that update a repo to a given node
1410 1410 updatefunc(<repo>, <node>)
1411 1411 """
1412 1412 # avoid cycle context -> subrepo -> cmdutil
1413 1413 from . import context
1414 1414
1415 1415 tmpname = patchdata.get('filename')
1416 1416 message = patchdata.get('message')
1417 1417 user = opts.get('user') or patchdata.get('user')
1418 1418 date = opts.get('date') or patchdata.get('date')
1419 1419 branch = patchdata.get('branch')
1420 1420 nodeid = patchdata.get('nodeid')
1421 1421 p1 = patchdata.get('p1')
1422 1422 p2 = patchdata.get('p2')
1423 1423
1424 1424 nocommit = opts.get('no_commit')
1425 1425 importbranch = opts.get('import_branch')
1426 1426 update = not opts.get('bypass')
1427 1427 strip = opts["strip"]
1428 1428 prefix = opts["prefix"]
1429 1429 sim = float(opts.get('similarity') or 0)
1430 1430
1431 1431 if not tmpname:
1432 1432 return None, None, False
1433 1433
1434 1434 rejects = False
1435 1435
1436 1436 cmdline_message = logmessage(ui, opts)
1437 1437 if cmdline_message:
1438 1438 # pickup the cmdline msg
1439 1439 message = cmdline_message
1440 1440 elif message:
1441 1441 # pickup the patch msg
1442 1442 message = message.strip()
1443 1443 else:
1444 1444 # launch the editor
1445 1445 message = None
1446 1446 ui.debug('message:\n%s\n' % (message or ''))
1447 1447
1448 1448 if len(parents) == 1:
1449 1449 parents.append(repo[nullid])
1450 1450 if opts.get('exact'):
1451 1451 if not nodeid or not p1:
1452 1452 raise error.Abort(_('not a Mercurial patch'))
1453 1453 p1 = repo[p1]
1454 1454 p2 = repo[p2 or nullid]
1455 1455 elif p2:
1456 1456 try:
1457 1457 p1 = repo[p1]
1458 1458 p2 = repo[p2]
1459 1459 # Without any options, consider p2 only if the
1460 1460 # patch is being applied on top of the recorded
1461 1461 # first parent.
1462 1462 if p1 != parents[0]:
1463 1463 p1 = parents[0]
1464 1464 p2 = repo[nullid]
1465 1465 except error.RepoError:
1466 1466 p1, p2 = parents
1467 1467 if p2.node() == nullid:
1468 1468 ui.warn(_("warning: import the patch as a normal revision\n"
1469 1469 "(use --exact to import the patch as a merge)\n"))
1470 1470 else:
1471 1471 p1, p2 = parents
1472 1472
1473 1473 n = None
1474 1474 if update:
1475 1475 if p1 != parents[0]:
1476 1476 updatefunc(repo, p1.node())
1477 1477 if p2 != parents[1]:
1478 1478 repo.setparents(p1.node(), p2.node())
1479 1479
1480 1480 if opts.get('exact') or importbranch:
1481 1481 repo.dirstate.setbranch(branch or 'default')
1482 1482
1483 1483 partial = opts.get('partial', False)
1484 1484 files = set()
1485 1485 try:
1486 1486 patch.patch(ui, repo, tmpname, strip=strip, prefix=prefix,
1487 1487 files=files, eolmode=None, similarity=sim / 100.0)
1488 1488 except error.PatchError as e:
1489 1489 if not partial:
1490 1490 raise error.Abort(pycompat.bytestr(e))
1491 1491 if partial:
1492 1492 rejects = True
1493 1493
1494 1494 files = list(files)
1495 1495 if nocommit:
1496 1496 if message:
1497 1497 msgs.append(message)
1498 1498 else:
1499 1499 if opts.get('exact') or p2:
1500 1500 # If you got here, you either use --force and know what
1501 1501 # you are doing or used --exact or a merge patch while
1502 1502 # being updated to its first parent.
1503 1503 m = None
1504 1504 else:
1505 1505 m = scmutil.matchfiles(repo, files or [])
1506 1506 editform = mergeeditform(repo[None], 'import.normal')
1507 1507 if opts.get('exact'):
1508 1508 editor = None
1509 1509 else:
1510 1510 editor = getcommiteditor(editform=editform,
1511 1511 **pycompat.strkwargs(opts))
1512 1512 extra = {}
1513 1513 for idfunc in extrapreimport:
1514 1514 extrapreimportmap[idfunc](repo, patchdata, extra, opts)
1515 1515 overrides = {}
1516 1516 if partial:
1517 1517 overrides[('ui', 'allowemptycommit')] = True
1518 1518 with repo.ui.configoverride(overrides, 'import'):
1519 1519 n = repo.commit(message, user,
1520 1520 date, match=m,
1521 1521 editor=editor, extra=extra)
1522 1522 for idfunc in extrapostimport:
1523 1523 extrapostimportmap[idfunc](repo[n])
1524 1524 else:
1525 1525 if opts.get('exact') or importbranch:
1526 1526 branch = branch or 'default'
1527 1527 else:
1528 1528 branch = p1.branch()
1529 1529 store = patch.filestore()
1530 1530 try:
1531 1531 files = set()
1532 1532 try:
1533 1533 patch.patchrepo(ui, repo, p1, store, tmpname, strip, prefix,
1534 1534 files, eolmode=None)
1535 1535 except error.PatchError as e:
1536 1536 raise error.Abort(stringutil.forcebytestr(e))
1537 1537 if opts.get('exact'):
1538 1538 editor = None
1539 1539 else:
1540 1540 editor = getcommiteditor(editform='import.bypass')
1541 1541 memctx = context.memctx(repo, (p1.node(), p2.node()),
1542 1542 message,
1543 1543 files=files,
1544 1544 filectxfn=store,
1545 1545 user=user,
1546 1546 date=date,
1547 1547 branch=branch,
1548 1548 editor=editor)
1549 1549 n = memctx.commit()
1550 1550 finally:
1551 1551 store.close()
1552 1552 if opts.get('exact') and nocommit:
1553 1553 # --exact with --no-commit is still useful in that it does merge
1554 1554 # and branch bits
1555 1555 ui.warn(_("warning: can't check exact import with --no-commit\n"))
1556 1556 elif opts.get('exact') and (not n or hex(n) != nodeid):
1557 1557 raise error.Abort(_('patch is damaged or loses information'))
1558 1558 msg = _('applied to working directory')
1559 1559 if n:
1560 1560 # i18n: refers to a short changeset id
1561 1561 msg = _('created %s') % short(n)
1562 1562 return msg, n, rejects
1563 1563
1564 1564 # facility to let extensions include additional data in an exported patch
1565 1565 # list of identifiers to be executed in order
1566 1566 extraexport = []
1567 1567 # mapping from identifier to actual export function
1568 1568 # function as to return a string to be added to the header or None
1569 1569 # it is given two arguments (sequencenumber, changectx)
1570 1570 extraexportmap = {}
1571 1571
1572 1572 def _exportsingle(repo, ctx, fm, match, switch_parent, seqno, diffopts):
1573 1573 node = scmutil.binnode(ctx)
1574 1574 parents = [p.node() for p in ctx.parents() if p]
1575 1575 branch = ctx.branch()
1576 1576 if switch_parent:
1577 1577 parents.reverse()
1578 1578
1579 1579 if parents:
1580 1580 prev = parents[0]
1581 1581 else:
1582 1582 prev = nullid
1583 1583
1584 1584 fm.context(ctx=ctx)
1585 1585 fm.plain('# HG changeset patch\n')
1586 1586 fm.write('user', '# User %s\n', ctx.user())
1587 1587 fm.plain('# Date %d %d\n' % ctx.date())
1588 1588 fm.write('date', '# %s\n', fm.formatdate(ctx.date()))
1589 1589 fm.condwrite(branch and branch != 'default',
1590 1590 'branch', '# Branch %s\n', branch)
1591 1591 fm.write('node', '# Node ID %s\n', hex(node))
1592 1592 fm.plain('# Parent %s\n' % hex(prev))
1593 1593 if len(parents) > 1:
1594 1594 fm.plain('# Parent %s\n' % hex(parents[1]))
1595 1595 fm.data(parents=fm.formatlist(pycompat.maplist(hex, parents), name='node'))
1596 1596
1597 1597 # TODO: redesign extraexportmap function to support formatter
1598 1598 for headerid in extraexport:
1599 1599 header = extraexportmap[headerid](seqno, ctx)
1600 1600 if header is not None:
1601 1601 fm.plain('# %s\n' % header)
1602 1602
1603 1603 fm.write('desc', '%s\n', ctx.description().rstrip())
1604 1604 fm.plain('\n')
1605 1605
1606 1606 if fm.isplain():
1607 1607 chunkiter = patch.diffui(repo, prev, node, match, opts=diffopts)
1608 1608 for chunk, label in chunkiter:
1609 1609 fm.plain(chunk, label=label)
1610 1610 else:
1611 1611 chunkiter = patch.diff(repo, prev, node, match, opts=diffopts)
1612 1612 # TODO: make it structured?
1613 1613 fm.data(diff=b''.join(chunkiter))
1614 1614
1615 1615 def _exportfile(repo, revs, fm, dest, switch_parent, diffopts, match):
1616 1616 """Export changesets to stdout or a single file"""
1617 1617 for seqno, rev in enumerate(revs, 1):
1618 1618 ctx = repo[rev]
1619 1619 if not dest.startswith('<'):
1620 1620 repo.ui.note("%s\n" % dest)
1621 1621 fm.startitem()
1622 1622 _exportsingle(repo, ctx, fm, match, switch_parent, seqno, diffopts)
1623 1623
1624 1624 def _exportfntemplate(repo, revs, basefm, fntemplate, switch_parent, diffopts,
1625 1625 match):
1626 1626 """Export changesets to possibly multiple files"""
1627 1627 total = len(revs)
1628 1628 revwidth = max(len(str(rev)) for rev in revs)
1629 1629 filemap = util.sortdict() # filename: [(seqno, rev), ...]
1630 1630
1631 1631 for seqno, rev in enumerate(revs, 1):
1632 1632 ctx = repo[rev]
1633 1633 dest = makefilename(ctx, fntemplate,
1634 1634 total=total, seqno=seqno, revwidth=revwidth)
1635 1635 filemap.setdefault(dest, []).append((seqno, rev))
1636 1636
1637 1637 for dest in filemap:
1638 1638 with formatter.maybereopen(basefm, dest) as fm:
1639 1639 repo.ui.note("%s\n" % dest)
1640 1640 for seqno, rev in filemap[dest]:
1641 1641 fm.startitem()
1642 1642 ctx = repo[rev]
1643 1643 _exportsingle(repo, ctx, fm, match, switch_parent, seqno,
1644 1644 diffopts)
1645 1645
1646 1646 def export(repo, revs, basefm, fntemplate='hg-%h.patch', switch_parent=False,
1647 1647 opts=None, match=None):
1648 1648 '''export changesets as hg patches
1649 1649
1650 1650 Args:
1651 1651 repo: The repository from which we're exporting revisions.
1652 1652 revs: A list of revisions to export as revision numbers.
1653 1653 basefm: A formatter to which patches should be written.
1654 1654 fntemplate: An optional string to use for generating patch file names.
1655 1655 switch_parent: If True, show diffs against second parent when not nullid.
1656 1656 Default is false, which always shows diff against p1.
1657 1657 opts: diff options to use for generating the patch.
1658 1658 match: If specified, only export changes to files matching this matcher.
1659 1659
1660 1660 Returns:
1661 1661 Nothing.
1662 1662
1663 1663 Side Effect:
1664 1664 "HG Changeset Patch" data is emitted to one of the following
1665 1665 destinations:
1666 1666 fntemplate specified: Each rev is written to a unique file named using
1667 1667 the given template.
1668 1668 Otherwise: All revs will be written to basefm.
1669 1669 '''
1670 1670 scmutil.prefetchfiles(repo, revs, match)
1671 1671
1672 1672 if not fntemplate:
1673 1673 _exportfile(repo, revs, basefm, '<unnamed>', switch_parent, opts, match)
1674 1674 else:
1675 1675 _exportfntemplate(repo, revs, basefm, fntemplate, switch_parent, opts,
1676 1676 match)
1677 1677
1678 1678 def exportfile(repo, revs, fp, switch_parent=False, opts=None, match=None):
1679 1679 """Export changesets to the given file stream"""
1680 1680 scmutil.prefetchfiles(repo, revs, match)
1681 1681
1682 1682 dest = getattr(fp, 'name', '<unnamed>')
1683 1683 with formatter.formatter(repo.ui, fp, 'export', {}) as fm:
1684 1684 _exportfile(repo, revs, fm, dest, switch_parent, opts, match)
1685 1685
1686 1686 def showmarker(fm, marker, index=None):
1687 1687 """utility function to display obsolescence marker in a readable way
1688 1688
1689 1689 To be used by debug function."""
1690 1690 if index is not None:
1691 1691 fm.write('index', '%i ', index)
1692 1692 fm.write('prednode', '%s ', hex(marker.prednode()))
1693 1693 succs = marker.succnodes()
1694 1694 fm.condwrite(succs, 'succnodes', '%s ',
1695 1695 fm.formatlist(map(hex, succs), name='node'))
1696 1696 fm.write('flag', '%X ', marker.flags())
1697 1697 parents = marker.parentnodes()
1698 1698 if parents is not None:
1699 1699 fm.write('parentnodes', '{%s} ',
1700 1700 fm.formatlist(map(hex, parents), name='node', sep=', '))
1701 1701 fm.write('date', '(%s) ', fm.formatdate(marker.date()))
1702 1702 meta = marker.metadata().copy()
1703 1703 meta.pop('date', None)
1704 1704 smeta = pycompat.rapply(pycompat.maybebytestr, meta)
1705 1705 fm.write('metadata', '{%s}', fm.formatdict(smeta, fmt='%r: %r', sep=', '))
1706 1706 fm.plain('\n')
1707 1707
1708 1708 def finddate(ui, repo, date):
1709 1709 """Find the tipmost changeset that matches the given date spec"""
1710 1710
1711 1711 df = dateutil.matchdate(date)
1712 1712 m = scmutil.matchall(repo)
1713 1713 results = {}
1714 1714
1715 1715 def prep(ctx, fns):
1716 1716 d = ctx.date()
1717 1717 if df(d[0]):
1718 1718 results[ctx.rev()] = d
1719 1719
1720 1720 for ctx in walkchangerevs(repo, m, {'rev': None}, prep):
1721 1721 rev = ctx.rev()
1722 1722 if rev in results:
1723 1723 ui.status(_("found revision %s from %s\n") %
1724 1724 (rev, dateutil.datestr(results[rev])))
1725 1725 return '%d' % rev
1726 1726
1727 1727 raise error.Abort(_("revision matching date not found"))
1728 1728
1729 1729 def increasingwindows(windowsize=8, sizelimit=512):
1730 1730 while True:
1731 1731 yield windowsize
1732 1732 if windowsize < sizelimit:
1733 1733 windowsize *= 2
1734 1734
1735 1735 def _walkrevs(repo, opts):
1736 1736 # Default --rev value depends on --follow but --follow behavior
1737 1737 # depends on revisions resolved from --rev...
1738 1738 follow = opts.get('follow') or opts.get('follow_first')
1739 1739 if opts.get('rev'):
1740 1740 revs = scmutil.revrange(repo, opts['rev'])
1741 1741 elif follow and repo.dirstate.p1() == nullid:
1742 1742 revs = smartset.baseset()
1743 1743 elif follow:
1744 1744 revs = repo.revs('reverse(:.)')
1745 1745 else:
1746 1746 revs = smartset.spanset(repo)
1747 1747 revs.reverse()
1748 1748 return revs
1749 1749
1750 1750 class FileWalkError(Exception):
1751 1751 pass
1752 1752
1753 1753 def walkfilerevs(repo, match, follow, revs, fncache):
1754 1754 '''Walks the file history for the matched files.
1755 1755
1756 1756 Returns the changeset revs that are involved in the file history.
1757 1757
1758 1758 Throws FileWalkError if the file history can't be walked using
1759 1759 filelogs alone.
1760 1760 '''
1761 1761 wanted = set()
1762 1762 copies = []
1763 1763 minrev, maxrev = min(revs), max(revs)
1764 1764 def filerevgen(filelog, last):
1765 1765 """
1766 1766 Only files, no patterns. Check the history of each file.
1767 1767
1768 1768 Examines filelog entries within minrev, maxrev linkrev range
1769 1769 Returns an iterator yielding (linkrev, parentlinkrevs, copied)
1770 1770 tuples in backwards order
1771 1771 """
1772 1772 cl_count = len(repo)
1773 1773 revs = []
1774 1774 for j in pycompat.xrange(0, last + 1):
1775 1775 linkrev = filelog.linkrev(j)
1776 1776 if linkrev < minrev:
1777 1777 continue
1778 1778 # only yield rev for which we have the changelog, it can
1779 1779 # happen while doing "hg log" during a pull or commit
1780 1780 if linkrev >= cl_count:
1781 1781 break
1782 1782
1783 1783 parentlinkrevs = []
1784 1784 for p in filelog.parentrevs(j):
1785 1785 if p != nullrev:
1786 1786 parentlinkrevs.append(filelog.linkrev(p))
1787 1787 n = filelog.node(j)
1788 1788 revs.append((linkrev, parentlinkrevs,
1789 1789 follow and filelog.renamed(n)))
1790 1790
1791 1791 return reversed(revs)
1792 1792 def iterfiles():
1793 1793 pctx = repo['.']
1794 1794 for filename in match.files():
1795 1795 if follow:
1796 1796 if filename not in pctx:
1797 1797 raise error.Abort(_('cannot follow file not in parent '
1798 1798 'revision: "%s"') % filename)
1799 1799 yield filename, pctx[filename].filenode()
1800 1800 else:
1801 1801 yield filename, None
1802 1802 for filename_node in copies:
1803 1803 yield filename_node
1804 1804
1805 1805 for file_, node in iterfiles():
1806 1806 filelog = repo.file(file_)
1807 1807 if not len(filelog):
1808 1808 if node is None:
1809 1809 # A zero count may be a directory or deleted file, so
1810 1810 # try to find matching entries on the slow path.
1811 1811 if follow:
1812 1812 raise error.Abort(
1813 1813 _('cannot follow nonexistent file: "%s"') % file_)
1814 1814 raise FileWalkError("Cannot walk via filelog")
1815 1815 else:
1816 1816 continue
1817 1817
1818 1818 if node is None:
1819 1819 last = len(filelog) - 1
1820 1820 else:
1821 1821 last = filelog.rev(node)
1822 1822
1823 1823 # keep track of all ancestors of the file
1824 1824 ancestors = {filelog.linkrev(last)}
1825 1825
1826 1826 # iterate from latest to oldest revision
1827 1827 for rev, flparentlinkrevs, copied in filerevgen(filelog, last):
1828 1828 if not follow:
1829 1829 if rev > maxrev:
1830 1830 continue
1831 1831 else:
1832 1832 # Note that last might not be the first interesting
1833 1833 # rev to us:
1834 1834 # if the file has been changed after maxrev, we'll
1835 1835 # have linkrev(last) > maxrev, and we still need
1836 1836 # to explore the file graph
1837 1837 if rev not in ancestors:
1838 1838 continue
1839 1839 # XXX insert 1327 fix here
1840 1840 if flparentlinkrevs:
1841 1841 ancestors.update(flparentlinkrevs)
1842 1842
1843 1843 fncache.setdefault(rev, []).append(file_)
1844 1844 wanted.add(rev)
1845 1845 if copied:
1846 1846 copies.append(copied)
1847 1847
1848 1848 return wanted
1849 1849
1850 1850 class _followfilter(object):
1851 1851 def __init__(self, repo, onlyfirst=False):
1852 1852 self.repo = repo
1853 1853 self.startrev = nullrev
1854 1854 self.roots = set()
1855 1855 self.onlyfirst = onlyfirst
1856 1856
1857 1857 def match(self, rev):
1858 1858 def realparents(rev):
1859 1859 if self.onlyfirst:
1860 1860 return self.repo.changelog.parentrevs(rev)[0:1]
1861 1861 else:
1862 1862 return filter(lambda x: x != nullrev,
1863 1863 self.repo.changelog.parentrevs(rev))
1864 1864
1865 1865 if self.startrev == nullrev:
1866 1866 self.startrev = rev
1867 1867 return True
1868 1868
1869 1869 if rev > self.startrev:
1870 1870 # forward: all descendants
1871 1871 if not self.roots:
1872 1872 self.roots.add(self.startrev)
1873 1873 for parent in realparents(rev):
1874 1874 if parent in self.roots:
1875 1875 self.roots.add(rev)
1876 1876 return True
1877 1877 else:
1878 1878 # backwards: all parents
1879 1879 if not self.roots:
1880 1880 self.roots.update(realparents(self.startrev))
1881 1881 if rev in self.roots:
1882 1882 self.roots.remove(rev)
1883 1883 self.roots.update(realparents(rev))
1884 1884 return True
1885 1885
1886 1886 return False
1887 1887
1888 1888 def walkchangerevs(repo, match, opts, prepare):
1889 1889 '''Iterate over files and the revs in which they changed.
1890 1890
1891 1891 Callers most commonly need to iterate backwards over the history
1892 1892 in which they are interested. Doing so has awful (quadratic-looking)
1893 1893 performance, so we use iterators in a "windowed" way.
1894 1894
1895 1895 We walk a window of revisions in the desired order. Within the
1896 1896 window, we first walk forwards to gather data, then in the desired
1897 1897 order (usually backwards) to display it.
1898 1898
1899 1899 This function returns an iterator yielding contexts. Before
1900 1900 yielding each context, the iterator will first call the prepare
1901 1901 function on each context in the window in forward order.'''
1902 1902
1903 1903 allfiles = opts.get('all_files')
1904 1904 follow = opts.get('follow') or opts.get('follow_first')
1905 1905 revs = _walkrevs(repo, opts)
1906 1906 if not revs:
1907 1907 return []
1908 1908 wanted = set()
1909 1909 slowpath = match.anypats() or (not match.always() and opts.get('removed'))
1910 1910 fncache = {}
1911 1911 change = repo.__getitem__
1912 1912
1913 1913 # First step is to fill wanted, the set of revisions that we want to yield.
1914 1914 # When it does not induce extra cost, we also fill fncache for revisions in
1915 1915 # wanted: a cache of filenames that were changed (ctx.files()) and that
1916 1916 # match the file filtering conditions.
1917 1917
1918 1918 if match.always() or allfiles:
1919 1919 # No files, no patterns. Display all revs.
1920 1920 wanted = revs
1921 1921 elif not slowpath:
1922 1922 # We only have to read through the filelog to find wanted revisions
1923 1923
1924 1924 try:
1925 1925 wanted = walkfilerevs(repo, match, follow, revs, fncache)
1926 1926 except FileWalkError:
1927 1927 slowpath = True
1928 1928
1929 1929 # We decided to fall back to the slowpath because at least one
1930 1930 # of the paths was not a file. Check to see if at least one of them
1931 1931 # existed in history, otherwise simply return
1932 1932 for path in match.files():
1933 1933 if path == '.' or path in repo.store:
1934 1934 break
1935 1935 else:
1936 1936 return []
1937 1937
1938 1938 if slowpath:
1939 1939 # We have to read the changelog to match filenames against
1940 1940 # changed files
1941 1941
1942 1942 if follow:
1943 1943 raise error.Abort(_('can only follow copies/renames for explicit '
1944 1944 'filenames'))
1945 1945
1946 1946 # The slow path checks files modified in every changeset.
1947 1947 # This is really slow on large repos, so compute the set lazily.
1948 1948 class lazywantedset(object):
1949 1949 def __init__(self):
1950 1950 self.set = set()
1951 1951 self.revs = set(revs)
1952 1952
1953 1953 # No need to worry about locality here because it will be accessed
1954 1954 # in the same order as the increasing window below.
1955 1955 def __contains__(self, value):
1956 1956 if value in self.set:
1957 1957 return True
1958 1958 elif not value in self.revs:
1959 1959 return False
1960 1960 else:
1961 1961 self.revs.discard(value)
1962 1962 ctx = change(value)
1963 1963 matches = [f for f in ctx.files() if match(f)]
1964 1964 if matches:
1965 1965 fncache[value] = matches
1966 1966 self.set.add(value)
1967 1967 return True
1968 1968 return False
1969 1969
1970 1970 def discard(self, value):
1971 1971 self.revs.discard(value)
1972 1972 self.set.discard(value)
1973 1973
1974 1974 wanted = lazywantedset()
1975 1975
1976 1976 # it might be worthwhile to do this in the iterator if the rev range
1977 1977 # is descending and the prune args are all within that range
1978 1978 for rev in opts.get('prune', ()):
1979 1979 rev = repo[rev].rev()
1980 1980 ff = _followfilter(repo)
1981 1981 stop = min(revs[0], revs[-1])
1982 1982 for x in pycompat.xrange(rev, stop - 1, -1):
1983 1983 if ff.match(x):
1984 1984 wanted = wanted - [x]
1985 1985
1986 1986 # Now that wanted is correctly initialized, we can iterate over the
1987 1987 # revision range, yielding only revisions in wanted.
1988 1988 def iterate():
1989 1989 if follow and match.always():
1990 1990 ff = _followfilter(repo, onlyfirst=opts.get('follow_first'))
1991 1991 def want(rev):
1992 1992 return ff.match(rev) and rev in wanted
1993 1993 else:
1994 1994 def want(rev):
1995 1995 return rev in wanted
1996 1996
1997 1997 it = iter(revs)
1998 1998 stopiteration = False
1999 1999 for windowsize in increasingwindows():
2000 2000 nrevs = []
2001 2001 for i in pycompat.xrange(windowsize):
2002 2002 rev = next(it, None)
2003 2003 if rev is None:
2004 2004 stopiteration = True
2005 2005 break
2006 2006 elif want(rev):
2007 2007 nrevs.append(rev)
2008 2008 for rev in sorted(nrevs):
2009 2009 fns = fncache.get(rev)
2010 2010 ctx = change(rev)
2011 2011 if not fns:
2012 2012 def fns_generator():
2013 2013 if allfiles:
2014 2014 fiter = iter(ctx)
2015 2015 else:
2016 2016 fiter = ctx.files()
2017 2017 for f in fiter:
2018 2018 if match(f):
2019 2019 yield f
2020 2020 fns = fns_generator()
2021 2021 prepare(ctx, fns)
2022 2022 for rev in nrevs:
2023 2023 yield change(rev)
2024 2024
2025 2025 if stopiteration:
2026 2026 break
2027 2027
2028 2028 return iterate()
2029 2029
2030 2030 def add(ui, repo, match, prefix, uipathfn, explicitonly, **opts):
2031 2031 bad = []
2032 2032
2033 2033 badfn = lambda x, y: bad.append(x) or match.bad(x, y)
2034 2034 names = []
2035 2035 wctx = repo[None]
2036 2036 cca = None
2037 2037 abort, warn = scmutil.checkportabilityalert(ui)
2038 2038 if abort or warn:
2039 2039 cca = scmutil.casecollisionauditor(ui, abort, repo.dirstate)
2040 2040
2041 2041 match = repo.narrowmatch(match, includeexact=True)
2042 2042 badmatch = matchmod.badmatch(match, badfn)
2043 2043 dirstate = repo.dirstate
2044 2044 # We don't want to just call wctx.walk here, since it would return a lot of
2045 2045 # clean files, which we aren't interested in and takes time.
2046 2046 for f in sorted(dirstate.walk(badmatch, subrepos=sorted(wctx.substate),
2047 2047 unknown=True, ignored=False, full=False)):
2048 2048 exact = match.exact(f)
2049 2049 if exact or not explicitonly and f not in wctx and repo.wvfs.lexists(f):
2050 2050 if cca:
2051 2051 cca(f)
2052 2052 names.append(f)
2053 2053 if ui.verbose or not exact:
2054 2054 ui.status(_('adding %s\n') % uipathfn(f),
2055 2055 label='ui.addremove.added')
2056 2056
2057 2057 for subpath in sorted(wctx.substate):
2058 2058 sub = wctx.sub(subpath)
2059 2059 try:
2060 2060 submatch = matchmod.subdirmatcher(subpath, match)
2061 2061 subprefix = repo.wvfs.reljoin(prefix, subpath)
2062 2062 subuipathfn = scmutil.subdiruipathfn(subpath, uipathfn)
2063 2063 if opts.get(r'subrepos'):
2064 2064 bad.extend(sub.add(ui, submatch, subprefix, subuipathfn, False,
2065 2065 **opts))
2066 2066 else:
2067 2067 bad.extend(sub.add(ui, submatch, subprefix, subuipathfn, True,
2068 2068 **opts))
2069 2069 except error.LookupError:
2070 2070 ui.status(_("skipping missing subrepository: %s\n")
2071 2071 % uipathfn(subpath))
2072 2072
2073 2073 if not opts.get(r'dry_run'):
2074 2074 rejected = wctx.add(names, prefix)
2075 2075 bad.extend(f for f in rejected if f in match.files())
2076 2076 return bad
2077 2077
2078 2078 def addwebdirpath(repo, serverpath, webconf):
2079 2079 webconf[serverpath] = repo.root
2080 2080 repo.ui.debug('adding %s = %s\n' % (serverpath, repo.root))
2081 2081
2082 2082 for r in repo.revs('filelog("path:.hgsub")'):
2083 2083 ctx = repo[r]
2084 2084 for subpath in ctx.substate:
2085 2085 ctx.sub(subpath).addwebdirpath(serverpath, webconf)
2086 2086
2087 def forget(ui, repo, match, prefix, explicitonly, dryrun, interactive):
2087 def forget(ui, repo, match, prefix, uipathfn, explicitonly, dryrun,
2088 interactive):
2088 2089 if dryrun and interactive:
2089 2090 raise error.Abort(_("cannot specify both --dry-run and --interactive"))
2090 2091 bad = []
2091 2092 badfn = lambda x, y: bad.append(x) or match.bad(x, y)
2092 2093 wctx = repo[None]
2093 2094 forgot = []
2094 2095
2095 2096 s = repo.status(match=matchmod.badmatch(match, badfn), clean=True)
2096 2097 forget = sorted(s.modified + s.added + s.deleted + s.clean)
2097 2098 if explicitonly:
2098 2099 forget = [f for f in forget if match.exact(f)]
2099 2100
2100 2101 for subpath in sorted(wctx.substate):
2101 2102 sub = wctx.sub(subpath)
2102 2103 submatch = matchmod.subdirmatcher(subpath, match)
2103 2104 subprefix = repo.wvfs.reljoin(prefix, subpath)
2105 subuipathfn = scmutil.subdiruipathfn(subpath, uipathfn)
2104 2106 try:
2105 subbad, subforgot = sub.forget(submatch, subprefix, dryrun=dryrun,
2107 subbad, subforgot = sub.forget(submatch, subprefix, subuipathfn,
2108 dryrun=dryrun,
2106 2109 interactive=interactive)
2107 2110 bad.extend([subpath + '/' + f for f in subbad])
2108 2111 forgot.extend([subpath + '/' + f for f in subforgot])
2109 2112 except error.LookupError:
2110 2113 ui.status(_("skipping missing subrepository: %s\n")
2111 % match.rel(subpath))
2114 % uipathfn(subpath))
2112 2115
2113 2116 if not explicitonly:
2114 2117 for f in match.files():
2115 2118 if f not in repo.dirstate and not repo.wvfs.isdir(f):
2116 2119 if f not in forgot:
2117 2120 if repo.wvfs.exists(f):
2118 2121 # Don't complain if the exact case match wasn't given.
2119 2122 # But don't do this until after checking 'forgot', so
2120 2123 # that subrepo files aren't normalized, and this op is
2121 2124 # purely from data cached by the status walk above.
2122 2125 if repo.dirstate.normalize(f) in repo.dirstate:
2123 2126 continue
2124 2127 ui.warn(_('not removing %s: '
2125 2128 'file is already untracked\n')
2126 % match.rel(f))
2129 % uipathfn(f))
2127 2130 bad.append(f)
2128 2131
2129 2132 if interactive:
2130 2133 responses = _('[Ynsa?]'
2131 2134 '$$ &Yes, forget this file'
2132 2135 '$$ &No, skip this file'
2133 2136 '$$ &Skip remaining files'
2134 2137 '$$ Include &all remaining files'
2135 2138 '$$ &? (display help)')
2136 2139 for filename in forget[:]:
2137 2140 r = ui.promptchoice(_('forget %s %s') % (filename, responses))
2138 2141 if r == 4: # ?
2139 2142 while r == 4:
2140 2143 for c, t in ui.extractchoices(responses)[1]:
2141 2144 ui.write('%s - %s\n' % (c, encoding.lower(t)))
2142 2145 r = ui.promptchoice(_('forget %s %s') % (filename,
2143 2146 responses))
2144 2147 if r == 0: # yes
2145 2148 continue
2146 2149 elif r == 1: # no
2147 2150 forget.remove(filename)
2148 2151 elif r == 2: # Skip
2149 2152 fnindex = forget.index(filename)
2150 2153 del forget[fnindex:]
2151 2154 break
2152 2155 elif r == 3: # All
2153 2156 break
2154 2157
2155 2158 for f in forget:
2156 2159 if ui.verbose or not match.exact(f) or interactive:
2157 ui.status(_('removing %s\n') % match.rel(f),
2160 ui.status(_('removing %s\n') % uipathfn(f),
2158 2161 label='ui.addremove.removed')
2159 2162
2160 2163 if not dryrun:
2161 2164 rejected = wctx.forget(forget, prefix)
2162 2165 bad.extend(f for f in rejected if f in match.files())
2163 2166 forgot.extend(f for f in forget if f not in rejected)
2164 2167 return bad, forgot
2165 2168
2166 2169 def files(ui, ctx, m, fm, fmt, subrepos):
2167 2170 ret = 1
2168 2171
2169 2172 needsfctx = ui.verbose or {'size', 'flags'} & fm.datahint()
2170 2173 uipathfn = scmutil.getuipathfn(ctx.repo(), legacyrelativevalue=True)
2171 2174 for f in ctx.matches(m):
2172 2175 fm.startitem()
2173 2176 fm.context(ctx=ctx)
2174 2177 if needsfctx:
2175 2178 fc = ctx[f]
2176 2179 fm.write('size flags', '% 10d % 1s ', fc.size(), fc.flags())
2177 2180 fm.data(path=f)
2178 2181 fm.plain(fmt % uipathfn(f))
2179 2182 ret = 0
2180 2183
2181 2184 for subpath in sorted(ctx.substate):
2182 2185 submatch = matchmod.subdirmatcher(subpath, m)
2183 2186 if (subrepos or m.exact(subpath) or any(submatch.files())):
2184 2187 sub = ctx.sub(subpath)
2185 2188 try:
2186 2189 recurse = m.exact(subpath) or subrepos
2187 2190 if sub.printfiles(ui, submatch, fm, fmt, recurse) == 0:
2188 2191 ret = 0
2189 2192 except error.LookupError:
2190 2193 ui.status(_("skipping missing subrepository: %s\n")
2191 2194 % m.rel(subpath))
2192 2195
2193 2196 return ret
2194 2197
2195 2198 def remove(ui, repo, m, prefix, uipathfn, after, force, subrepos, dryrun,
2196 2199 warnings=None):
2197 2200 ret = 0
2198 2201 s = repo.status(match=m, clean=True)
2199 2202 modified, added, deleted, clean = s[0], s[1], s[3], s[6]
2200 2203
2201 2204 wctx = repo[None]
2202 2205
2203 2206 if warnings is None:
2204 2207 warnings = []
2205 2208 warn = True
2206 2209 else:
2207 2210 warn = False
2208 2211
2209 2212 subs = sorted(wctx.substate)
2210 2213 progress = ui.makeprogress(_('searching'), total=len(subs),
2211 2214 unit=_('subrepos'))
2212 2215 for subpath in subs:
2213 2216 submatch = matchmod.subdirmatcher(subpath, m)
2214 2217 subprefix = repo.wvfs.reljoin(prefix, subpath)
2215 2218 subuipathfn = scmutil.subdiruipathfn(subpath, uipathfn)
2216 2219 if subrepos or m.exact(subpath) or any(submatch.files()):
2217 2220 progress.increment()
2218 2221 sub = wctx.sub(subpath)
2219 2222 try:
2220 2223 if sub.removefiles(submatch, subprefix, subuipathfn, after,
2221 2224 force, subrepos, dryrun, warnings):
2222 2225 ret = 1
2223 2226 except error.LookupError:
2224 2227 warnings.append(_("skipping missing subrepository: %s\n")
2225 2228 % uipathfn(subpath))
2226 2229 progress.complete()
2227 2230
2228 2231 # warn about failure to delete explicit files/dirs
2229 2232 deleteddirs = util.dirs(deleted)
2230 2233 files = m.files()
2231 2234 progress = ui.makeprogress(_('deleting'), total=len(files),
2232 2235 unit=_('files'))
2233 2236 for f in files:
2234 2237 def insubrepo():
2235 2238 for subpath in wctx.substate:
2236 2239 if f.startswith(subpath + '/'):
2237 2240 return True
2238 2241 return False
2239 2242
2240 2243 progress.increment()
2241 2244 isdir = f in deleteddirs or wctx.hasdir(f)
2242 2245 if (f in repo.dirstate or isdir or f == '.'
2243 2246 or insubrepo() or f in subs):
2244 2247 continue
2245 2248
2246 2249 if repo.wvfs.exists(f):
2247 2250 if repo.wvfs.isdir(f):
2248 2251 warnings.append(_('not removing %s: no tracked files\n')
2249 2252 % uipathfn(f))
2250 2253 else:
2251 2254 warnings.append(_('not removing %s: file is untracked\n')
2252 2255 % uipathfn(f))
2253 2256 # missing files will generate a warning elsewhere
2254 2257 ret = 1
2255 2258 progress.complete()
2256 2259
2257 2260 if force:
2258 2261 list = modified + deleted + clean + added
2259 2262 elif after:
2260 2263 list = deleted
2261 2264 remaining = modified + added + clean
2262 2265 progress = ui.makeprogress(_('skipping'), total=len(remaining),
2263 2266 unit=_('files'))
2264 2267 for f in remaining:
2265 2268 progress.increment()
2266 2269 if ui.verbose or (f in files):
2267 2270 warnings.append(_('not removing %s: file still exists\n')
2268 2271 % uipathfn(f))
2269 2272 ret = 1
2270 2273 progress.complete()
2271 2274 else:
2272 2275 list = deleted + clean
2273 2276 progress = ui.makeprogress(_('skipping'),
2274 2277 total=(len(modified) + len(added)),
2275 2278 unit=_('files'))
2276 2279 for f in modified:
2277 2280 progress.increment()
2278 2281 warnings.append(_('not removing %s: file is modified (use -f'
2279 2282 ' to force removal)\n') % uipathfn(f))
2280 2283 ret = 1
2281 2284 for f in added:
2282 2285 progress.increment()
2283 2286 warnings.append(_("not removing %s: file has been marked for add"
2284 2287 " (use 'hg forget' to undo add)\n") % uipathfn(f))
2285 2288 ret = 1
2286 2289 progress.complete()
2287 2290
2288 2291 list = sorted(list)
2289 2292 progress = ui.makeprogress(_('deleting'), total=len(list),
2290 2293 unit=_('files'))
2291 2294 for f in list:
2292 2295 if ui.verbose or not m.exact(f):
2293 2296 progress.increment()
2294 2297 ui.status(_('removing %s\n') % uipathfn(f),
2295 2298 label='ui.addremove.removed')
2296 2299 progress.complete()
2297 2300
2298 2301 if not dryrun:
2299 2302 with repo.wlock():
2300 2303 if not after:
2301 2304 for f in list:
2302 2305 if f in added:
2303 2306 continue # we never unlink added files on remove
2304 2307 rmdir = repo.ui.configbool('experimental',
2305 2308 'removeemptydirs')
2306 2309 repo.wvfs.unlinkpath(f, ignoremissing=True, rmdir=rmdir)
2307 2310 repo[None].forget(list)
2308 2311
2309 2312 if warn:
2310 2313 for warning in warnings:
2311 2314 ui.warn(warning)
2312 2315
2313 2316 return ret
2314 2317
2315 2318 def _updatecatformatter(fm, ctx, matcher, path, decode):
2316 2319 """Hook for adding data to the formatter used by ``hg cat``.
2317 2320
2318 2321 Extensions (e.g., lfs) can wrap this to inject keywords/data, but must call
2319 2322 this method first."""
2320 2323 data = ctx[path].data()
2321 2324 if decode:
2322 2325 data = ctx.repo().wwritedata(path, data)
2323 2326 fm.startitem()
2324 2327 fm.context(ctx=ctx)
2325 2328 fm.write('data', '%s', data)
2326 2329 fm.data(path=path)
2327 2330
2328 2331 def cat(ui, repo, ctx, matcher, basefm, fntemplate, prefix, **opts):
2329 2332 err = 1
2330 2333 opts = pycompat.byteskwargs(opts)
2331 2334
2332 2335 def write(path):
2333 2336 filename = None
2334 2337 if fntemplate:
2335 2338 filename = makefilename(ctx, fntemplate,
2336 2339 pathname=os.path.join(prefix, path))
2337 2340 # attempt to create the directory if it does not already exist
2338 2341 try:
2339 2342 os.makedirs(os.path.dirname(filename))
2340 2343 except OSError:
2341 2344 pass
2342 2345 with formatter.maybereopen(basefm, filename) as fm:
2343 2346 _updatecatformatter(fm, ctx, matcher, path, opts.get('decode'))
2344 2347
2345 2348 # Automation often uses hg cat on single files, so special case it
2346 2349 # for performance to avoid the cost of parsing the manifest.
2347 2350 if len(matcher.files()) == 1 and not matcher.anypats():
2348 2351 file = matcher.files()[0]
2349 2352 mfl = repo.manifestlog
2350 2353 mfnode = ctx.manifestnode()
2351 2354 try:
2352 2355 if mfnode and mfl[mfnode].find(file)[0]:
2353 2356 scmutil.prefetchfiles(repo, [ctx.rev()], matcher)
2354 2357 write(file)
2355 2358 return 0
2356 2359 except KeyError:
2357 2360 pass
2358 2361
2359 2362 scmutil.prefetchfiles(repo, [ctx.rev()], matcher)
2360 2363
2361 2364 for abs in ctx.walk(matcher):
2362 2365 write(abs)
2363 2366 err = 0
2364 2367
2365 2368 for subpath in sorted(ctx.substate):
2366 2369 sub = ctx.sub(subpath)
2367 2370 try:
2368 2371 submatch = matchmod.subdirmatcher(subpath, matcher)
2369 2372 subprefix = os.path.join(prefix, subpath)
2370 2373 if not sub.cat(submatch, basefm, fntemplate, subprefix,
2371 2374 **pycompat.strkwargs(opts)):
2372 2375 err = 0
2373 2376 except error.RepoLookupError:
2374 2377 ui.status(_("skipping missing subrepository: %s\n") %
2375 2378 matcher.rel(subpath))
2376 2379
2377 2380 return err
2378 2381
2379 2382 def commit(ui, repo, commitfunc, pats, opts):
2380 2383 '''commit the specified files or all outstanding changes'''
2381 2384 date = opts.get('date')
2382 2385 if date:
2383 2386 opts['date'] = dateutil.parsedate(date)
2384 2387 message = logmessage(ui, opts)
2385 2388 matcher = scmutil.match(repo[None], pats, opts)
2386 2389
2387 2390 dsguard = None
2388 2391 # extract addremove carefully -- this function can be called from a command
2389 2392 # that doesn't support addremove
2390 2393 if opts.get('addremove'):
2391 2394 dsguard = dirstateguard.dirstateguard(repo, 'commit')
2392 2395 with dsguard or util.nullcontextmanager():
2393 2396 if dsguard:
2394 2397 relative = scmutil.anypats(pats, opts)
2395 2398 uipathfn = scmutil.getuipathfn(repo, forcerelativevalue=relative)
2396 2399 if scmutil.addremove(repo, matcher, "", uipathfn, opts) != 0:
2397 2400 raise error.Abort(
2398 2401 _("failed to mark all new/missing files as added/removed"))
2399 2402
2400 2403 return commitfunc(ui, repo, message, matcher, opts)
2401 2404
2402 2405 def samefile(f, ctx1, ctx2):
2403 2406 if f in ctx1.manifest():
2404 2407 a = ctx1.filectx(f)
2405 2408 if f in ctx2.manifest():
2406 2409 b = ctx2.filectx(f)
2407 2410 return (not a.cmp(b)
2408 2411 and a.flags() == b.flags())
2409 2412 else:
2410 2413 return False
2411 2414 else:
2412 2415 return f not in ctx2.manifest()
2413 2416
2414 2417 def amend(ui, repo, old, extra, pats, opts):
2415 2418 # avoid cycle context -> subrepo -> cmdutil
2416 2419 from . import context
2417 2420
2418 2421 # amend will reuse the existing user if not specified, but the obsolete
2419 2422 # marker creation requires that the current user's name is specified.
2420 2423 if obsolete.isenabled(repo, obsolete.createmarkersopt):
2421 2424 ui.username() # raise exception if username not set
2422 2425
2423 2426 ui.note(_('amending changeset %s\n') % old)
2424 2427 base = old.p1()
2425 2428
2426 2429 with repo.wlock(), repo.lock(), repo.transaction('amend'):
2427 2430 # Participating changesets:
2428 2431 #
2429 2432 # wctx o - workingctx that contains changes from working copy
2430 2433 # | to go into amending commit
2431 2434 # |
2432 2435 # old o - changeset to amend
2433 2436 # |
2434 2437 # base o - first parent of the changeset to amend
2435 2438 wctx = repo[None]
2436 2439
2437 2440 # Copy to avoid mutating input
2438 2441 extra = extra.copy()
2439 2442 # Update extra dict from amended commit (e.g. to preserve graft
2440 2443 # source)
2441 2444 extra.update(old.extra())
2442 2445
2443 2446 # Also update it from the from the wctx
2444 2447 extra.update(wctx.extra())
2445 2448
2446 2449 user = opts.get('user') or old.user()
2447 2450
2448 2451 datemaydiffer = False # date-only change should be ignored?
2449 2452 if opts.get('date') and opts.get('currentdate'):
2450 2453 raise error.Abort(_('--date and --currentdate are mutually '
2451 2454 'exclusive'))
2452 2455 if opts.get('date'):
2453 2456 date = dateutil.parsedate(opts.get('date'))
2454 2457 elif opts.get('currentdate'):
2455 2458 date = dateutil.makedate()
2456 2459 elif (ui.configbool('rewrite', 'update-timestamp')
2457 2460 and opts.get('currentdate') is None):
2458 2461 date = dateutil.makedate()
2459 2462 datemaydiffer = True
2460 2463 else:
2461 2464 date = old.date()
2462 2465
2463 2466 if len(old.parents()) > 1:
2464 2467 # ctx.files() isn't reliable for merges, so fall back to the
2465 2468 # slower repo.status() method
2466 2469 files = set([fn for st in base.status(old)[:3]
2467 2470 for fn in st])
2468 2471 else:
2469 2472 files = set(old.files())
2470 2473
2471 2474 # add/remove the files to the working copy if the "addremove" option
2472 2475 # was specified.
2473 2476 matcher = scmutil.match(wctx, pats, opts)
2474 2477 relative = scmutil.anypats(pats, opts)
2475 2478 uipathfn = scmutil.getuipathfn(repo, forcerelativevalue=relative)
2476 2479 if (opts.get('addremove')
2477 2480 and scmutil.addremove(repo, matcher, "", uipathfn, opts)):
2478 2481 raise error.Abort(
2479 2482 _("failed to mark all new/missing files as added/removed"))
2480 2483
2481 2484 # Check subrepos. This depends on in-place wctx._status update in
2482 2485 # subrepo.precommit(). To minimize the risk of this hack, we do
2483 2486 # nothing if .hgsub does not exist.
2484 2487 if '.hgsub' in wctx or '.hgsub' in old:
2485 2488 subs, commitsubs, newsubstate = subrepoutil.precommit(
2486 2489 ui, wctx, wctx._status, matcher)
2487 2490 # amend should abort if commitsubrepos is enabled
2488 2491 assert not commitsubs
2489 2492 if subs:
2490 2493 subrepoutil.writestate(repo, newsubstate)
2491 2494
2492 2495 ms = mergemod.mergestate.read(repo)
2493 2496 mergeutil.checkunresolved(ms)
2494 2497
2495 2498 filestoamend = set(f for f in wctx.files() if matcher(f))
2496 2499
2497 2500 changes = (len(filestoamend) > 0)
2498 2501 if changes:
2499 2502 # Recompute copies (avoid recording a -> b -> a)
2500 2503 copied = copies.pathcopies(base, wctx, matcher)
2501 2504 if old.p2:
2502 2505 copied.update(copies.pathcopies(old.p2(), wctx, matcher))
2503 2506
2504 2507 # Prune files which were reverted by the updates: if old
2505 2508 # introduced file X and the file was renamed in the working
2506 2509 # copy, then those two files are the same and
2507 2510 # we can discard X from our list of files. Likewise if X
2508 2511 # was removed, it's no longer relevant. If X is missing (aka
2509 2512 # deleted), old X must be preserved.
2510 2513 files.update(filestoamend)
2511 2514 files = [f for f in files if (not samefile(f, wctx, base)
2512 2515 or f in wctx.deleted())]
2513 2516
2514 2517 def filectxfn(repo, ctx_, path):
2515 2518 try:
2516 2519 # If the file being considered is not amongst the files
2517 2520 # to be amended, we should return the file context from the
2518 2521 # old changeset. This avoids issues when only some files in
2519 2522 # the working copy are being amended but there are also
2520 2523 # changes to other files from the old changeset.
2521 2524 if path not in filestoamend:
2522 2525 return old.filectx(path)
2523 2526
2524 2527 # Return None for removed files.
2525 2528 if path in wctx.removed():
2526 2529 return None
2527 2530
2528 2531 fctx = wctx[path]
2529 2532 flags = fctx.flags()
2530 2533 mctx = context.memfilectx(repo, ctx_,
2531 2534 fctx.path(), fctx.data(),
2532 2535 islink='l' in flags,
2533 2536 isexec='x' in flags,
2534 2537 copied=copied.get(path))
2535 2538 return mctx
2536 2539 except KeyError:
2537 2540 return None
2538 2541 else:
2539 2542 ui.note(_('copying changeset %s to %s\n') % (old, base))
2540 2543
2541 2544 # Use version of files as in the old cset
2542 2545 def filectxfn(repo, ctx_, path):
2543 2546 try:
2544 2547 return old.filectx(path)
2545 2548 except KeyError:
2546 2549 return None
2547 2550
2548 2551 # See if we got a message from -m or -l, if not, open the editor with
2549 2552 # the message of the changeset to amend.
2550 2553 message = logmessage(ui, opts)
2551 2554
2552 2555 editform = mergeeditform(old, 'commit.amend')
2553 2556 editor = getcommiteditor(editform=editform,
2554 2557 **pycompat.strkwargs(opts))
2555 2558
2556 2559 if not message:
2557 2560 editor = getcommiteditor(edit=True, editform=editform)
2558 2561 message = old.description()
2559 2562
2560 2563 pureextra = extra.copy()
2561 2564 extra['amend_source'] = old.hex()
2562 2565
2563 2566 new = context.memctx(repo,
2564 2567 parents=[base.node(), old.p2().node()],
2565 2568 text=message,
2566 2569 files=files,
2567 2570 filectxfn=filectxfn,
2568 2571 user=user,
2569 2572 date=date,
2570 2573 extra=extra,
2571 2574 editor=editor)
2572 2575
2573 2576 newdesc = changelog.stripdesc(new.description())
2574 2577 if ((not changes)
2575 2578 and newdesc == old.description()
2576 2579 and user == old.user()
2577 2580 and (date == old.date() or datemaydiffer)
2578 2581 and pureextra == old.extra()):
2579 2582 # nothing changed. continuing here would create a new node
2580 2583 # anyway because of the amend_source noise.
2581 2584 #
2582 2585 # This not what we expect from amend.
2583 2586 return old.node()
2584 2587
2585 2588 commitphase = None
2586 2589 if opts.get('secret'):
2587 2590 commitphase = phases.secret
2588 2591 newid = repo.commitctx(new)
2589 2592
2590 2593 # Reroute the working copy parent to the new changeset
2591 2594 repo.setparents(newid, nullid)
2592 2595 mapping = {old.node(): (newid,)}
2593 2596 obsmetadata = None
2594 2597 if opts.get('note'):
2595 2598 obsmetadata = {'note': encoding.fromlocal(opts['note'])}
2596 2599 backup = ui.configbool('rewrite', 'backup-bundle')
2597 2600 scmutil.cleanupnodes(repo, mapping, 'amend', metadata=obsmetadata,
2598 2601 fixphase=True, targetphase=commitphase,
2599 2602 backup=backup)
2600 2603
2601 2604 # Fixing the dirstate because localrepo.commitctx does not update
2602 2605 # it. This is rather convenient because we did not need to update
2603 2606 # the dirstate for all the files in the new commit which commitctx
2604 2607 # could have done if it updated the dirstate. Now, we can
2605 2608 # selectively update the dirstate only for the amended files.
2606 2609 dirstate = repo.dirstate
2607 2610
2608 2611 # Update the state of the files which were added and
2609 2612 # and modified in the amend to "normal" in the dirstate.
2610 2613 normalfiles = set(wctx.modified() + wctx.added()) & filestoamend
2611 2614 for f in normalfiles:
2612 2615 dirstate.normal(f)
2613 2616
2614 2617 # Update the state of files which were removed in the amend
2615 2618 # to "removed" in the dirstate.
2616 2619 removedfiles = set(wctx.removed()) & filestoamend
2617 2620 for f in removedfiles:
2618 2621 dirstate.drop(f)
2619 2622
2620 2623 return newid
2621 2624
2622 2625 def commiteditor(repo, ctx, subs, editform=''):
2623 2626 if ctx.description():
2624 2627 return ctx.description()
2625 2628 return commitforceeditor(repo, ctx, subs, editform=editform,
2626 2629 unchangedmessagedetection=True)
2627 2630
2628 2631 def commitforceeditor(repo, ctx, subs, finishdesc=None, extramsg=None,
2629 2632 editform='', unchangedmessagedetection=False):
2630 2633 if not extramsg:
2631 2634 extramsg = _("Leave message empty to abort commit.")
2632 2635
2633 2636 forms = [e for e in editform.split('.') if e]
2634 2637 forms.insert(0, 'changeset')
2635 2638 templatetext = None
2636 2639 while forms:
2637 2640 ref = '.'.join(forms)
2638 2641 if repo.ui.config('committemplate', ref):
2639 2642 templatetext = committext = buildcommittemplate(
2640 2643 repo, ctx, subs, extramsg, ref)
2641 2644 break
2642 2645 forms.pop()
2643 2646 else:
2644 2647 committext = buildcommittext(repo, ctx, subs, extramsg)
2645 2648
2646 2649 # run editor in the repository root
2647 2650 olddir = encoding.getcwd()
2648 2651 os.chdir(repo.root)
2649 2652
2650 2653 # make in-memory changes visible to external process
2651 2654 tr = repo.currenttransaction()
2652 2655 repo.dirstate.write(tr)
2653 2656 pending = tr and tr.writepending() and repo.root
2654 2657
2655 2658 editortext = repo.ui.edit(committext, ctx.user(), ctx.extra(),
2656 2659 editform=editform, pending=pending,
2657 2660 repopath=repo.path, action='commit')
2658 2661 text = editortext
2659 2662
2660 2663 # strip away anything below this special string (used for editors that want
2661 2664 # to display the diff)
2662 2665 stripbelow = re.search(_linebelow, text, flags=re.MULTILINE)
2663 2666 if stripbelow:
2664 2667 text = text[:stripbelow.start()]
2665 2668
2666 2669 text = re.sub("(?m)^HG:.*(\n|$)", "", text)
2667 2670 os.chdir(olddir)
2668 2671
2669 2672 if finishdesc:
2670 2673 text = finishdesc(text)
2671 2674 if not text.strip():
2672 2675 raise error.Abort(_("empty commit message"))
2673 2676 if unchangedmessagedetection and editortext == templatetext:
2674 2677 raise error.Abort(_("commit message unchanged"))
2675 2678
2676 2679 return text
2677 2680
2678 2681 def buildcommittemplate(repo, ctx, subs, extramsg, ref):
2679 2682 ui = repo.ui
2680 2683 spec = formatter.templatespec(ref, None, None)
2681 2684 t = logcmdutil.changesettemplater(ui, repo, spec)
2682 2685 t.t.cache.update((k, templater.unquotestring(v))
2683 2686 for k, v in repo.ui.configitems('committemplate'))
2684 2687
2685 2688 if not extramsg:
2686 2689 extramsg = '' # ensure that extramsg is string
2687 2690
2688 2691 ui.pushbuffer()
2689 2692 t.show(ctx, extramsg=extramsg)
2690 2693 return ui.popbuffer()
2691 2694
2692 2695 def hgprefix(msg):
2693 2696 return "\n".join(["HG: %s" % a for a in msg.split("\n") if a])
2694 2697
2695 2698 def buildcommittext(repo, ctx, subs, extramsg):
2696 2699 edittext = []
2697 2700 modified, added, removed = ctx.modified(), ctx.added(), ctx.removed()
2698 2701 if ctx.description():
2699 2702 edittext.append(ctx.description())
2700 2703 edittext.append("")
2701 2704 edittext.append("") # Empty line between message and comments.
2702 2705 edittext.append(hgprefix(_("Enter commit message."
2703 2706 " Lines beginning with 'HG:' are removed.")))
2704 2707 edittext.append(hgprefix(extramsg))
2705 2708 edittext.append("HG: --")
2706 2709 edittext.append(hgprefix(_("user: %s") % ctx.user()))
2707 2710 if ctx.p2():
2708 2711 edittext.append(hgprefix(_("branch merge")))
2709 2712 if ctx.branch():
2710 2713 edittext.append(hgprefix(_("branch '%s'") % ctx.branch()))
2711 2714 if bookmarks.isactivewdirparent(repo):
2712 2715 edittext.append(hgprefix(_("bookmark '%s'") % repo._activebookmark))
2713 2716 edittext.extend([hgprefix(_("subrepo %s") % s) for s in subs])
2714 2717 edittext.extend([hgprefix(_("added %s") % f) for f in added])
2715 2718 edittext.extend([hgprefix(_("changed %s") % f) for f in modified])
2716 2719 edittext.extend([hgprefix(_("removed %s") % f) for f in removed])
2717 2720 if not added and not modified and not removed:
2718 2721 edittext.append(hgprefix(_("no files changed")))
2719 2722 edittext.append("")
2720 2723
2721 2724 return "\n".join(edittext)
2722 2725
2723 2726 def commitstatus(repo, node, branch, bheads=None, opts=None):
2724 2727 if opts is None:
2725 2728 opts = {}
2726 2729 ctx = repo[node]
2727 2730 parents = ctx.parents()
2728 2731
2729 2732 if (not opts.get('amend') and bheads and node not in bheads and not
2730 2733 [x for x in parents if x.node() in bheads and x.branch() == branch]):
2731 2734 repo.ui.status(_('created new head\n'))
2732 2735 # The message is not printed for initial roots. For the other
2733 2736 # changesets, it is printed in the following situations:
2734 2737 #
2735 2738 # Par column: for the 2 parents with ...
2736 2739 # N: null or no parent
2737 2740 # B: parent is on another named branch
2738 2741 # C: parent is a regular non head changeset
2739 2742 # H: parent was a branch head of the current branch
2740 2743 # Msg column: whether we print "created new head" message
2741 2744 # In the following, it is assumed that there already exists some
2742 2745 # initial branch heads of the current branch, otherwise nothing is
2743 2746 # printed anyway.
2744 2747 #
2745 2748 # Par Msg Comment
2746 2749 # N N y additional topo root
2747 2750 #
2748 2751 # B N y additional branch root
2749 2752 # C N y additional topo head
2750 2753 # H N n usual case
2751 2754 #
2752 2755 # B B y weird additional branch root
2753 2756 # C B y branch merge
2754 2757 # H B n merge with named branch
2755 2758 #
2756 2759 # C C y additional head from merge
2757 2760 # C H n merge with a head
2758 2761 #
2759 2762 # H H n head merge: head count decreases
2760 2763
2761 2764 if not opts.get('close_branch'):
2762 2765 for r in parents:
2763 2766 if r.closesbranch() and r.branch() == branch:
2764 2767 repo.ui.status(_('reopening closed branch head %d\n') % r.rev())
2765 2768
2766 2769 if repo.ui.debugflag:
2767 2770 repo.ui.write(_('committed changeset %d:%s\n') % (ctx.rev(), ctx.hex()))
2768 2771 elif repo.ui.verbose:
2769 2772 repo.ui.write(_('committed changeset %d:%s\n') % (ctx.rev(), ctx))
2770 2773
2771 2774 def postcommitstatus(repo, pats, opts):
2772 2775 return repo.status(match=scmutil.match(repo[None], pats, opts))
2773 2776
2774 2777 def revert(ui, repo, ctx, parents, *pats, **opts):
2775 2778 opts = pycompat.byteskwargs(opts)
2776 2779 parent, p2 = parents
2777 2780 node = ctx.node()
2778 2781
2779 2782 mf = ctx.manifest()
2780 2783 if node == p2:
2781 2784 parent = p2
2782 2785
2783 2786 # need all matching names in dirstate and manifest of target rev,
2784 2787 # so have to walk both. do not print errors if files exist in one
2785 2788 # but not other. in both cases, filesets should be evaluated against
2786 2789 # workingctx to get consistent result (issue4497). this means 'set:**'
2787 2790 # cannot be used to select missing files from target rev.
2788 2791
2789 2792 # `names` is a mapping for all elements in working copy and target revision
2790 2793 # The mapping is in the form:
2791 2794 # <abs path in repo> -> (<path from CWD>, <exactly specified by matcher?>)
2792 2795 names = {}
2793 2796 uipathfn = scmutil.getuipathfn(repo, legacyrelativevalue=True)
2794 2797
2795 2798 with repo.wlock():
2796 2799 ## filling of the `names` mapping
2797 2800 # walk dirstate to fill `names`
2798 2801
2799 2802 interactive = opts.get('interactive', False)
2800 2803 wctx = repo[None]
2801 2804 m = scmutil.match(wctx, pats, opts)
2802 2805
2803 2806 # we'll need this later
2804 2807 targetsubs = sorted(s for s in wctx.substate if m(s))
2805 2808
2806 2809 if not m.always():
2807 2810 matcher = matchmod.badmatch(m, lambda x, y: False)
2808 2811 for abs in wctx.walk(matcher):
2809 2812 names[abs] = m.exact(abs)
2810 2813
2811 2814 # walk target manifest to fill `names`
2812 2815
2813 2816 def badfn(path, msg):
2814 2817 if path in names:
2815 2818 return
2816 2819 if path in ctx.substate:
2817 2820 return
2818 2821 path_ = path + '/'
2819 2822 for f in names:
2820 2823 if f.startswith(path_):
2821 2824 return
2822 2825 ui.warn("%s: %s\n" % (m.rel(path), msg))
2823 2826
2824 2827 for abs in ctx.walk(matchmod.badmatch(m, badfn)):
2825 2828 if abs not in names:
2826 2829 names[abs] = m.exact(abs)
2827 2830
2828 2831 # Find status of all file in `names`.
2829 2832 m = scmutil.matchfiles(repo, names)
2830 2833
2831 2834 changes = repo.status(node1=node, match=m,
2832 2835 unknown=True, ignored=True, clean=True)
2833 2836 else:
2834 2837 changes = repo.status(node1=node, match=m)
2835 2838 for kind in changes:
2836 2839 for abs in kind:
2837 2840 names[abs] = m.exact(abs)
2838 2841
2839 2842 m = scmutil.matchfiles(repo, names)
2840 2843
2841 2844 modified = set(changes.modified)
2842 2845 added = set(changes.added)
2843 2846 removed = set(changes.removed)
2844 2847 _deleted = set(changes.deleted)
2845 2848 unknown = set(changes.unknown)
2846 2849 unknown.update(changes.ignored)
2847 2850 clean = set(changes.clean)
2848 2851 modadded = set()
2849 2852
2850 2853 # We need to account for the state of the file in the dirstate,
2851 2854 # even when we revert against something else than parent. This will
2852 2855 # slightly alter the behavior of revert (doing back up or not, delete
2853 2856 # or just forget etc).
2854 2857 if parent == node:
2855 2858 dsmodified = modified
2856 2859 dsadded = added
2857 2860 dsremoved = removed
2858 2861 # store all local modifications, useful later for rename detection
2859 2862 localchanges = dsmodified | dsadded
2860 2863 modified, added, removed = set(), set(), set()
2861 2864 else:
2862 2865 changes = repo.status(node1=parent, match=m)
2863 2866 dsmodified = set(changes.modified)
2864 2867 dsadded = set(changes.added)
2865 2868 dsremoved = set(changes.removed)
2866 2869 # store all local modifications, useful later for rename detection
2867 2870 localchanges = dsmodified | dsadded
2868 2871
2869 2872 # only take into account for removes between wc and target
2870 2873 clean |= dsremoved - removed
2871 2874 dsremoved &= removed
2872 2875 # distinct between dirstate remove and other
2873 2876 removed -= dsremoved
2874 2877
2875 2878 modadded = added & dsmodified
2876 2879 added -= modadded
2877 2880
2878 2881 # tell newly modified apart.
2879 2882 dsmodified &= modified
2880 2883 dsmodified |= modified & dsadded # dirstate added may need backup
2881 2884 modified -= dsmodified
2882 2885
2883 2886 # We need to wait for some post-processing to update this set
2884 2887 # before making the distinction. The dirstate will be used for
2885 2888 # that purpose.
2886 2889 dsadded = added
2887 2890
2888 2891 # in case of merge, files that are actually added can be reported as
2889 2892 # modified, we need to post process the result
2890 2893 if p2 != nullid:
2891 2894 mergeadd = set(dsmodified)
2892 2895 for path in dsmodified:
2893 2896 if path in mf:
2894 2897 mergeadd.remove(path)
2895 2898 dsadded |= mergeadd
2896 2899 dsmodified -= mergeadd
2897 2900
2898 2901 # if f is a rename, update `names` to also revert the source
2899 2902 for f in localchanges:
2900 2903 src = repo.dirstate.copied(f)
2901 2904 # XXX should we check for rename down to target node?
2902 2905 if src and src not in names and repo.dirstate[src] == 'r':
2903 2906 dsremoved.add(src)
2904 2907 names[src] = True
2905 2908
2906 2909 # determine the exact nature of the deleted changesets
2907 2910 deladded = set(_deleted)
2908 2911 for path in _deleted:
2909 2912 if path in mf:
2910 2913 deladded.remove(path)
2911 2914 deleted = _deleted - deladded
2912 2915
2913 2916 # distinguish between file to forget and the other
2914 2917 added = set()
2915 2918 for abs in dsadded:
2916 2919 if repo.dirstate[abs] != 'a':
2917 2920 added.add(abs)
2918 2921 dsadded -= added
2919 2922
2920 2923 for abs in deladded:
2921 2924 if repo.dirstate[abs] == 'a':
2922 2925 dsadded.add(abs)
2923 2926 deladded -= dsadded
2924 2927
2925 2928 # For files marked as removed, we check if an unknown file is present at
2926 2929 # the same path. If a such file exists it may need to be backed up.
2927 2930 # Making the distinction at this stage helps have simpler backup
2928 2931 # logic.
2929 2932 removunk = set()
2930 2933 for abs in removed:
2931 2934 target = repo.wjoin(abs)
2932 2935 if os.path.lexists(target):
2933 2936 removunk.add(abs)
2934 2937 removed -= removunk
2935 2938
2936 2939 dsremovunk = set()
2937 2940 for abs in dsremoved:
2938 2941 target = repo.wjoin(abs)
2939 2942 if os.path.lexists(target):
2940 2943 dsremovunk.add(abs)
2941 2944 dsremoved -= dsremovunk
2942 2945
2943 2946 # action to be actually performed by revert
2944 2947 # (<list of file>, message>) tuple
2945 2948 actions = {'revert': ([], _('reverting %s\n')),
2946 2949 'add': ([], _('adding %s\n')),
2947 2950 'remove': ([], _('removing %s\n')),
2948 2951 'drop': ([], _('removing %s\n')),
2949 2952 'forget': ([], _('forgetting %s\n')),
2950 2953 'undelete': ([], _('undeleting %s\n')),
2951 2954 'noop': (None, _('no changes needed to %s\n')),
2952 2955 'unknown': (None, _('file not managed: %s\n')),
2953 2956 }
2954 2957
2955 2958 # "constant" that convey the backup strategy.
2956 2959 # All set to `discard` if `no-backup` is set do avoid checking
2957 2960 # no_backup lower in the code.
2958 2961 # These values are ordered for comparison purposes
2959 2962 backupinteractive = 3 # do backup if interactively modified
2960 2963 backup = 2 # unconditionally do backup
2961 2964 check = 1 # check if the existing file differs from target
2962 2965 discard = 0 # never do backup
2963 2966 if opts.get('no_backup'):
2964 2967 backupinteractive = backup = check = discard
2965 2968 if interactive:
2966 2969 dsmodifiedbackup = backupinteractive
2967 2970 else:
2968 2971 dsmodifiedbackup = backup
2969 2972 tobackup = set()
2970 2973
2971 2974 backupanddel = actions['remove']
2972 2975 if not opts.get('no_backup'):
2973 2976 backupanddel = actions['drop']
2974 2977
2975 2978 disptable = (
2976 2979 # dispatch table:
2977 2980 # file state
2978 2981 # action
2979 2982 # make backup
2980 2983
2981 2984 ## Sets that results that will change file on disk
2982 2985 # Modified compared to target, no local change
2983 2986 (modified, actions['revert'], discard),
2984 2987 # Modified compared to target, but local file is deleted
2985 2988 (deleted, actions['revert'], discard),
2986 2989 # Modified compared to target, local change
2987 2990 (dsmodified, actions['revert'], dsmodifiedbackup),
2988 2991 # Added since target
2989 2992 (added, actions['remove'], discard),
2990 2993 # Added in working directory
2991 2994 (dsadded, actions['forget'], discard),
2992 2995 # Added since target, have local modification
2993 2996 (modadded, backupanddel, backup),
2994 2997 # Added since target but file is missing in working directory
2995 2998 (deladded, actions['drop'], discard),
2996 2999 # Removed since target, before working copy parent
2997 3000 (removed, actions['add'], discard),
2998 3001 # Same as `removed` but an unknown file exists at the same path
2999 3002 (removunk, actions['add'], check),
3000 3003 # Removed since targe, marked as such in working copy parent
3001 3004 (dsremoved, actions['undelete'], discard),
3002 3005 # Same as `dsremoved` but an unknown file exists at the same path
3003 3006 (dsremovunk, actions['undelete'], check),
3004 3007 ## the following sets does not result in any file changes
3005 3008 # File with no modification
3006 3009 (clean, actions['noop'], discard),
3007 3010 # Existing file, not tracked anywhere
3008 3011 (unknown, actions['unknown'], discard),
3009 3012 )
3010 3013
3011 3014 for abs, exact in sorted(names.items()):
3012 3015 # target file to be touch on disk (relative to cwd)
3013 3016 target = repo.wjoin(abs)
3014 3017 # search the entry in the dispatch table.
3015 3018 # if the file is in any of these sets, it was touched in the working
3016 3019 # directory parent and we are sure it needs to be reverted.
3017 3020 for table, (xlist, msg), dobackup in disptable:
3018 3021 if abs not in table:
3019 3022 continue
3020 3023 if xlist is not None:
3021 3024 xlist.append(abs)
3022 3025 if dobackup:
3023 3026 # If in interactive mode, don't automatically create
3024 3027 # .orig files (issue4793)
3025 3028 if dobackup == backupinteractive:
3026 3029 tobackup.add(abs)
3027 3030 elif (backup <= dobackup or wctx[abs].cmp(ctx[abs])):
3028 3031 absbakname = scmutil.backuppath(ui, repo, abs)
3029 3032 bakname = os.path.relpath(absbakname,
3030 3033 start=repo.root)
3031 3034 ui.note(_('saving current version of %s as %s\n') %
3032 3035 (uipathfn(abs), uipathfn(bakname)))
3033 3036 if not opts.get('dry_run'):
3034 3037 if interactive:
3035 3038 util.copyfile(target, absbakname)
3036 3039 else:
3037 3040 util.rename(target, absbakname)
3038 3041 if opts.get('dry_run'):
3039 3042 if ui.verbose or not exact:
3040 3043 ui.status(msg % uipathfn(abs))
3041 3044 elif exact:
3042 3045 ui.warn(msg % uipathfn(abs))
3043 3046 break
3044 3047
3045 3048 if not opts.get('dry_run'):
3046 3049 needdata = ('revert', 'add', 'undelete')
3047 3050 oplist = [actions[name][0] for name in needdata]
3048 3051 prefetch = scmutil.prefetchfiles
3049 3052 matchfiles = scmutil.matchfiles
3050 3053 prefetch(repo, [ctx.rev()],
3051 3054 matchfiles(repo,
3052 3055 [f for sublist in oplist for f in sublist]))
3053 3056 _performrevert(repo, parents, ctx, names, uipathfn, actions,
3054 3057 interactive, tobackup)
3055 3058
3056 3059 if targetsubs:
3057 3060 # Revert the subrepos on the revert list
3058 3061 for sub in targetsubs:
3059 3062 try:
3060 3063 wctx.sub(sub).revert(ctx.substate[sub], *pats,
3061 3064 **pycompat.strkwargs(opts))
3062 3065 except KeyError:
3063 3066 raise error.Abort("subrepository '%s' does not exist in %s!"
3064 3067 % (sub, short(ctx.node())))
3065 3068
3066 3069 def _performrevert(repo, parents, ctx, names, uipathfn, actions,
3067 3070 interactive=False, tobackup=None):
3068 3071 """function that actually perform all the actions computed for revert
3069 3072
3070 3073 This is an independent function to let extension to plug in and react to
3071 3074 the imminent revert.
3072 3075
3073 3076 Make sure you have the working directory locked when calling this function.
3074 3077 """
3075 3078 parent, p2 = parents
3076 3079 node = ctx.node()
3077 3080 excluded_files = []
3078 3081
3079 3082 def checkout(f):
3080 3083 fc = ctx[f]
3081 3084 repo.wwrite(f, fc.data(), fc.flags())
3082 3085
3083 3086 def doremove(f):
3084 3087 try:
3085 3088 rmdir = repo.ui.configbool('experimental', 'removeemptydirs')
3086 3089 repo.wvfs.unlinkpath(f, rmdir=rmdir)
3087 3090 except OSError:
3088 3091 pass
3089 3092 repo.dirstate.remove(f)
3090 3093
3091 3094 def prntstatusmsg(action, f):
3092 3095 exact = names[f]
3093 3096 if repo.ui.verbose or not exact:
3094 3097 repo.ui.status(actions[action][1] % uipathfn(f))
3095 3098
3096 3099 audit_path = pathutil.pathauditor(repo.root, cached=True)
3097 3100 for f in actions['forget'][0]:
3098 3101 if interactive:
3099 3102 choice = repo.ui.promptchoice(
3100 3103 _("forget added file %s (Yn)?$$ &Yes $$ &No") % uipathfn(f))
3101 3104 if choice == 0:
3102 3105 prntstatusmsg('forget', f)
3103 3106 repo.dirstate.drop(f)
3104 3107 else:
3105 3108 excluded_files.append(f)
3106 3109 else:
3107 3110 prntstatusmsg('forget', f)
3108 3111 repo.dirstate.drop(f)
3109 3112 for f in actions['remove'][0]:
3110 3113 audit_path(f)
3111 3114 if interactive:
3112 3115 choice = repo.ui.promptchoice(
3113 3116 _("remove added file %s (Yn)?$$ &Yes $$ &No") % uipathfn(f))
3114 3117 if choice == 0:
3115 3118 prntstatusmsg('remove', f)
3116 3119 doremove(f)
3117 3120 else:
3118 3121 excluded_files.append(f)
3119 3122 else:
3120 3123 prntstatusmsg('remove', f)
3121 3124 doremove(f)
3122 3125 for f in actions['drop'][0]:
3123 3126 audit_path(f)
3124 3127 prntstatusmsg('drop', f)
3125 3128 repo.dirstate.remove(f)
3126 3129
3127 3130 normal = None
3128 3131 if node == parent:
3129 3132 # We're reverting to our parent. If possible, we'd like status
3130 3133 # to report the file as clean. We have to use normallookup for
3131 3134 # merges to avoid losing information about merged/dirty files.
3132 3135 if p2 != nullid:
3133 3136 normal = repo.dirstate.normallookup
3134 3137 else:
3135 3138 normal = repo.dirstate.normal
3136 3139
3137 3140 newlyaddedandmodifiedfiles = set()
3138 3141 if interactive:
3139 3142 # Prompt the user for changes to revert
3140 3143 torevert = [f for f in actions['revert'][0] if f not in excluded_files]
3141 3144 m = scmutil.matchfiles(repo, torevert)
3142 3145 diffopts = patch.difffeatureopts(repo.ui, whitespace=True,
3143 3146 section='commands',
3144 3147 configprefix='revert.interactive.')
3145 3148 diffopts.nodates = True
3146 3149 diffopts.git = True
3147 3150 operation = 'discard'
3148 3151 reversehunks = True
3149 3152 if node != parent:
3150 3153 operation = 'apply'
3151 3154 reversehunks = False
3152 3155 if reversehunks:
3153 3156 diff = patch.diff(repo, ctx.node(), None, m, opts=diffopts)
3154 3157 else:
3155 3158 diff = patch.diff(repo, None, ctx.node(), m, opts=diffopts)
3156 3159 originalchunks = patch.parsepatch(diff)
3157 3160
3158 3161 try:
3159 3162
3160 3163 chunks, opts = recordfilter(repo.ui, originalchunks,
3161 3164 operation=operation)
3162 3165 if reversehunks:
3163 3166 chunks = patch.reversehunks(chunks)
3164 3167
3165 3168 except error.PatchError as err:
3166 3169 raise error.Abort(_('error parsing patch: %s') % err)
3167 3170
3168 3171 newlyaddedandmodifiedfiles = newandmodified(chunks, originalchunks)
3169 3172 if tobackup is None:
3170 3173 tobackup = set()
3171 3174 # Apply changes
3172 3175 fp = stringio()
3173 3176 # chunks are serialized per file, but files aren't sorted
3174 3177 for f in sorted(set(c.header.filename() for c in chunks if ishunk(c))):
3175 3178 prntstatusmsg('revert', f)
3176 3179 for c in chunks:
3177 3180 if ishunk(c):
3178 3181 abs = c.header.filename()
3179 3182 # Create a backup file only if this hunk should be backed up
3180 3183 if c.header.filename() in tobackup:
3181 3184 target = repo.wjoin(abs)
3182 3185 bakname = scmutil.backuppath(repo.ui, repo, abs)
3183 3186 util.copyfile(target, bakname)
3184 3187 tobackup.remove(abs)
3185 3188 c.write(fp)
3186 3189 dopatch = fp.tell()
3187 3190 fp.seek(0)
3188 3191 if dopatch:
3189 3192 try:
3190 3193 patch.internalpatch(repo.ui, repo, fp, 1, eolmode=None)
3191 3194 except error.PatchError as err:
3192 3195 raise error.Abort(pycompat.bytestr(err))
3193 3196 del fp
3194 3197 else:
3195 3198 for f in actions['revert'][0]:
3196 3199 prntstatusmsg('revert', f)
3197 3200 checkout(f)
3198 3201 if normal:
3199 3202 normal(f)
3200 3203
3201 3204 for f in actions['add'][0]:
3202 3205 # Don't checkout modified files, they are already created by the diff
3203 3206 if f not in newlyaddedandmodifiedfiles:
3204 3207 prntstatusmsg('add', f)
3205 3208 checkout(f)
3206 3209 repo.dirstate.add(f)
3207 3210
3208 3211 normal = repo.dirstate.normallookup
3209 3212 if node == parent and p2 == nullid:
3210 3213 normal = repo.dirstate.normal
3211 3214 for f in actions['undelete'][0]:
3212 3215 if interactive:
3213 3216 choice = repo.ui.promptchoice(
3214 3217 _("add back removed file %s (Yn)?$$ &Yes $$ &No") % f)
3215 3218 if choice == 0:
3216 3219 prntstatusmsg('undelete', f)
3217 3220 checkout(f)
3218 3221 normal(f)
3219 3222 else:
3220 3223 excluded_files.append(f)
3221 3224 else:
3222 3225 prntstatusmsg('undelete', f)
3223 3226 checkout(f)
3224 3227 normal(f)
3225 3228
3226 3229 copied = copies.pathcopies(repo[parent], ctx)
3227 3230
3228 3231 for f in actions['add'][0] + actions['undelete'][0] + actions['revert'][0]:
3229 3232 if f in copied:
3230 3233 repo.dirstate.copy(copied[f], f)
3231 3234
3232 3235 # a list of (ui, repo, otherpeer, opts, missing) functions called by
3233 3236 # commands.outgoing. "missing" is "missing" of the result of
3234 3237 # "findcommonoutgoing()"
3235 3238 outgoinghooks = util.hooks()
3236 3239
3237 3240 # a list of (ui, repo) functions called by commands.summary
3238 3241 summaryhooks = util.hooks()
3239 3242
3240 3243 # a list of (ui, repo, opts, changes) functions called by commands.summary.
3241 3244 #
3242 3245 # functions should return tuple of booleans below, if 'changes' is None:
3243 3246 # (whether-incomings-are-needed, whether-outgoings-are-needed)
3244 3247 #
3245 3248 # otherwise, 'changes' is a tuple of tuples below:
3246 3249 # - (sourceurl, sourcebranch, sourcepeer, incoming)
3247 3250 # - (desturl, destbranch, destpeer, outgoing)
3248 3251 summaryremotehooks = util.hooks()
3249 3252
3250 3253 # A list of state files kept by multistep operations like graft.
3251 3254 # Since graft cannot be aborted, it is considered 'clearable' by update.
3252 3255 # note: bisect is intentionally excluded
3253 3256 # (state file, clearable, allowcommit, error, hint)
3254 3257 unfinishedstates = [
3255 3258 ('graftstate', True, False, _('graft in progress'),
3256 3259 _("use 'hg graft --continue' or 'hg graft --stop' to stop")),
3257 3260 ('updatestate', True, False, _('last update was interrupted'),
3258 3261 _("use 'hg update' to get a consistent checkout"))
3259 3262 ]
3260 3263
3261 3264 def checkunfinished(repo, commit=False):
3262 3265 '''Look for an unfinished multistep operation, like graft, and abort
3263 3266 if found. It's probably good to check this right before
3264 3267 bailifchanged().
3265 3268 '''
3266 3269 # Check for non-clearable states first, so things like rebase will take
3267 3270 # precedence over update.
3268 3271 for f, clearable, allowcommit, msg, hint in unfinishedstates:
3269 3272 if clearable or (commit and allowcommit):
3270 3273 continue
3271 3274 if repo.vfs.exists(f):
3272 3275 raise error.Abort(msg, hint=hint)
3273 3276
3274 3277 for f, clearable, allowcommit, msg, hint in unfinishedstates:
3275 3278 if not clearable or (commit and allowcommit):
3276 3279 continue
3277 3280 if repo.vfs.exists(f):
3278 3281 raise error.Abort(msg, hint=hint)
3279 3282
3280 3283 def clearunfinished(repo):
3281 3284 '''Check for unfinished operations (as above), and clear the ones
3282 3285 that are clearable.
3283 3286 '''
3284 3287 for f, clearable, allowcommit, msg, hint in unfinishedstates:
3285 3288 if not clearable and repo.vfs.exists(f):
3286 3289 raise error.Abort(msg, hint=hint)
3287 3290 for f, clearable, allowcommit, msg, hint in unfinishedstates:
3288 3291 if clearable and repo.vfs.exists(f):
3289 3292 util.unlink(repo.vfs.join(f))
3290 3293
3291 3294 afterresolvedstates = [
3292 3295 ('graftstate',
3293 3296 _('hg graft --continue')),
3294 3297 ]
3295 3298
3296 3299 def howtocontinue(repo):
3297 3300 '''Check for an unfinished operation and return the command to finish
3298 3301 it.
3299 3302
3300 3303 afterresolvedstates tuples define a .hg/{file} and the corresponding
3301 3304 command needed to finish it.
3302 3305
3303 3306 Returns a (msg, warning) tuple. 'msg' is a string and 'warning' is
3304 3307 a boolean.
3305 3308 '''
3306 3309 contmsg = _("continue: %s")
3307 3310 for f, msg in afterresolvedstates:
3308 3311 if repo.vfs.exists(f):
3309 3312 return contmsg % msg, True
3310 3313 if repo[None].dirty(missing=True, merge=False, branch=False):
3311 3314 return contmsg % _("hg commit"), False
3312 3315 return None, None
3313 3316
3314 3317 def checkafterresolved(repo):
3315 3318 '''Inform the user about the next action after completing hg resolve
3316 3319
3317 3320 If there's a matching afterresolvedstates, howtocontinue will yield
3318 3321 repo.ui.warn as the reporter.
3319 3322
3320 3323 Otherwise, it will yield repo.ui.note.
3321 3324 '''
3322 3325 msg, warning = howtocontinue(repo)
3323 3326 if msg is not None:
3324 3327 if warning:
3325 3328 repo.ui.warn("%s\n" % msg)
3326 3329 else:
3327 3330 repo.ui.note("%s\n" % msg)
3328 3331
3329 3332 def wrongtooltocontinue(repo, task):
3330 3333 '''Raise an abort suggesting how to properly continue if there is an
3331 3334 active task.
3332 3335
3333 3336 Uses howtocontinue() to find the active task.
3334 3337
3335 3338 If there's no task (repo.ui.note for 'hg commit'), it does not offer
3336 3339 a hint.
3337 3340 '''
3338 3341 after = howtocontinue(repo)
3339 3342 hint = None
3340 3343 if after[1]:
3341 3344 hint = after[0]
3342 3345 raise error.Abort(_('no %s in progress') % task, hint=hint)
@@ -1,6232 +1,6233 b''
1 1 # commands.py - command processing for mercurial
2 2 #
3 3 # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
4 4 #
5 5 # This software may be used and distributed according to the terms of the
6 6 # GNU General Public License version 2 or any later version.
7 7
8 8 from __future__ import absolute_import
9 9
10 10 import difflib
11 11 import errno
12 12 import os
13 13 import re
14 14 import sys
15 15
16 16 from .i18n import _
17 17 from .node import (
18 18 hex,
19 19 nullid,
20 20 nullrev,
21 21 short,
22 22 wdirhex,
23 23 wdirrev,
24 24 )
25 25 from . import (
26 26 archival,
27 27 bookmarks,
28 28 bundle2,
29 29 changegroup,
30 30 cmdutil,
31 31 copies,
32 32 debugcommands as debugcommandsmod,
33 33 destutil,
34 34 dirstateguard,
35 35 discovery,
36 36 encoding,
37 37 error,
38 38 exchange,
39 39 extensions,
40 40 filemerge,
41 41 formatter,
42 42 graphmod,
43 43 hbisect,
44 44 help,
45 45 hg,
46 46 logcmdutil,
47 47 merge as mergemod,
48 48 narrowspec,
49 49 obsolete,
50 50 obsutil,
51 51 patch,
52 52 phases,
53 53 pycompat,
54 54 rcutil,
55 55 registrar,
56 56 repair,
57 57 revsetlang,
58 58 rewriteutil,
59 59 scmutil,
60 60 server,
61 61 state as statemod,
62 62 streamclone,
63 63 tags as tagsmod,
64 64 templatekw,
65 65 ui as uimod,
66 66 util,
67 67 wireprotoserver,
68 68 )
69 69 from .utils import (
70 70 dateutil,
71 71 stringutil,
72 72 )
73 73
74 74 table = {}
75 75 table.update(debugcommandsmod.command._table)
76 76
77 77 command = registrar.command(table)
78 78 INTENT_READONLY = registrar.INTENT_READONLY
79 79
80 80 # common command options
81 81
82 82 globalopts = [
83 83 ('R', 'repository', '',
84 84 _('repository root directory or name of overlay bundle file'),
85 85 _('REPO')),
86 86 ('', 'cwd', '',
87 87 _('change working directory'), _('DIR')),
88 88 ('y', 'noninteractive', None,
89 89 _('do not prompt, automatically pick the first choice for all prompts')),
90 90 ('q', 'quiet', None, _('suppress output')),
91 91 ('v', 'verbose', None, _('enable additional output')),
92 92 ('', 'color', '',
93 93 # i18n: 'always', 'auto', 'never', and 'debug' are keywords
94 94 # and should not be translated
95 95 _("when to colorize (boolean, always, auto, never, or debug)"),
96 96 _('TYPE')),
97 97 ('', 'config', [],
98 98 _('set/override config option (use \'section.name=value\')'),
99 99 _('CONFIG')),
100 100 ('', 'debug', None, _('enable debugging output')),
101 101 ('', 'debugger', None, _('start debugger')),
102 102 ('', 'encoding', encoding.encoding, _('set the charset encoding'),
103 103 _('ENCODE')),
104 104 ('', 'encodingmode', encoding.encodingmode,
105 105 _('set the charset encoding mode'), _('MODE')),
106 106 ('', 'traceback', None, _('always print a traceback on exception')),
107 107 ('', 'time', None, _('time how long the command takes')),
108 108 ('', 'profile', None, _('print command execution profile')),
109 109 ('', 'version', None, _('output version information and exit')),
110 110 ('h', 'help', None, _('display help and exit')),
111 111 ('', 'hidden', False, _('consider hidden changesets')),
112 112 ('', 'pager', 'auto',
113 113 _("when to paginate (boolean, always, auto, or never)"), _('TYPE')),
114 114 ]
115 115
116 116 dryrunopts = cmdutil.dryrunopts
117 117 remoteopts = cmdutil.remoteopts
118 118 walkopts = cmdutil.walkopts
119 119 commitopts = cmdutil.commitopts
120 120 commitopts2 = cmdutil.commitopts2
121 121 formatteropts = cmdutil.formatteropts
122 122 templateopts = cmdutil.templateopts
123 123 logopts = cmdutil.logopts
124 124 diffopts = cmdutil.diffopts
125 125 diffwsopts = cmdutil.diffwsopts
126 126 diffopts2 = cmdutil.diffopts2
127 127 mergetoolopts = cmdutil.mergetoolopts
128 128 similarityopts = cmdutil.similarityopts
129 129 subrepoopts = cmdutil.subrepoopts
130 130 debugrevlogopts = cmdutil.debugrevlogopts
131 131
132 132 # Commands start here, listed alphabetically
133 133
134 134 @command('add',
135 135 walkopts + subrepoopts + dryrunopts,
136 136 _('[OPTION]... [FILE]...'),
137 137 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
138 138 helpbasic=True, inferrepo=True)
139 139 def add(ui, repo, *pats, **opts):
140 140 """add the specified files on the next commit
141 141
142 142 Schedule files to be version controlled and added to the
143 143 repository.
144 144
145 145 The files will be added to the repository at the next commit. To
146 146 undo an add before that, see :hg:`forget`.
147 147
148 148 If no names are given, add all files to the repository (except
149 149 files matching ``.hgignore``).
150 150
151 151 .. container:: verbose
152 152
153 153 Examples:
154 154
155 155 - New (unknown) files are added
156 156 automatically by :hg:`add`::
157 157
158 158 $ ls
159 159 foo.c
160 160 $ hg status
161 161 ? foo.c
162 162 $ hg add
163 163 adding foo.c
164 164 $ hg status
165 165 A foo.c
166 166
167 167 - Specific files to be added can be specified::
168 168
169 169 $ ls
170 170 bar.c foo.c
171 171 $ hg status
172 172 ? bar.c
173 173 ? foo.c
174 174 $ hg add bar.c
175 175 $ hg status
176 176 A bar.c
177 177 ? foo.c
178 178
179 179 Returns 0 if all files are successfully added.
180 180 """
181 181
182 182 m = scmutil.match(repo[None], pats, pycompat.byteskwargs(opts))
183 183 uipathfn = scmutil.getuipathfn(repo, forcerelativevalue=True)
184 184 rejected = cmdutil.add(ui, repo, m, "", uipathfn, False, **opts)
185 185 return rejected and 1 or 0
186 186
187 187 @command('addremove',
188 188 similarityopts + subrepoopts + walkopts + dryrunopts,
189 189 _('[OPTION]... [FILE]...'),
190 190 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
191 191 inferrepo=True)
192 192 def addremove(ui, repo, *pats, **opts):
193 193 """add all new files, delete all missing files
194 194
195 195 Add all new files and remove all missing files from the
196 196 repository.
197 197
198 198 Unless names are given, new files are ignored if they match any of
199 199 the patterns in ``.hgignore``. As with add, these changes take
200 200 effect at the next commit.
201 201
202 202 Use the -s/--similarity option to detect renamed files. This
203 203 option takes a percentage between 0 (disabled) and 100 (files must
204 204 be identical) as its parameter. With a parameter greater than 0,
205 205 this compares every removed file with every added file and records
206 206 those similar enough as renames. Detecting renamed files this way
207 207 can be expensive. After using this option, :hg:`status -C` can be
208 208 used to check which files were identified as moved or renamed. If
209 209 not specified, -s/--similarity defaults to 100 and only renames of
210 210 identical files are detected.
211 211
212 212 .. container:: verbose
213 213
214 214 Examples:
215 215
216 216 - A number of files (bar.c and foo.c) are new,
217 217 while foobar.c has been removed (without using :hg:`remove`)
218 218 from the repository::
219 219
220 220 $ ls
221 221 bar.c foo.c
222 222 $ hg status
223 223 ! foobar.c
224 224 ? bar.c
225 225 ? foo.c
226 226 $ hg addremove
227 227 adding bar.c
228 228 adding foo.c
229 229 removing foobar.c
230 230 $ hg status
231 231 A bar.c
232 232 A foo.c
233 233 R foobar.c
234 234
235 235 - A file foobar.c was moved to foo.c without using :hg:`rename`.
236 236 Afterwards, it was edited slightly::
237 237
238 238 $ ls
239 239 foo.c
240 240 $ hg status
241 241 ! foobar.c
242 242 ? foo.c
243 243 $ hg addremove --similarity 90
244 244 removing foobar.c
245 245 adding foo.c
246 246 recording removal of foobar.c as rename to foo.c (94% similar)
247 247 $ hg status -C
248 248 A foo.c
249 249 foobar.c
250 250 R foobar.c
251 251
252 252 Returns 0 if all files are successfully added.
253 253 """
254 254 opts = pycompat.byteskwargs(opts)
255 255 if not opts.get('similarity'):
256 256 opts['similarity'] = '100'
257 257 matcher = scmutil.match(repo[None], pats, opts)
258 258 relative = scmutil.anypats(pats, opts)
259 259 uipathfn = scmutil.getuipathfn(repo, forcerelativevalue=relative)
260 260 return scmutil.addremove(repo, matcher, "", uipathfn, opts)
261 261
262 262 @command('annotate|blame',
263 263 [('r', 'rev', '', _('annotate the specified revision'), _('REV')),
264 264 ('', 'follow', None,
265 265 _('follow copies/renames and list the filename (DEPRECATED)')),
266 266 ('', 'no-follow', None, _("don't follow copies and renames")),
267 267 ('a', 'text', None, _('treat all files as text')),
268 268 ('u', 'user', None, _('list the author (long with -v)')),
269 269 ('f', 'file', None, _('list the filename')),
270 270 ('d', 'date', None, _('list the date (short with -q)')),
271 271 ('n', 'number', None, _('list the revision number (default)')),
272 272 ('c', 'changeset', None, _('list the changeset')),
273 273 ('l', 'line-number', None, _('show line number at the first appearance')),
274 274 ('', 'skip', [], _('revision to not display (EXPERIMENTAL)'), _('REV')),
275 275 ] + diffwsopts + walkopts + formatteropts,
276 276 _('[-r REV] [-f] [-a] [-u] [-d] [-n] [-c] [-l] FILE...'),
277 277 helpcategory=command.CATEGORY_FILE_CONTENTS,
278 278 helpbasic=True, inferrepo=True)
279 279 def annotate(ui, repo, *pats, **opts):
280 280 """show changeset information by line for each file
281 281
282 282 List changes in files, showing the revision id responsible for
283 283 each line.
284 284
285 285 This command is useful for discovering when a change was made and
286 286 by whom.
287 287
288 288 If you include --file, --user, or --date, the revision number is
289 289 suppressed unless you also include --number.
290 290
291 291 Without the -a/--text option, annotate will avoid processing files
292 292 it detects as binary. With -a, annotate will annotate the file
293 293 anyway, although the results will probably be neither useful
294 294 nor desirable.
295 295
296 296 .. container:: verbose
297 297
298 298 Template:
299 299
300 300 The following keywords are supported in addition to the common template
301 301 keywords and functions. See also :hg:`help templates`.
302 302
303 303 :lines: List of lines with annotation data.
304 304 :path: String. Repository-absolute path of the specified file.
305 305
306 306 And each entry of ``{lines}`` provides the following sub-keywords in
307 307 addition to ``{date}``, ``{node}``, ``{rev}``, ``{user}``, etc.
308 308
309 309 :line: String. Line content.
310 310 :lineno: Integer. Line number at that revision.
311 311 :path: String. Repository-absolute path of the file at that revision.
312 312
313 313 See :hg:`help templates.operators` for the list expansion syntax.
314 314
315 315 Returns 0 on success.
316 316 """
317 317 opts = pycompat.byteskwargs(opts)
318 318 if not pats:
319 319 raise error.Abort(_('at least one filename or pattern is required'))
320 320
321 321 if opts.get('follow'):
322 322 # --follow is deprecated and now just an alias for -f/--file
323 323 # to mimic the behavior of Mercurial before version 1.5
324 324 opts['file'] = True
325 325
326 326 if (not opts.get('user') and not opts.get('changeset')
327 327 and not opts.get('date') and not opts.get('file')):
328 328 opts['number'] = True
329 329
330 330 linenumber = opts.get('line_number') is not None
331 331 if linenumber and (not opts.get('changeset')) and (not opts.get('number')):
332 332 raise error.Abort(_('at least one of -n/-c is required for -l'))
333 333
334 334 rev = opts.get('rev')
335 335 if rev:
336 336 repo = scmutil.unhidehashlikerevs(repo, [rev], 'nowarn')
337 337 ctx = scmutil.revsingle(repo, rev)
338 338
339 339 ui.pager('annotate')
340 340 rootfm = ui.formatter('annotate', opts)
341 341 if ui.debugflag:
342 342 shorthex = pycompat.identity
343 343 else:
344 344 def shorthex(h):
345 345 return h[:12]
346 346 if ui.quiet:
347 347 datefunc = dateutil.shortdate
348 348 else:
349 349 datefunc = dateutil.datestr
350 350 if ctx.rev() is None:
351 351 if opts.get('changeset'):
352 352 # omit "+" suffix which is appended to node hex
353 353 def formatrev(rev):
354 354 if rev == wdirrev:
355 355 return '%d' % ctx.p1().rev()
356 356 else:
357 357 return '%d' % rev
358 358 else:
359 359 def formatrev(rev):
360 360 if rev == wdirrev:
361 361 return '%d+' % ctx.p1().rev()
362 362 else:
363 363 return '%d ' % rev
364 364 def formathex(h):
365 365 if h == wdirhex:
366 366 return '%s+' % shorthex(hex(ctx.p1().node()))
367 367 else:
368 368 return '%s ' % shorthex(h)
369 369 else:
370 370 formatrev = b'%d'.__mod__
371 371 formathex = shorthex
372 372
373 373 opmap = [
374 374 ('user', ' ', lambda x: x.fctx.user(), ui.shortuser),
375 375 ('rev', ' ', lambda x: scmutil.intrev(x.fctx), formatrev),
376 376 ('node', ' ', lambda x: hex(scmutil.binnode(x.fctx)), formathex),
377 377 ('date', ' ', lambda x: x.fctx.date(), util.cachefunc(datefunc)),
378 378 ('path', ' ', lambda x: x.fctx.path(), pycompat.bytestr),
379 379 ('lineno', ':', lambda x: x.lineno, pycompat.bytestr),
380 380 ]
381 381 opnamemap = {
382 382 'rev': 'number',
383 383 'node': 'changeset',
384 384 'path': 'file',
385 385 'lineno': 'line_number',
386 386 }
387 387
388 388 if rootfm.isplain():
389 389 def makefunc(get, fmt):
390 390 return lambda x: fmt(get(x))
391 391 else:
392 392 def makefunc(get, fmt):
393 393 return get
394 394 datahint = rootfm.datahint()
395 395 funcmap = [(makefunc(get, fmt), sep) for fn, sep, get, fmt in opmap
396 396 if opts.get(opnamemap.get(fn, fn)) or fn in datahint]
397 397 funcmap[0] = (funcmap[0][0], '') # no separator in front of first column
398 398 fields = ' '.join(fn for fn, sep, get, fmt in opmap
399 399 if opts.get(opnamemap.get(fn, fn)) or fn in datahint)
400 400
401 401 def bad(x, y):
402 402 raise error.Abort("%s: %s" % (x, y))
403 403
404 404 m = scmutil.match(ctx, pats, opts, badfn=bad)
405 405
406 406 follow = not opts.get('no_follow')
407 407 diffopts = patch.difffeatureopts(ui, opts, section='annotate',
408 408 whitespace=True)
409 409 skiprevs = opts.get('skip')
410 410 if skiprevs:
411 411 skiprevs = scmutil.revrange(repo, skiprevs)
412 412
413 413 uipathfn = scmutil.getuipathfn(repo, legacyrelativevalue=True)
414 414 for abs in ctx.walk(m):
415 415 fctx = ctx[abs]
416 416 rootfm.startitem()
417 417 rootfm.data(path=abs)
418 418 if not opts.get('text') and fctx.isbinary():
419 419 rootfm.plain(_("%s: binary file\n") % uipathfn(abs))
420 420 continue
421 421
422 422 fm = rootfm.nested('lines', tmpl='{rev}: {line}')
423 423 lines = fctx.annotate(follow=follow, skiprevs=skiprevs,
424 424 diffopts=diffopts)
425 425 if not lines:
426 426 fm.end()
427 427 continue
428 428 formats = []
429 429 pieces = []
430 430
431 431 for f, sep in funcmap:
432 432 l = [f(n) for n in lines]
433 433 if fm.isplain():
434 434 sizes = [encoding.colwidth(x) for x in l]
435 435 ml = max(sizes)
436 436 formats.append([sep + ' ' * (ml - w) + '%s' for w in sizes])
437 437 else:
438 438 formats.append(['%s' for x in l])
439 439 pieces.append(l)
440 440
441 441 for f, p, n in zip(zip(*formats), zip(*pieces), lines):
442 442 fm.startitem()
443 443 fm.context(fctx=n.fctx)
444 444 fm.write(fields, "".join(f), *p)
445 445 if n.skip:
446 446 fmt = "* %s"
447 447 else:
448 448 fmt = ": %s"
449 449 fm.write('line', fmt, n.text)
450 450
451 451 if not lines[-1].text.endswith('\n'):
452 452 fm.plain('\n')
453 453 fm.end()
454 454
455 455 rootfm.end()
456 456
457 457 @command('archive',
458 458 [('', 'no-decode', None, _('do not pass files through decoders')),
459 459 ('p', 'prefix', '', _('directory prefix for files in archive'),
460 460 _('PREFIX')),
461 461 ('r', 'rev', '', _('revision to distribute'), _('REV')),
462 462 ('t', 'type', '', _('type of distribution to create'), _('TYPE')),
463 463 ] + subrepoopts + walkopts,
464 464 _('[OPTION]... DEST'),
465 465 helpcategory=command.CATEGORY_IMPORT_EXPORT)
466 466 def archive(ui, repo, dest, **opts):
467 467 '''create an unversioned archive of a repository revision
468 468
469 469 By default, the revision used is the parent of the working
470 470 directory; use -r/--rev to specify a different revision.
471 471
472 472 The archive type is automatically detected based on file
473 473 extension (to override, use -t/--type).
474 474
475 475 .. container:: verbose
476 476
477 477 Examples:
478 478
479 479 - create a zip file containing the 1.0 release::
480 480
481 481 hg archive -r 1.0 project-1.0.zip
482 482
483 483 - create a tarball excluding .hg files::
484 484
485 485 hg archive project.tar.gz -X ".hg*"
486 486
487 487 Valid types are:
488 488
489 489 :``files``: a directory full of files (default)
490 490 :``tar``: tar archive, uncompressed
491 491 :``tbz2``: tar archive, compressed using bzip2
492 492 :``tgz``: tar archive, compressed using gzip
493 493 :``uzip``: zip archive, uncompressed
494 494 :``zip``: zip archive, compressed using deflate
495 495
496 496 The exact name of the destination archive or directory is given
497 497 using a format string; see :hg:`help export` for details.
498 498
499 499 Each member added to an archive file has a directory prefix
500 500 prepended. Use -p/--prefix to specify a format string for the
501 501 prefix. The default is the basename of the archive, with suffixes
502 502 removed.
503 503
504 504 Returns 0 on success.
505 505 '''
506 506
507 507 opts = pycompat.byteskwargs(opts)
508 508 rev = opts.get('rev')
509 509 if rev:
510 510 repo = scmutil.unhidehashlikerevs(repo, [rev], 'nowarn')
511 511 ctx = scmutil.revsingle(repo, rev)
512 512 if not ctx:
513 513 raise error.Abort(_('no working directory: please specify a revision'))
514 514 node = ctx.node()
515 515 dest = cmdutil.makefilename(ctx, dest)
516 516 if os.path.realpath(dest) == repo.root:
517 517 raise error.Abort(_('repository root cannot be destination'))
518 518
519 519 kind = opts.get('type') or archival.guesskind(dest) or 'files'
520 520 prefix = opts.get('prefix')
521 521
522 522 if dest == '-':
523 523 if kind == 'files':
524 524 raise error.Abort(_('cannot archive plain files to stdout'))
525 525 dest = cmdutil.makefileobj(ctx, dest)
526 526 if not prefix:
527 527 prefix = os.path.basename(repo.root) + '-%h'
528 528
529 529 prefix = cmdutil.makefilename(ctx, prefix)
530 530 match = scmutil.match(ctx, [], opts)
531 531 archival.archive(repo, dest, node, kind, not opts.get('no_decode'),
532 532 match, prefix, subrepos=opts.get('subrepos'))
533 533
534 534 @command('backout',
535 535 [('', 'merge', None, _('merge with old dirstate parent after backout')),
536 536 ('', 'commit', None,
537 537 _('commit if no conflicts were encountered (DEPRECATED)')),
538 538 ('', 'no-commit', None, _('do not commit')),
539 539 ('', 'parent', '',
540 540 _('parent to choose when backing out merge (DEPRECATED)'), _('REV')),
541 541 ('r', 'rev', '', _('revision to backout'), _('REV')),
542 542 ('e', 'edit', False, _('invoke editor on commit messages')),
543 543 ] + mergetoolopts + walkopts + commitopts + commitopts2,
544 544 _('[OPTION]... [-r] REV'),
545 545 helpcategory=command.CATEGORY_CHANGE_MANAGEMENT)
546 546 def backout(ui, repo, node=None, rev=None, **opts):
547 547 '''reverse effect of earlier changeset
548 548
549 549 Prepare a new changeset with the effect of REV undone in the
550 550 current working directory. If no conflicts were encountered,
551 551 it will be committed immediately.
552 552
553 553 If REV is the parent of the working directory, then this new changeset
554 554 is committed automatically (unless --no-commit is specified).
555 555
556 556 .. note::
557 557
558 558 :hg:`backout` cannot be used to fix either an unwanted or
559 559 incorrect merge.
560 560
561 561 .. container:: verbose
562 562
563 563 Examples:
564 564
565 565 - Reverse the effect of the parent of the working directory.
566 566 This backout will be committed immediately::
567 567
568 568 hg backout -r .
569 569
570 570 - Reverse the effect of previous bad revision 23::
571 571
572 572 hg backout -r 23
573 573
574 574 - Reverse the effect of previous bad revision 23 and
575 575 leave changes uncommitted::
576 576
577 577 hg backout -r 23 --no-commit
578 578 hg commit -m "Backout revision 23"
579 579
580 580 By default, the pending changeset will have one parent,
581 581 maintaining a linear history. With --merge, the pending
582 582 changeset will instead have two parents: the old parent of the
583 583 working directory and a new child of REV that simply undoes REV.
584 584
585 585 Before version 1.7, the behavior without --merge was equivalent
586 586 to specifying --merge followed by :hg:`update --clean .` to
587 587 cancel the merge and leave the child of REV as a head to be
588 588 merged separately.
589 589
590 590 See :hg:`help dates` for a list of formats valid for -d/--date.
591 591
592 592 See :hg:`help revert` for a way to restore files to the state
593 593 of another revision.
594 594
595 595 Returns 0 on success, 1 if nothing to backout or there are unresolved
596 596 files.
597 597 '''
598 598 with repo.wlock(), repo.lock():
599 599 return _dobackout(ui, repo, node, rev, **opts)
600 600
601 601 def _dobackout(ui, repo, node=None, rev=None, **opts):
602 602 opts = pycompat.byteskwargs(opts)
603 603 if opts.get('commit') and opts.get('no_commit'):
604 604 raise error.Abort(_("cannot use --commit with --no-commit"))
605 605 if opts.get('merge') and opts.get('no_commit'):
606 606 raise error.Abort(_("cannot use --merge with --no-commit"))
607 607
608 608 if rev and node:
609 609 raise error.Abort(_("please specify just one revision"))
610 610
611 611 if not rev:
612 612 rev = node
613 613
614 614 if not rev:
615 615 raise error.Abort(_("please specify a revision to backout"))
616 616
617 617 date = opts.get('date')
618 618 if date:
619 619 opts['date'] = dateutil.parsedate(date)
620 620
621 621 cmdutil.checkunfinished(repo)
622 622 cmdutil.bailifchanged(repo)
623 623 node = scmutil.revsingle(repo, rev).node()
624 624
625 625 op1, op2 = repo.dirstate.parents()
626 626 if not repo.changelog.isancestor(node, op1):
627 627 raise error.Abort(_('cannot backout change that is not an ancestor'))
628 628
629 629 p1, p2 = repo.changelog.parents(node)
630 630 if p1 == nullid:
631 631 raise error.Abort(_('cannot backout a change with no parents'))
632 632 if p2 != nullid:
633 633 if not opts.get('parent'):
634 634 raise error.Abort(_('cannot backout a merge changeset'))
635 635 p = repo.lookup(opts['parent'])
636 636 if p not in (p1, p2):
637 637 raise error.Abort(_('%s is not a parent of %s') %
638 638 (short(p), short(node)))
639 639 parent = p
640 640 else:
641 641 if opts.get('parent'):
642 642 raise error.Abort(_('cannot use --parent on non-merge changeset'))
643 643 parent = p1
644 644
645 645 # the backout should appear on the same branch
646 646 branch = repo.dirstate.branch()
647 647 bheads = repo.branchheads(branch)
648 648 rctx = scmutil.revsingle(repo, hex(parent))
649 649 if not opts.get('merge') and op1 != node:
650 650 with dirstateguard.dirstateguard(repo, 'backout'):
651 651 overrides = {('ui', 'forcemerge'): opts.get('tool', '')}
652 652 with ui.configoverride(overrides, 'backout'):
653 653 stats = mergemod.update(repo, parent, branchmerge=True,
654 654 force=True, ancestor=node,
655 655 mergeancestor=False)
656 656 repo.setparents(op1, op2)
657 657 hg._showstats(repo, stats)
658 658 if stats.unresolvedcount:
659 659 repo.ui.status(_("use 'hg resolve' to retry unresolved "
660 660 "file merges\n"))
661 661 return 1
662 662 else:
663 663 hg.clean(repo, node, show_stats=False)
664 664 repo.dirstate.setbranch(branch)
665 665 cmdutil.revert(ui, repo, rctx, repo.dirstate.parents())
666 666
667 667 if opts.get('no_commit'):
668 668 msg = _("changeset %s backed out, "
669 669 "don't forget to commit.\n")
670 670 ui.status(msg % short(node))
671 671 return 0
672 672
673 673 def commitfunc(ui, repo, message, match, opts):
674 674 editform = 'backout'
675 675 e = cmdutil.getcommiteditor(editform=editform,
676 676 **pycompat.strkwargs(opts))
677 677 if not message:
678 678 # we don't translate commit messages
679 679 message = "Backed out changeset %s" % short(node)
680 680 e = cmdutil.getcommiteditor(edit=True, editform=editform)
681 681 return repo.commit(message, opts.get('user'), opts.get('date'),
682 682 match, editor=e)
683 683 newnode = cmdutil.commit(ui, repo, commitfunc, [], opts)
684 684 if not newnode:
685 685 ui.status(_("nothing changed\n"))
686 686 return 1
687 687 cmdutil.commitstatus(repo, newnode, branch, bheads)
688 688
689 689 def nice(node):
690 690 return '%d:%s' % (repo.changelog.rev(node), short(node))
691 691 ui.status(_('changeset %s backs out changeset %s\n') %
692 692 (nice(repo.changelog.tip()), nice(node)))
693 693 if opts.get('merge') and op1 != node:
694 694 hg.clean(repo, op1, show_stats=False)
695 695 ui.status(_('merging with changeset %s\n')
696 696 % nice(repo.changelog.tip()))
697 697 overrides = {('ui', 'forcemerge'): opts.get('tool', '')}
698 698 with ui.configoverride(overrides, 'backout'):
699 699 return hg.merge(repo, hex(repo.changelog.tip()))
700 700 return 0
701 701
702 702 @command('bisect',
703 703 [('r', 'reset', False, _('reset bisect state')),
704 704 ('g', 'good', False, _('mark changeset good')),
705 705 ('b', 'bad', False, _('mark changeset bad')),
706 706 ('s', 'skip', False, _('skip testing changeset')),
707 707 ('e', 'extend', False, _('extend the bisect range')),
708 708 ('c', 'command', '', _('use command to check changeset state'), _('CMD')),
709 709 ('U', 'noupdate', False, _('do not update to target'))],
710 710 _("[-gbsr] [-U] [-c CMD] [REV]"),
711 711 helpcategory=command.CATEGORY_CHANGE_NAVIGATION)
712 712 def bisect(ui, repo, rev=None, extra=None, command=None,
713 713 reset=None, good=None, bad=None, skip=None, extend=None,
714 714 noupdate=None):
715 715 """subdivision search of changesets
716 716
717 717 This command helps to find changesets which introduce problems. To
718 718 use, mark the earliest changeset you know exhibits the problem as
719 719 bad, then mark the latest changeset which is free from the problem
720 720 as good. Bisect will update your working directory to a revision
721 721 for testing (unless the -U/--noupdate option is specified). Once
722 722 you have performed tests, mark the working directory as good or
723 723 bad, and bisect will either update to another candidate changeset
724 724 or announce that it has found the bad revision.
725 725
726 726 As a shortcut, you can also use the revision argument to mark a
727 727 revision as good or bad without checking it out first.
728 728
729 729 If you supply a command, it will be used for automatic bisection.
730 730 The environment variable HG_NODE will contain the ID of the
731 731 changeset being tested. The exit status of the command will be
732 732 used to mark revisions as good or bad: status 0 means good, 125
733 733 means to skip the revision, 127 (command not found) will abort the
734 734 bisection, and any other non-zero exit status means the revision
735 735 is bad.
736 736
737 737 .. container:: verbose
738 738
739 739 Some examples:
740 740
741 741 - start a bisection with known bad revision 34, and good revision 12::
742 742
743 743 hg bisect --bad 34
744 744 hg bisect --good 12
745 745
746 746 - advance the current bisection by marking current revision as good or
747 747 bad::
748 748
749 749 hg bisect --good
750 750 hg bisect --bad
751 751
752 752 - mark the current revision, or a known revision, to be skipped (e.g. if
753 753 that revision is not usable because of another issue)::
754 754
755 755 hg bisect --skip
756 756 hg bisect --skip 23
757 757
758 758 - skip all revisions that do not touch directories ``foo`` or ``bar``::
759 759
760 760 hg bisect --skip "!( file('path:foo') & file('path:bar') )"
761 761
762 762 - forget the current bisection::
763 763
764 764 hg bisect --reset
765 765
766 766 - use 'make && make tests' to automatically find the first broken
767 767 revision::
768 768
769 769 hg bisect --reset
770 770 hg bisect --bad 34
771 771 hg bisect --good 12
772 772 hg bisect --command "make && make tests"
773 773
774 774 - see all changesets whose states are already known in the current
775 775 bisection::
776 776
777 777 hg log -r "bisect(pruned)"
778 778
779 779 - see the changeset currently being bisected (especially useful
780 780 if running with -U/--noupdate)::
781 781
782 782 hg log -r "bisect(current)"
783 783
784 784 - see all changesets that took part in the current bisection::
785 785
786 786 hg log -r "bisect(range)"
787 787
788 788 - you can even get a nice graph::
789 789
790 790 hg log --graph -r "bisect(range)"
791 791
792 792 See :hg:`help revisions.bisect` for more about the `bisect()` predicate.
793 793
794 794 Returns 0 on success.
795 795 """
796 796 # backward compatibility
797 797 if rev in "good bad reset init".split():
798 798 ui.warn(_("(use of 'hg bisect <cmd>' is deprecated)\n"))
799 799 cmd, rev, extra = rev, extra, None
800 800 if cmd == "good":
801 801 good = True
802 802 elif cmd == "bad":
803 803 bad = True
804 804 else:
805 805 reset = True
806 806 elif extra:
807 807 raise error.Abort(_('incompatible arguments'))
808 808
809 809 incompatibles = {
810 810 '--bad': bad,
811 811 '--command': bool(command),
812 812 '--extend': extend,
813 813 '--good': good,
814 814 '--reset': reset,
815 815 '--skip': skip,
816 816 }
817 817
818 818 enabled = [x for x in incompatibles if incompatibles[x]]
819 819
820 820 if len(enabled) > 1:
821 821 raise error.Abort(_('%s and %s are incompatible') %
822 822 tuple(sorted(enabled)[0:2]))
823 823
824 824 if reset:
825 825 hbisect.resetstate(repo)
826 826 return
827 827
828 828 state = hbisect.load_state(repo)
829 829
830 830 # update state
831 831 if good or bad or skip:
832 832 if rev:
833 833 nodes = [repo[i].node() for i in scmutil.revrange(repo, [rev])]
834 834 else:
835 835 nodes = [repo.lookup('.')]
836 836 if good:
837 837 state['good'] += nodes
838 838 elif bad:
839 839 state['bad'] += nodes
840 840 elif skip:
841 841 state['skip'] += nodes
842 842 hbisect.save_state(repo, state)
843 843 if not (state['good'] and state['bad']):
844 844 return
845 845
846 846 def mayupdate(repo, node, show_stats=True):
847 847 """common used update sequence"""
848 848 if noupdate:
849 849 return
850 850 cmdutil.checkunfinished(repo)
851 851 cmdutil.bailifchanged(repo)
852 852 return hg.clean(repo, node, show_stats=show_stats)
853 853
854 854 displayer = logcmdutil.changesetdisplayer(ui, repo, {})
855 855
856 856 if command:
857 857 changesets = 1
858 858 if noupdate:
859 859 try:
860 860 node = state['current'][0]
861 861 except LookupError:
862 862 raise error.Abort(_('current bisect revision is unknown - '
863 863 'start a new bisect to fix'))
864 864 else:
865 865 node, p2 = repo.dirstate.parents()
866 866 if p2 != nullid:
867 867 raise error.Abort(_('current bisect revision is a merge'))
868 868 if rev:
869 869 node = repo[scmutil.revsingle(repo, rev, node)].node()
870 870 try:
871 871 while changesets:
872 872 # update state
873 873 state['current'] = [node]
874 874 hbisect.save_state(repo, state)
875 875 status = ui.system(command, environ={'HG_NODE': hex(node)},
876 876 blockedtag='bisect_check')
877 877 if status == 125:
878 878 transition = "skip"
879 879 elif status == 0:
880 880 transition = "good"
881 881 # status < 0 means process was killed
882 882 elif status == 127:
883 883 raise error.Abort(_("failed to execute %s") % command)
884 884 elif status < 0:
885 885 raise error.Abort(_("%s killed") % command)
886 886 else:
887 887 transition = "bad"
888 888 state[transition].append(node)
889 889 ctx = repo[node]
890 890 ui.status(_('changeset %d:%s: %s\n') % (ctx.rev(), ctx,
891 891 transition))
892 892 hbisect.checkstate(state)
893 893 # bisect
894 894 nodes, changesets, bgood = hbisect.bisect(repo, state)
895 895 # update to next check
896 896 node = nodes[0]
897 897 mayupdate(repo, node, show_stats=False)
898 898 finally:
899 899 state['current'] = [node]
900 900 hbisect.save_state(repo, state)
901 901 hbisect.printresult(ui, repo, state, displayer, nodes, bgood)
902 902 return
903 903
904 904 hbisect.checkstate(state)
905 905
906 906 # actually bisect
907 907 nodes, changesets, good = hbisect.bisect(repo, state)
908 908 if extend:
909 909 if not changesets:
910 910 extendnode = hbisect.extendrange(repo, state, nodes, good)
911 911 if extendnode is not None:
912 912 ui.write(_("Extending search to changeset %d:%s\n")
913 913 % (extendnode.rev(), extendnode))
914 914 state['current'] = [extendnode.node()]
915 915 hbisect.save_state(repo, state)
916 916 return mayupdate(repo, extendnode.node())
917 917 raise error.Abort(_("nothing to extend"))
918 918
919 919 if changesets == 0:
920 920 hbisect.printresult(ui, repo, state, displayer, nodes, good)
921 921 else:
922 922 assert len(nodes) == 1 # only a single node can be tested next
923 923 node = nodes[0]
924 924 # compute the approximate number of remaining tests
925 925 tests, size = 0, 2
926 926 while size <= changesets:
927 927 tests, size = tests + 1, size * 2
928 928 rev = repo.changelog.rev(node)
929 929 ui.write(_("Testing changeset %d:%s "
930 930 "(%d changesets remaining, ~%d tests)\n")
931 931 % (rev, short(node), changesets, tests))
932 932 state['current'] = [node]
933 933 hbisect.save_state(repo, state)
934 934 return mayupdate(repo, node)
935 935
936 936 @command('bookmarks|bookmark',
937 937 [('f', 'force', False, _('force')),
938 938 ('r', 'rev', '', _('revision for bookmark action'), _('REV')),
939 939 ('d', 'delete', False, _('delete a given bookmark')),
940 940 ('m', 'rename', '', _('rename a given bookmark'), _('OLD')),
941 941 ('i', 'inactive', False, _('mark a bookmark inactive')),
942 942 ('l', 'list', False, _('list existing bookmarks')),
943 943 ] + formatteropts,
944 944 _('hg bookmarks [OPTIONS]... [NAME]...'),
945 945 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION)
946 946 def bookmark(ui, repo, *names, **opts):
947 947 '''create a new bookmark or list existing bookmarks
948 948
949 949 Bookmarks are labels on changesets to help track lines of development.
950 950 Bookmarks are unversioned and can be moved, renamed and deleted.
951 951 Deleting or moving a bookmark has no effect on the associated changesets.
952 952
953 953 Creating or updating to a bookmark causes it to be marked as 'active'.
954 954 The active bookmark is indicated with a '*'.
955 955 When a commit is made, the active bookmark will advance to the new commit.
956 956 A plain :hg:`update` will also advance an active bookmark, if possible.
957 957 Updating away from a bookmark will cause it to be deactivated.
958 958
959 959 Bookmarks can be pushed and pulled between repositories (see
960 960 :hg:`help push` and :hg:`help pull`). If a shared bookmark has
961 961 diverged, a new 'divergent bookmark' of the form 'name@path' will
962 962 be created. Using :hg:`merge` will resolve the divergence.
963 963
964 964 Specifying bookmark as '.' to -m/-d/-l options is equivalent to specifying
965 965 the active bookmark's name.
966 966
967 967 A bookmark named '@' has the special property that :hg:`clone` will
968 968 check it out by default if it exists.
969 969
970 970 .. container:: verbose
971 971
972 972 Template:
973 973
974 974 The following keywords are supported in addition to the common template
975 975 keywords and functions such as ``{bookmark}``. See also
976 976 :hg:`help templates`.
977 977
978 978 :active: Boolean. True if the bookmark is active.
979 979
980 980 Examples:
981 981
982 982 - create an active bookmark for a new line of development::
983 983
984 984 hg book new-feature
985 985
986 986 - create an inactive bookmark as a place marker::
987 987
988 988 hg book -i reviewed
989 989
990 990 - create an inactive bookmark on another changeset::
991 991
992 992 hg book -r .^ tested
993 993
994 994 - rename bookmark turkey to dinner::
995 995
996 996 hg book -m turkey dinner
997 997
998 998 - move the '@' bookmark from another branch::
999 999
1000 1000 hg book -f @
1001 1001
1002 1002 - print only the active bookmark name::
1003 1003
1004 1004 hg book -ql .
1005 1005 '''
1006 1006 opts = pycompat.byteskwargs(opts)
1007 1007 force = opts.get('force')
1008 1008 rev = opts.get('rev')
1009 1009 inactive = opts.get('inactive') # meaning add/rename to inactive bookmark
1010 1010
1011 1011 selactions = [k for k in ['delete', 'rename', 'list'] if opts.get(k)]
1012 1012 if len(selactions) > 1:
1013 1013 raise error.Abort(_('--%s and --%s are incompatible')
1014 1014 % tuple(selactions[:2]))
1015 1015 if selactions:
1016 1016 action = selactions[0]
1017 1017 elif names or rev:
1018 1018 action = 'add'
1019 1019 elif inactive:
1020 1020 action = 'inactive' # meaning deactivate
1021 1021 else:
1022 1022 action = 'list'
1023 1023
1024 1024 if rev and action in {'delete', 'rename', 'list'}:
1025 1025 raise error.Abort(_("--rev is incompatible with --%s") % action)
1026 1026 if inactive and action in {'delete', 'list'}:
1027 1027 raise error.Abort(_("--inactive is incompatible with --%s") % action)
1028 1028 if not names and action in {'add', 'delete'}:
1029 1029 raise error.Abort(_("bookmark name required"))
1030 1030
1031 1031 if action in {'add', 'delete', 'rename', 'inactive'}:
1032 1032 with repo.wlock(), repo.lock(), repo.transaction('bookmark') as tr:
1033 1033 if action == 'delete':
1034 1034 names = pycompat.maplist(repo._bookmarks.expandname, names)
1035 1035 bookmarks.delete(repo, tr, names)
1036 1036 elif action == 'rename':
1037 1037 if not names:
1038 1038 raise error.Abort(_("new bookmark name required"))
1039 1039 elif len(names) > 1:
1040 1040 raise error.Abort(_("only one new bookmark name allowed"))
1041 1041 oldname = repo._bookmarks.expandname(opts['rename'])
1042 1042 bookmarks.rename(repo, tr, oldname, names[0], force, inactive)
1043 1043 elif action == 'add':
1044 1044 bookmarks.addbookmarks(repo, tr, names, rev, force, inactive)
1045 1045 elif action == 'inactive':
1046 1046 if len(repo._bookmarks) == 0:
1047 1047 ui.status(_("no bookmarks set\n"))
1048 1048 elif not repo._activebookmark:
1049 1049 ui.status(_("no active bookmark\n"))
1050 1050 else:
1051 1051 bookmarks.deactivate(repo)
1052 1052 elif action == 'list':
1053 1053 names = pycompat.maplist(repo._bookmarks.expandname, names)
1054 1054 with ui.formatter('bookmarks', opts) as fm:
1055 1055 bookmarks.printbookmarks(ui, repo, fm, names)
1056 1056 else:
1057 1057 raise error.ProgrammingError('invalid action: %s' % action)
1058 1058
1059 1059 @command('branch',
1060 1060 [('f', 'force', None,
1061 1061 _('set branch name even if it shadows an existing branch')),
1062 1062 ('C', 'clean', None, _('reset branch name to parent branch name')),
1063 1063 ('r', 'rev', [], _('change branches of the given revs (EXPERIMENTAL)')),
1064 1064 ],
1065 1065 _('[-fC] [NAME]'),
1066 1066 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION)
1067 1067 def branch(ui, repo, label=None, **opts):
1068 1068 """set or show the current branch name
1069 1069
1070 1070 .. note::
1071 1071
1072 1072 Branch names are permanent and global. Use :hg:`bookmark` to create a
1073 1073 light-weight bookmark instead. See :hg:`help glossary` for more
1074 1074 information about named branches and bookmarks.
1075 1075
1076 1076 With no argument, show the current branch name. With one argument,
1077 1077 set the working directory branch name (the branch will not exist
1078 1078 in the repository until the next commit). Standard practice
1079 1079 recommends that primary development take place on the 'default'
1080 1080 branch.
1081 1081
1082 1082 Unless -f/--force is specified, branch will not let you set a
1083 1083 branch name that already exists.
1084 1084
1085 1085 Use -C/--clean to reset the working directory branch to that of
1086 1086 the parent of the working directory, negating a previous branch
1087 1087 change.
1088 1088
1089 1089 Use the command :hg:`update` to switch to an existing branch. Use
1090 1090 :hg:`commit --close-branch` to mark this branch head as closed.
1091 1091 When all heads of a branch are closed, the branch will be
1092 1092 considered closed.
1093 1093
1094 1094 Returns 0 on success.
1095 1095 """
1096 1096 opts = pycompat.byteskwargs(opts)
1097 1097 revs = opts.get('rev')
1098 1098 if label:
1099 1099 label = label.strip()
1100 1100
1101 1101 if not opts.get('clean') and not label:
1102 1102 if revs:
1103 1103 raise error.Abort(_("no branch name specified for the revisions"))
1104 1104 ui.write("%s\n" % repo.dirstate.branch())
1105 1105 return
1106 1106
1107 1107 with repo.wlock():
1108 1108 if opts.get('clean'):
1109 1109 label = repo['.'].branch()
1110 1110 repo.dirstate.setbranch(label)
1111 1111 ui.status(_('reset working directory to branch %s\n') % label)
1112 1112 elif label:
1113 1113
1114 1114 scmutil.checknewlabel(repo, label, 'branch')
1115 1115 if revs:
1116 1116 return cmdutil.changebranch(ui, repo, revs, label)
1117 1117
1118 1118 if not opts.get('force') and label in repo.branchmap():
1119 1119 if label not in [p.branch() for p in repo[None].parents()]:
1120 1120 raise error.Abort(_('a branch of the same name already'
1121 1121 ' exists'),
1122 1122 # i18n: "it" refers to an existing branch
1123 1123 hint=_("use 'hg update' to switch to it"))
1124 1124
1125 1125 repo.dirstate.setbranch(label)
1126 1126 ui.status(_('marked working directory as branch %s\n') % label)
1127 1127
1128 1128 # find any open named branches aside from default
1129 1129 others = [n for n, h, t, c in repo.branchmap().iterbranches()
1130 1130 if n != "default" and not c]
1131 1131 if not others:
1132 1132 ui.status(_('(branches are permanent and global, '
1133 1133 'did you want a bookmark?)\n'))
1134 1134
1135 1135 @command('branches',
1136 1136 [('a', 'active', False,
1137 1137 _('show only branches that have unmerged heads (DEPRECATED)')),
1138 1138 ('c', 'closed', False, _('show normal and closed branches')),
1139 1139 ('r', 'rev', [], _('show branch name(s) of the given rev'))
1140 1140 ] + formatteropts,
1141 1141 _('[-c]'),
1142 1142 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
1143 1143 intents={INTENT_READONLY})
1144 1144 def branches(ui, repo, active=False, closed=False, **opts):
1145 1145 """list repository named branches
1146 1146
1147 1147 List the repository's named branches, indicating which ones are
1148 1148 inactive. If -c/--closed is specified, also list branches which have
1149 1149 been marked closed (see :hg:`commit --close-branch`).
1150 1150
1151 1151 Use the command :hg:`update` to switch to an existing branch.
1152 1152
1153 1153 .. container:: verbose
1154 1154
1155 1155 Template:
1156 1156
1157 1157 The following keywords are supported in addition to the common template
1158 1158 keywords and functions such as ``{branch}``. See also
1159 1159 :hg:`help templates`.
1160 1160
1161 1161 :active: Boolean. True if the branch is active.
1162 1162 :closed: Boolean. True if the branch is closed.
1163 1163 :current: Boolean. True if it is the current branch.
1164 1164
1165 1165 Returns 0.
1166 1166 """
1167 1167
1168 1168 opts = pycompat.byteskwargs(opts)
1169 1169 revs = opts.get('rev')
1170 1170 selectedbranches = None
1171 1171 if revs:
1172 1172 revs = scmutil.revrange(repo, revs)
1173 1173 getbi = repo.revbranchcache().branchinfo
1174 1174 selectedbranches = {getbi(r)[0] for r in revs}
1175 1175
1176 1176 ui.pager('branches')
1177 1177 fm = ui.formatter('branches', opts)
1178 1178 hexfunc = fm.hexfunc
1179 1179
1180 1180 allheads = set(repo.heads())
1181 1181 branches = []
1182 1182 for tag, heads, tip, isclosed in repo.branchmap().iterbranches():
1183 1183 if selectedbranches is not None and tag not in selectedbranches:
1184 1184 continue
1185 1185 isactive = False
1186 1186 if not isclosed:
1187 1187 openheads = set(repo.branchmap().iteropen(heads))
1188 1188 isactive = bool(openheads & allheads)
1189 1189 branches.append((tag, repo[tip], isactive, not isclosed))
1190 1190 branches.sort(key=lambda i: (i[2], i[1].rev(), i[0], i[3]),
1191 1191 reverse=True)
1192 1192
1193 1193 for tag, ctx, isactive, isopen in branches:
1194 1194 if active and not isactive:
1195 1195 continue
1196 1196 if isactive:
1197 1197 label = 'branches.active'
1198 1198 notice = ''
1199 1199 elif not isopen:
1200 1200 if not closed:
1201 1201 continue
1202 1202 label = 'branches.closed'
1203 1203 notice = _(' (closed)')
1204 1204 else:
1205 1205 label = 'branches.inactive'
1206 1206 notice = _(' (inactive)')
1207 1207 current = (tag == repo.dirstate.branch())
1208 1208 if current:
1209 1209 label = 'branches.current'
1210 1210
1211 1211 fm.startitem()
1212 1212 fm.write('branch', '%s', tag, label=label)
1213 1213 rev = ctx.rev()
1214 1214 padsize = max(31 - len("%d" % rev) - encoding.colwidth(tag), 0)
1215 1215 fmt = ' ' * padsize + ' %d:%s'
1216 1216 fm.condwrite(not ui.quiet, 'rev node', fmt, rev, hexfunc(ctx.node()),
1217 1217 label='log.changeset changeset.%s' % ctx.phasestr())
1218 1218 fm.context(ctx=ctx)
1219 1219 fm.data(active=isactive, closed=not isopen, current=current)
1220 1220 if not ui.quiet:
1221 1221 fm.plain(notice)
1222 1222 fm.plain('\n')
1223 1223 fm.end()
1224 1224
1225 1225 @command('bundle',
1226 1226 [('f', 'force', None, _('run even when the destination is unrelated')),
1227 1227 ('r', 'rev', [], _('a changeset intended to be added to the destination'),
1228 1228 _('REV')),
1229 1229 ('b', 'branch', [], _('a specific branch you would like to bundle'),
1230 1230 _('BRANCH')),
1231 1231 ('', 'base', [],
1232 1232 _('a base changeset assumed to be available at the destination'),
1233 1233 _('REV')),
1234 1234 ('a', 'all', None, _('bundle all changesets in the repository')),
1235 1235 ('t', 'type', 'bzip2', _('bundle compression type to use'), _('TYPE')),
1236 1236 ] + remoteopts,
1237 1237 _('[-f] [-t BUNDLESPEC] [-a] [-r REV]... [--base REV]... FILE [DEST]'),
1238 1238 helpcategory=command.CATEGORY_IMPORT_EXPORT)
1239 1239 def bundle(ui, repo, fname, dest=None, **opts):
1240 1240 """create a bundle file
1241 1241
1242 1242 Generate a bundle file containing data to be transferred to another
1243 1243 repository.
1244 1244
1245 1245 To create a bundle containing all changesets, use -a/--all
1246 1246 (or --base null). Otherwise, hg assumes the destination will have
1247 1247 all the nodes you specify with --base parameters. Otherwise, hg
1248 1248 will assume the repository has all the nodes in destination, or
1249 1249 default-push/default if no destination is specified, where destination
1250 1250 is the repository you provide through DEST option.
1251 1251
1252 1252 You can change bundle format with the -t/--type option. See
1253 1253 :hg:`help bundlespec` for documentation on this format. By default,
1254 1254 the most appropriate format is used and compression defaults to
1255 1255 bzip2.
1256 1256
1257 1257 The bundle file can then be transferred using conventional means
1258 1258 and applied to another repository with the unbundle or pull
1259 1259 command. This is useful when direct push and pull are not
1260 1260 available or when exporting an entire repository is undesirable.
1261 1261
1262 1262 Applying bundles preserves all changeset contents including
1263 1263 permissions, copy/rename information, and revision history.
1264 1264
1265 1265 Returns 0 on success, 1 if no changes found.
1266 1266 """
1267 1267 opts = pycompat.byteskwargs(opts)
1268 1268 revs = None
1269 1269 if 'rev' in opts:
1270 1270 revstrings = opts['rev']
1271 1271 revs = scmutil.revrange(repo, revstrings)
1272 1272 if revstrings and not revs:
1273 1273 raise error.Abort(_('no commits to bundle'))
1274 1274
1275 1275 bundletype = opts.get('type', 'bzip2').lower()
1276 1276 try:
1277 1277 bundlespec = exchange.parsebundlespec(repo, bundletype, strict=False)
1278 1278 except error.UnsupportedBundleSpecification as e:
1279 1279 raise error.Abort(pycompat.bytestr(e),
1280 1280 hint=_("see 'hg help bundlespec' for supported "
1281 1281 "values for --type"))
1282 1282 cgversion = bundlespec.contentopts["cg.version"]
1283 1283
1284 1284 # Packed bundles are a pseudo bundle format for now.
1285 1285 if cgversion == 's1':
1286 1286 raise error.Abort(_('packed bundles cannot be produced by "hg bundle"'),
1287 1287 hint=_("use 'hg debugcreatestreamclonebundle'"))
1288 1288
1289 1289 if opts.get('all'):
1290 1290 if dest:
1291 1291 raise error.Abort(_("--all is incompatible with specifying "
1292 1292 "a destination"))
1293 1293 if opts.get('base'):
1294 1294 ui.warn(_("ignoring --base because --all was specified\n"))
1295 1295 base = [nullrev]
1296 1296 else:
1297 1297 base = scmutil.revrange(repo, opts.get('base'))
1298 1298 if cgversion not in changegroup.supportedoutgoingversions(repo):
1299 1299 raise error.Abort(_("repository does not support bundle version %s") %
1300 1300 cgversion)
1301 1301
1302 1302 if base:
1303 1303 if dest:
1304 1304 raise error.Abort(_("--base is incompatible with specifying "
1305 1305 "a destination"))
1306 1306 common = [repo[rev].node() for rev in base]
1307 1307 heads = [repo[r].node() for r in revs] if revs else None
1308 1308 outgoing = discovery.outgoing(repo, common, heads)
1309 1309 else:
1310 1310 dest = ui.expandpath(dest or 'default-push', dest or 'default')
1311 1311 dest, branches = hg.parseurl(dest, opts.get('branch'))
1312 1312 other = hg.peer(repo, opts, dest)
1313 1313 revs = [repo[r].hex() for r in revs]
1314 1314 revs, checkout = hg.addbranchrevs(repo, repo, branches, revs)
1315 1315 heads = revs and pycompat.maplist(repo.lookup, revs) or revs
1316 1316 outgoing = discovery.findcommonoutgoing(repo, other,
1317 1317 onlyheads=heads,
1318 1318 force=opts.get('force'),
1319 1319 portable=True)
1320 1320
1321 1321 if not outgoing.missing:
1322 1322 scmutil.nochangesfound(ui, repo, not base and outgoing.excluded)
1323 1323 return 1
1324 1324
1325 1325 if cgversion == '01': #bundle1
1326 1326 bversion = 'HG10' + bundlespec.wirecompression
1327 1327 bcompression = None
1328 1328 elif cgversion in ('02', '03'):
1329 1329 bversion = 'HG20'
1330 1330 bcompression = bundlespec.wirecompression
1331 1331 else:
1332 1332 raise error.ProgrammingError(
1333 1333 'bundle: unexpected changegroup version %s' % cgversion)
1334 1334
1335 1335 # TODO compression options should be derived from bundlespec parsing.
1336 1336 # This is a temporary hack to allow adjusting bundle compression
1337 1337 # level without a) formalizing the bundlespec changes to declare it
1338 1338 # b) introducing a command flag.
1339 1339 compopts = {}
1340 1340 complevel = ui.configint('experimental',
1341 1341 'bundlecomplevel.' + bundlespec.compression)
1342 1342 if complevel is None:
1343 1343 complevel = ui.configint('experimental', 'bundlecomplevel')
1344 1344 if complevel is not None:
1345 1345 compopts['level'] = complevel
1346 1346
1347 1347 # Allow overriding the bundling of obsmarker in phases through
1348 1348 # configuration while we don't have a bundle version that include them
1349 1349 if repo.ui.configbool('experimental', 'evolution.bundle-obsmarker'):
1350 1350 bundlespec.contentopts['obsolescence'] = True
1351 1351 if repo.ui.configbool('experimental', 'bundle-phases'):
1352 1352 bundlespec.contentopts['phases'] = True
1353 1353
1354 1354 bundle2.writenewbundle(ui, repo, 'bundle', fname, bversion, outgoing,
1355 1355 bundlespec.contentopts, compression=bcompression,
1356 1356 compopts=compopts)
1357 1357
1358 1358 @command('cat',
1359 1359 [('o', 'output', '',
1360 1360 _('print output to file with formatted name'), _('FORMAT')),
1361 1361 ('r', 'rev', '', _('print the given revision'), _('REV')),
1362 1362 ('', 'decode', None, _('apply any matching decode filter')),
1363 1363 ] + walkopts + formatteropts,
1364 1364 _('[OPTION]... FILE...'),
1365 1365 helpcategory=command.CATEGORY_FILE_CONTENTS,
1366 1366 inferrepo=True,
1367 1367 intents={INTENT_READONLY})
1368 1368 def cat(ui, repo, file1, *pats, **opts):
1369 1369 """output the current or given revision of files
1370 1370
1371 1371 Print the specified files as they were at the given revision. If
1372 1372 no revision is given, the parent of the working directory is used.
1373 1373
1374 1374 Output may be to a file, in which case the name of the file is
1375 1375 given using a template string. See :hg:`help templates`. In addition
1376 1376 to the common template keywords, the following formatting rules are
1377 1377 supported:
1378 1378
1379 1379 :``%%``: literal "%" character
1380 1380 :``%s``: basename of file being printed
1381 1381 :``%d``: dirname of file being printed, or '.' if in repository root
1382 1382 :``%p``: root-relative path name of file being printed
1383 1383 :``%H``: changeset hash (40 hexadecimal digits)
1384 1384 :``%R``: changeset revision number
1385 1385 :``%h``: short-form changeset hash (12 hexadecimal digits)
1386 1386 :``%r``: zero-padded changeset revision number
1387 1387 :``%b``: basename of the exporting repository
1388 1388 :``\\``: literal "\\" character
1389 1389
1390 1390 .. container:: verbose
1391 1391
1392 1392 Template:
1393 1393
1394 1394 The following keywords are supported in addition to the common template
1395 1395 keywords and functions. See also :hg:`help templates`.
1396 1396
1397 1397 :data: String. File content.
1398 1398 :path: String. Repository-absolute path of the file.
1399 1399
1400 1400 Returns 0 on success.
1401 1401 """
1402 1402 opts = pycompat.byteskwargs(opts)
1403 1403 rev = opts.get('rev')
1404 1404 if rev:
1405 1405 repo = scmutil.unhidehashlikerevs(repo, [rev], 'nowarn')
1406 1406 ctx = scmutil.revsingle(repo, rev)
1407 1407 m = scmutil.match(ctx, (file1,) + pats, opts)
1408 1408 fntemplate = opts.pop('output', '')
1409 1409 if cmdutil.isstdiofilename(fntemplate):
1410 1410 fntemplate = ''
1411 1411
1412 1412 if fntemplate:
1413 1413 fm = formatter.nullformatter(ui, 'cat', opts)
1414 1414 else:
1415 1415 ui.pager('cat')
1416 1416 fm = ui.formatter('cat', opts)
1417 1417 with fm:
1418 1418 return cmdutil.cat(ui, repo, ctx, m, fm, fntemplate, '',
1419 1419 **pycompat.strkwargs(opts))
1420 1420
1421 1421 @command('clone',
1422 1422 [('U', 'noupdate', None, _('the clone will include an empty working '
1423 1423 'directory (only a repository)')),
1424 1424 ('u', 'updaterev', '', _('revision, tag, or branch to check out'),
1425 1425 _('REV')),
1426 1426 ('r', 'rev', [], _('do not clone everything, but include this changeset'
1427 1427 ' and its ancestors'), _('REV')),
1428 1428 ('b', 'branch', [], _('do not clone everything, but include this branch\'s'
1429 1429 ' changesets and their ancestors'), _('BRANCH')),
1430 1430 ('', 'pull', None, _('use pull protocol to copy metadata')),
1431 1431 ('', 'uncompressed', None,
1432 1432 _('an alias to --stream (DEPRECATED)')),
1433 1433 ('', 'stream', None,
1434 1434 _('clone with minimal data processing')),
1435 1435 ] + remoteopts,
1436 1436 _('[OPTION]... SOURCE [DEST]'),
1437 1437 helpcategory=command.CATEGORY_REPO_CREATION,
1438 1438 helpbasic=True, norepo=True)
1439 1439 def clone(ui, source, dest=None, **opts):
1440 1440 """make a copy of an existing repository
1441 1441
1442 1442 Create a copy of an existing repository in a new directory.
1443 1443
1444 1444 If no destination directory name is specified, it defaults to the
1445 1445 basename of the source.
1446 1446
1447 1447 The location of the source is added to the new repository's
1448 1448 ``.hg/hgrc`` file, as the default to be used for future pulls.
1449 1449
1450 1450 Only local paths and ``ssh://`` URLs are supported as
1451 1451 destinations. For ``ssh://`` destinations, no working directory or
1452 1452 ``.hg/hgrc`` will be created on the remote side.
1453 1453
1454 1454 If the source repository has a bookmark called '@' set, that
1455 1455 revision will be checked out in the new repository by default.
1456 1456
1457 1457 To check out a particular version, use -u/--update, or
1458 1458 -U/--noupdate to create a clone with no working directory.
1459 1459
1460 1460 To pull only a subset of changesets, specify one or more revisions
1461 1461 identifiers with -r/--rev or branches with -b/--branch. The
1462 1462 resulting clone will contain only the specified changesets and
1463 1463 their ancestors. These options (or 'clone src#rev dest') imply
1464 1464 --pull, even for local source repositories.
1465 1465
1466 1466 In normal clone mode, the remote normalizes repository data into a common
1467 1467 exchange format and the receiving end translates this data into its local
1468 1468 storage format. --stream activates a different clone mode that essentially
1469 1469 copies repository files from the remote with minimal data processing. This
1470 1470 significantly reduces the CPU cost of a clone both remotely and locally.
1471 1471 However, it often increases the transferred data size by 30-40%. This can
1472 1472 result in substantially faster clones where I/O throughput is plentiful,
1473 1473 especially for larger repositories. A side-effect of --stream clones is
1474 1474 that storage settings and requirements on the remote are applied locally:
1475 1475 a modern client may inherit legacy or inefficient storage used by the
1476 1476 remote or a legacy Mercurial client may not be able to clone from a
1477 1477 modern Mercurial remote.
1478 1478
1479 1479 .. note::
1480 1480
1481 1481 Specifying a tag will include the tagged changeset but not the
1482 1482 changeset containing the tag.
1483 1483
1484 1484 .. container:: verbose
1485 1485
1486 1486 For efficiency, hardlinks are used for cloning whenever the
1487 1487 source and destination are on the same filesystem (note this
1488 1488 applies only to the repository data, not to the working
1489 1489 directory). Some filesystems, such as AFS, implement hardlinking
1490 1490 incorrectly, but do not report errors. In these cases, use the
1491 1491 --pull option to avoid hardlinking.
1492 1492
1493 1493 Mercurial will update the working directory to the first applicable
1494 1494 revision from this list:
1495 1495
1496 1496 a) null if -U or the source repository has no changesets
1497 1497 b) if -u . and the source repository is local, the first parent of
1498 1498 the source repository's working directory
1499 1499 c) the changeset specified with -u (if a branch name, this means the
1500 1500 latest head of that branch)
1501 1501 d) the changeset specified with -r
1502 1502 e) the tipmost head specified with -b
1503 1503 f) the tipmost head specified with the url#branch source syntax
1504 1504 g) the revision marked with the '@' bookmark, if present
1505 1505 h) the tipmost head of the default branch
1506 1506 i) tip
1507 1507
1508 1508 When cloning from servers that support it, Mercurial may fetch
1509 1509 pre-generated data from a server-advertised URL or inline from the
1510 1510 same stream. When this is done, hooks operating on incoming changesets
1511 1511 and changegroups may fire more than once, once for each pre-generated
1512 1512 bundle and as well as for any additional remaining data. In addition,
1513 1513 if an error occurs, the repository may be rolled back to a partial
1514 1514 clone. This behavior may change in future releases.
1515 1515 See :hg:`help -e clonebundles` for more.
1516 1516
1517 1517 Examples:
1518 1518
1519 1519 - clone a remote repository to a new directory named hg/::
1520 1520
1521 1521 hg clone https://www.mercurial-scm.org/repo/hg/
1522 1522
1523 1523 - create a lightweight local clone::
1524 1524
1525 1525 hg clone project/ project-feature/
1526 1526
1527 1527 - clone from an absolute path on an ssh server (note double-slash)::
1528 1528
1529 1529 hg clone ssh://user@server//home/projects/alpha/
1530 1530
1531 1531 - do a streaming clone while checking out a specified version::
1532 1532
1533 1533 hg clone --stream http://server/repo -u 1.5
1534 1534
1535 1535 - create a repository without changesets after a particular revision::
1536 1536
1537 1537 hg clone -r 04e544 experimental/ good/
1538 1538
1539 1539 - clone (and track) a particular named branch::
1540 1540
1541 1541 hg clone https://www.mercurial-scm.org/repo/hg/#stable
1542 1542
1543 1543 See :hg:`help urls` for details on specifying URLs.
1544 1544
1545 1545 Returns 0 on success.
1546 1546 """
1547 1547 opts = pycompat.byteskwargs(opts)
1548 1548 if opts.get('noupdate') and opts.get('updaterev'):
1549 1549 raise error.Abort(_("cannot specify both --noupdate and --updaterev"))
1550 1550
1551 1551 # --include/--exclude can come from narrow or sparse.
1552 1552 includepats, excludepats = None, None
1553 1553
1554 1554 # hg.clone() differentiates between None and an empty set. So make sure
1555 1555 # patterns are sets if narrow is requested without patterns.
1556 1556 if opts.get('narrow'):
1557 1557 includepats = set()
1558 1558 excludepats = set()
1559 1559
1560 1560 if opts.get('include'):
1561 1561 includepats = narrowspec.parsepatterns(opts.get('include'))
1562 1562 if opts.get('exclude'):
1563 1563 excludepats = narrowspec.parsepatterns(opts.get('exclude'))
1564 1564
1565 1565 r = hg.clone(ui, opts, source, dest,
1566 1566 pull=opts.get('pull'),
1567 1567 stream=opts.get('stream') or opts.get('uncompressed'),
1568 1568 revs=opts.get('rev'),
1569 1569 update=opts.get('updaterev') or not opts.get('noupdate'),
1570 1570 branch=opts.get('branch'),
1571 1571 shareopts=opts.get('shareopts'),
1572 1572 storeincludepats=includepats,
1573 1573 storeexcludepats=excludepats,
1574 1574 depth=opts.get('depth') or None)
1575 1575
1576 1576 return r is None
1577 1577
1578 1578 @command('commit|ci',
1579 1579 [('A', 'addremove', None,
1580 1580 _('mark new/missing files as added/removed before committing')),
1581 1581 ('', 'close-branch', None,
1582 1582 _('mark a branch head as closed')),
1583 1583 ('', 'amend', None, _('amend the parent of the working directory')),
1584 1584 ('s', 'secret', None, _('use the secret phase for committing')),
1585 1585 ('e', 'edit', None, _('invoke editor on commit messages')),
1586 1586 ('i', 'interactive', None, _('use interactive mode')),
1587 1587 ] + walkopts + commitopts + commitopts2 + subrepoopts,
1588 1588 _('[OPTION]... [FILE]...'),
1589 1589 helpcategory=command.CATEGORY_COMMITTING, helpbasic=True,
1590 1590 inferrepo=True)
1591 1591 def commit(ui, repo, *pats, **opts):
1592 1592 """commit the specified files or all outstanding changes
1593 1593
1594 1594 Commit changes to the given files into the repository. Unlike a
1595 1595 centralized SCM, this operation is a local operation. See
1596 1596 :hg:`push` for a way to actively distribute your changes.
1597 1597
1598 1598 If a list of files is omitted, all changes reported by :hg:`status`
1599 1599 will be committed.
1600 1600
1601 1601 If you are committing the result of a merge, do not provide any
1602 1602 filenames or -I/-X filters.
1603 1603
1604 1604 If no commit message is specified, Mercurial starts your
1605 1605 configured editor where you can enter a message. In case your
1606 1606 commit fails, you will find a backup of your message in
1607 1607 ``.hg/last-message.txt``.
1608 1608
1609 1609 The --close-branch flag can be used to mark the current branch
1610 1610 head closed. When all heads of a branch are closed, the branch
1611 1611 will be considered closed and no longer listed.
1612 1612
1613 1613 The --amend flag can be used to amend the parent of the
1614 1614 working directory with a new commit that contains the changes
1615 1615 in the parent in addition to those currently reported by :hg:`status`,
1616 1616 if there are any. The old commit is stored in a backup bundle in
1617 1617 ``.hg/strip-backup`` (see :hg:`help bundle` and :hg:`help unbundle`
1618 1618 on how to restore it).
1619 1619
1620 1620 Message, user and date are taken from the amended commit unless
1621 1621 specified. When a message isn't specified on the command line,
1622 1622 the editor will open with the message of the amended commit.
1623 1623
1624 1624 It is not possible to amend public changesets (see :hg:`help phases`)
1625 1625 or changesets that have children.
1626 1626
1627 1627 See :hg:`help dates` for a list of formats valid for -d/--date.
1628 1628
1629 1629 Returns 0 on success, 1 if nothing changed.
1630 1630
1631 1631 .. container:: verbose
1632 1632
1633 1633 Examples:
1634 1634
1635 1635 - commit all files ending in .py::
1636 1636
1637 1637 hg commit --include "set:**.py"
1638 1638
1639 1639 - commit all non-binary files::
1640 1640
1641 1641 hg commit --exclude "set:binary()"
1642 1642
1643 1643 - amend the current commit and set the date to now::
1644 1644
1645 1645 hg commit --amend --date now
1646 1646 """
1647 1647 with repo.wlock(), repo.lock():
1648 1648 return _docommit(ui, repo, *pats, **opts)
1649 1649
1650 1650 def _docommit(ui, repo, *pats, **opts):
1651 1651 if opts.get(r'interactive'):
1652 1652 opts.pop(r'interactive')
1653 1653 ret = cmdutil.dorecord(ui, repo, commit, None, False,
1654 1654 cmdutil.recordfilter, *pats,
1655 1655 **opts)
1656 1656 # ret can be 0 (no changes to record) or the value returned by
1657 1657 # commit(), 1 if nothing changed or None on success.
1658 1658 return 1 if ret == 0 else ret
1659 1659
1660 1660 opts = pycompat.byteskwargs(opts)
1661 1661 if opts.get('subrepos'):
1662 1662 if opts.get('amend'):
1663 1663 raise error.Abort(_('cannot amend with --subrepos'))
1664 1664 # Let --subrepos on the command line override config setting.
1665 1665 ui.setconfig('ui', 'commitsubrepos', True, 'commit')
1666 1666
1667 1667 cmdutil.checkunfinished(repo, commit=True)
1668 1668
1669 1669 branch = repo[None].branch()
1670 1670 bheads = repo.branchheads(branch)
1671 1671
1672 1672 extra = {}
1673 1673 if opts.get('close_branch'):
1674 1674 extra['close'] = '1'
1675 1675
1676 1676 if not bheads:
1677 1677 raise error.Abort(_('can only close branch heads'))
1678 1678 elif opts.get('amend'):
1679 1679 if repo['.'].p1().branch() != branch and \
1680 1680 repo['.'].p2().branch() != branch:
1681 1681 raise error.Abort(_('can only close branch heads'))
1682 1682
1683 1683 if opts.get('amend'):
1684 1684 if ui.configbool('ui', 'commitsubrepos'):
1685 1685 raise error.Abort(_('cannot amend with ui.commitsubrepos enabled'))
1686 1686
1687 1687 old = repo['.']
1688 1688 rewriteutil.precheck(repo, [old.rev()], 'amend')
1689 1689
1690 1690 # Currently histedit gets confused if an amend happens while histedit
1691 1691 # is in progress. Since we have a checkunfinished command, we are
1692 1692 # temporarily honoring it.
1693 1693 #
1694 1694 # Note: eventually this guard will be removed. Please do not expect
1695 1695 # this behavior to remain.
1696 1696 if not obsolete.isenabled(repo, obsolete.createmarkersopt):
1697 1697 cmdutil.checkunfinished(repo)
1698 1698
1699 1699 node = cmdutil.amend(ui, repo, old, extra, pats, opts)
1700 1700 if node == old.node():
1701 1701 ui.status(_("nothing changed\n"))
1702 1702 return 1
1703 1703 else:
1704 1704 def commitfunc(ui, repo, message, match, opts):
1705 1705 overrides = {}
1706 1706 if opts.get('secret'):
1707 1707 overrides[('phases', 'new-commit')] = 'secret'
1708 1708
1709 1709 baseui = repo.baseui
1710 1710 with baseui.configoverride(overrides, 'commit'):
1711 1711 with ui.configoverride(overrides, 'commit'):
1712 1712 editform = cmdutil.mergeeditform(repo[None],
1713 1713 'commit.normal')
1714 1714 editor = cmdutil.getcommiteditor(
1715 1715 editform=editform, **pycompat.strkwargs(opts))
1716 1716 return repo.commit(message,
1717 1717 opts.get('user'),
1718 1718 opts.get('date'),
1719 1719 match,
1720 1720 editor=editor,
1721 1721 extra=extra)
1722 1722
1723 1723 node = cmdutil.commit(ui, repo, commitfunc, pats, opts)
1724 1724
1725 1725 if not node:
1726 1726 stat = cmdutil.postcommitstatus(repo, pats, opts)
1727 1727 if stat[3]:
1728 1728 ui.status(_("nothing changed (%d missing files, see "
1729 1729 "'hg status')\n") % len(stat[3]))
1730 1730 else:
1731 1731 ui.status(_("nothing changed\n"))
1732 1732 return 1
1733 1733
1734 1734 cmdutil.commitstatus(repo, node, branch, bheads, opts)
1735 1735
1736 1736 @command('config|showconfig|debugconfig',
1737 1737 [('u', 'untrusted', None, _('show untrusted configuration options')),
1738 1738 ('e', 'edit', None, _('edit user config')),
1739 1739 ('l', 'local', None, _('edit repository config')),
1740 1740 ('g', 'global', None, _('edit global config'))] + formatteropts,
1741 1741 _('[-u] [NAME]...'),
1742 1742 helpcategory=command.CATEGORY_HELP,
1743 1743 optionalrepo=True,
1744 1744 intents={INTENT_READONLY})
1745 1745 def config(ui, repo, *values, **opts):
1746 1746 """show combined config settings from all hgrc files
1747 1747
1748 1748 With no arguments, print names and values of all config items.
1749 1749
1750 1750 With one argument of the form section.name, print just the value
1751 1751 of that config item.
1752 1752
1753 1753 With multiple arguments, print names and values of all config
1754 1754 items with matching section names or section.names.
1755 1755
1756 1756 With --edit, start an editor on the user-level config file. With
1757 1757 --global, edit the system-wide config file. With --local, edit the
1758 1758 repository-level config file.
1759 1759
1760 1760 With --debug, the source (filename and line number) is printed
1761 1761 for each config item.
1762 1762
1763 1763 See :hg:`help config` for more information about config files.
1764 1764
1765 1765 .. container:: verbose
1766 1766
1767 1767 Template:
1768 1768
1769 1769 The following keywords are supported. See also :hg:`help templates`.
1770 1770
1771 1771 :name: String. Config name.
1772 1772 :source: String. Filename and line number where the item is defined.
1773 1773 :value: String. Config value.
1774 1774
1775 1775 Returns 0 on success, 1 if NAME does not exist.
1776 1776
1777 1777 """
1778 1778
1779 1779 opts = pycompat.byteskwargs(opts)
1780 1780 if opts.get('edit') or opts.get('local') or opts.get('global'):
1781 1781 if opts.get('local') and opts.get('global'):
1782 1782 raise error.Abort(_("can't use --local and --global together"))
1783 1783
1784 1784 if opts.get('local'):
1785 1785 if not repo:
1786 1786 raise error.Abort(_("can't use --local outside a repository"))
1787 1787 paths = [repo.vfs.join('hgrc')]
1788 1788 elif opts.get('global'):
1789 1789 paths = rcutil.systemrcpath()
1790 1790 else:
1791 1791 paths = rcutil.userrcpath()
1792 1792
1793 1793 for f in paths:
1794 1794 if os.path.exists(f):
1795 1795 break
1796 1796 else:
1797 1797 if opts.get('global'):
1798 1798 samplehgrc = uimod.samplehgrcs['global']
1799 1799 elif opts.get('local'):
1800 1800 samplehgrc = uimod.samplehgrcs['local']
1801 1801 else:
1802 1802 samplehgrc = uimod.samplehgrcs['user']
1803 1803
1804 1804 f = paths[0]
1805 1805 fp = open(f, "wb")
1806 1806 fp.write(util.tonativeeol(samplehgrc))
1807 1807 fp.close()
1808 1808
1809 1809 editor = ui.geteditor()
1810 1810 ui.system("%s \"%s\"" % (editor, f),
1811 1811 onerr=error.Abort, errprefix=_("edit failed"),
1812 1812 blockedtag='config_edit')
1813 1813 return
1814 1814 ui.pager('config')
1815 1815 fm = ui.formatter('config', opts)
1816 1816 for t, f in rcutil.rccomponents():
1817 1817 if t == 'path':
1818 1818 ui.debug('read config from: %s\n' % f)
1819 1819 elif t == 'items':
1820 1820 for section, name, value, source in f:
1821 1821 ui.debug('set config by: %s\n' % source)
1822 1822 else:
1823 1823 raise error.ProgrammingError('unknown rctype: %s' % t)
1824 1824 untrusted = bool(opts.get('untrusted'))
1825 1825
1826 1826 selsections = selentries = []
1827 1827 if values:
1828 1828 selsections = [v for v in values if '.' not in v]
1829 1829 selentries = [v for v in values if '.' in v]
1830 1830 uniquesel = (len(selentries) == 1 and not selsections)
1831 1831 selsections = set(selsections)
1832 1832 selentries = set(selentries)
1833 1833
1834 1834 matched = False
1835 1835 for section, name, value in ui.walkconfig(untrusted=untrusted):
1836 1836 source = ui.configsource(section, name, untrusted)
1837 1837 value = pycompat.bytestr(value)
1838 1838 if fm.isplain():
1839 1839 source = source or 'none'
1840 1840 value = value.replace('\n', '\\n')
1841 1841 entryname = section + '.' + name
1842 1842 if values and not (section in selsections or entryname in selentries):
1843 1843 continue
1844 1844 fm.startitem()
1845 1845 fm.condwrite(ui.debugflag, 'source', '%s: ', source)
1846 1846 if uniquesel:
1847 1847 fm.data(name=entryname)
1848 1848 fm.write('value', '%s\n', value)
1849 1849 else:
1850 1850 fm.write('name value', '%s=%s\n', entryname, value)
1851 1851 matched = True
1852 1852 fm.end()
1853 1853 if matched:
1854 1854 return 0
1855 1855 return 1
1856 1856
1857 1857 @command('copy|cp',
1858 1858 [('A', 'after', None, _('record a copy that has already occurred')),
1859 1859 ('f', 'force', None, _('forcibly copy over an existing managed file')),
1860 1860 ] + walkopts + dryrunopts,
1861 1861 _('[OPTION]... [SOURCE]... DEST'),
1862 1862 helpcategory=command.CATEGORY_FILE_CONTENTS)
1863 1863 def copy(ui, repo, *pats, **opts):
1864 1864 """mark files as copied for the next commit
1865 1865
1866 1866 Mark dest as having copies of source files. If dest is a
1867 1867 directory, copies are put in that directory. If dest is a file,
1868 1868 the source must be a single file.
1869 1869
1870 1870 By default, this command copies the contents of files as they
1871 1871 exist in the working directory. If invoked with -A/--after, the
1872 1872 operation is recorded, but no copying is performed.
1873 1873
1874 1874 This command takes effect with the next commit. To undo a copy
1875 1875 before that, see :hg:`revert`.
1876 1876
1877 1877 Returns 0 on success, 1 if errors are encountered.
1878 1878 """
1879 1879 opts = pycompat.byteskwargs(opts)
1880 1880 with repo.wlock(False):
1881 1881 return cmdutil.copy(ui, repo, pats, opts)
1882 1882
1883 1883 @command(
1884 1884 'debugcommands', [], _('[COMMAND]'),
1885 1885 helpcategory=command.CATEGORY_HELP,
1886 1886 norepo=True)
1887 1887 def debugcommands(ui, cmd='', *args):
1888 1888 """list all available commands and options"""
1889 1889 for cmd, vals in sorted(table.iteritems()):
1890 1890 cmd = cmd.split('|')[0]
1891 1891 opts = ', '.join([i[1] for i in vals[1]])
1892 1892 ui.write('%s: %s\n' % (cmd, opts))
1893 1893
1894 1894 @command('debugcomplete',
1895 1895 [('o', 'options', None, _('show the command options'))],
1896 1896 _('[-o] CMD'),
1897 1897 helpcategory=command.CATEGORY_HELP,
1898 1898 norepo=True)
1899 1899 def debugcomplete(ui, cmd='', **opts):
1900 1900 """returns the completion list associated with the given command"""
1901 1901
1902 1902 if opts.get(r'options'):
1903 1903 options = []
1904 1904 otables = [globalopts]
1905 1905 if cmd:
1906 1906 aliases, entry = cmdutil.findcmd(cmd, table, False)
1907 1907 otables.append(entry[1])
1908 1908 for t in otables:
1909 1909 for o in t:
1910 1910 if "(DEPRECATED)" in o[3]:
1911 1911 continue
1912 1912 if o[0]:
1913 1913 options.append('-%s' % o[0])
1914 1914 options.append('--%s' % o[1])
1915 1915 ui.write("%s\n" % "\n".join(options))
1916 1916 return
1917 1917
1918 1918 cmdlist, unused_allcmds = cmdutil.findpossible(cmd, table)
1919 1919 if ui.verbose:
1920 1920 cmdlist = [' '.join(c[0]) for c in cmdlist.values()]
1921 1921 ui.write("%s\n" % "\n".join(sorted(cmdlist)))
1922 1922
1923 1923 @command('diff',
1924 1924 [('r', 'rev', [], _('revision'), _('REV')),
1925 1925 ('c', 'change', '', _('change made by revision'), _('REV'))
1926 1926 ] + diffopts + diffopts2 + walkopts + subrepoopts,
1927 1927 _('[OPTION]... ([-c REV] | [-r REV1 [-r REV2]]) [FILE]...'),
1928 1928 helpcategory=command.CATEGORY_FILE_CONTENTS,
1929 1929 helpbasic=True, inferrepo=True, intents={INTENT_READONLY})
1930 1930 def diff(ui, repo, *pats, **opts):
1931 1931 """diff repository (or selected files)
1932 1932
1933 1933 Show differences between revisions for the specified files.
1934 1934
1935 1935 Differences between files are shown using the unified diff format.
1936 1936
1937 1937 .. note::
1938 1938
1939 1939 :hg:`diff` may generate unexpected results for merges, as it will
1940 1940 default to comparing against the working directory's first
1941 1941 parent changeset if no revisions are specified.
1942 1942
1943 1943 When two revision arguments are given, then changes are shown
1944 1944 between those revisions. If only one revision is specified then
1945 1945 that revision is compared to the working directory, and, when no
1946 1946 revisions are specified, the working directory files are compared
1947 1947 to its first parent.
1948 1948
1949 1949 Alternatively you can specify -c/--change with a revision to see
1950 1950 the changes in that changeset relative to its first parent.
1951 1951
1952 1952 Without the -a/--text option, diff will avoid generating diffs of
1953 1953 files it detects as binary. With -a, diff will generate a diff
1954 1954 anyway, probably with undesirable results.
1955 1955
1956 1956 Use the -g/--git option to generate diffs in the git extended diff
1957 1957 format. For more information, read :hg:`help diffs`.
1958 1958
1959 1959 .. container:: verbose
1960 1960
1961 1961 Examples:
1962 1962
1963 1963 - compare a file in the current working directory to its parent::
1964 1964
1965 1965 hg diff foo.c
1966 1966
1967 1967 - compare two historical versions of a directory, with rename info::
1968 1968
1969 1969 hg diff --git -r 1.0:1.2 lib/
1970 1970
1971 1971 - get change stats relative to the last change on some date::
1972 1972
1973 1973 hg diff --stat -r "date('may 2')"
1974 1974
1975 1975 - diff all newly-added files that contain a keyword::
1976 1976
1977 1977 hg diff "set:added() and grep(GNU)"
1978 1978
1979 1979 - compare a revision and its parents::
1980 1980
1981 1981 hg diff -c 9353 # compare against first parent
1982 1982 hg diff -r 9353^:9353 # same using revset syntax
1983 1983 hg diff -r 9353^2:9353 # compare against the second parent
1984 1984
1985 1985 Returns 0 on success.
1986 1986 """
1987 1987
1988 1988 opts = pycompat.byteskwargs(opts)
1989 1989 revs = opts.get('rev')
1990 1990 change = opts.get('change')
1991 1991 stat = opts.get('stat')
1992 1992 reverse = opts.get('reverse')
1993 1993
1994 1994 if revs and change:
1995 1995 msg = _('cannot specify --rev and --change at the same time')
1996 1996 raise error.Abort(msg)
1997 1997 elif change:
1998 1998 repo = scmutil.unhidehashlikerevs(repo, [change], 'nowarn')
1999 1999 ctx2 = scmutil.revsingle(repo, change, None)
2000 2000 ctx1 = ctx2.p1()
2001 2001 else:
2002 2002 repo = scmutil.unhidehashlikerevs(repo, revs, 'nowarn')
2003 2003 ctx1, ctx2 = scmutil.revpair(repo, revs)
2004 2004 node1, node2 = ctx1.node(), ctx2.node()
2005 2005
2006 2006 if reverse:
2007 2007 node1, node2 = node2, node1
2008 2008
2009 2009 diffopts = patch.diffallopts(ui, opts)
2010 2010 m = scmutil.match(ctx2, pats, opts)
2011 2011 m = repo.narrowmatch(m)
2012 2012 ui.pager('diff')
2013 2013 logcmdutil.diffordiffstat(ui, repo, diffopts, node1, node2, m, stat=stat,
2014 2014 listsubrepos=opts.get('subrepos'),
2015 2015 root=opts.get('root'))
2016 2016
2017 2017 @command('export',
2018 2018 [('B', 'bookmark', '',
2019 2019 _('export changes only reachable by given bookmark'), _('BOOKMARK')),
2020 2020 ('o', 'output', '',
2021 2021 _('print output to file with formatted name'), _('FORMAT')),
2022 2022 ('', 'switch-parent', None, _('diff against the second parent')),
2023 2023 ('r', 'rev', [], _('revisions to export'), _('REV')),
2024 2024 ] + diffopts + formatteropts,
2025 2025 _('[OPTION]... [-o OUTFILESPEC] [-r] [REV]...'),
2026 2026 helpcategory=command.CATEGORY_IMPORT_EXPORT,
2027 2027 helpbasic=True, intents={INTENT_READONLY})
2028 2028 def export(ui, repo, *changesets, **opts):
2029 2029 """dump the header and diffs for one or more changesets
2030 2030
2031 2031 Print the changeset header and diffs for one or more revisions.
2032 2032 If no revision is given, the parent of the working directory is used.
2033 2033
2034 2034 The information shown in the changeset header is: author, date,
2035 2035 branch name (if non-default), changeset hash, parent(s) and commit
2036 2036 comment.
2037 2037
2038 2038 .. note::
2039 2039
2040 2040 :hg:`export` may generate unexpected diff output for merge
2041 2041 changesets, as it will compare the merge changeset against its
2042 2042 first parent only.
2043 2043
2044 2044 Output may be to a file, in which case the name of the file is
2045 2045 given using a template string. See :hg:`help templates`. In addition
2046 2046 to the common template keywords, the following formatting rules are
2047 2047 supported:
2048 2048
2049 2049 :``%%``: literal "%" character
2050 2050 :``%H``: changeset hash (40 hexadecimal digits)
2051 2051 :``%N``: number of patches being generated
2052 2052 :``%R``: changeset revision number
2053 2053 :``%b``: basename of the exporting repository
2054 2054 :``%h``: short-form changeset hash (12 hexadecimal digits)
2055 2055 :``%m``: first line of the commit message (only alphanumeric characters)
2056 2056 :``%n``: zero-padded sequence number, starting at 1
2057 2057 :``%r``: zero-padded changeset revision number
2058 2058 :``\\``: literal "\\" character
2059 2059
2060 2060 Without the -a/--text option, export will avoid generating diffs
2061 2061 of files it detects as binary. With -a, export will generate a
2062 2062 diff anyway, probably with undesirable results.
2063 2063
2064 2064 With -B/--bookmark changesets reachable by the given bookmark are
2065 2065 selected.
2066 2066
2067 2067 Use the -g/--git option to generate diffs in the git extended diff
2068 2068 format. See :hg:`help diffs` for more information.
2069 2069
2070 2070 With the --switch-parent option, the diff will be against the
2071 2071 second parent. It can be useful to review a merge.
2072 2072
2073 2073 .. container:: verbose
2074 2074
2075 2075 Template:
2076 2076
2077 2077 The following keywords are supported in addition to the common template
2078 2078 keywords and functions. See also :hg:`help templates`.
2079 2079
2080 2080 :diff: String. Diff content.
2081 2081 :parents: List of strings. Parent nodes of the changeset.
2082 2082
2083 2083 Examples:
2084 2084
2085 2085 - use export and import to transplant a bugfix to the current
2086 2086 branch::
2087 2087
2088 2088 hg export -r 9353 | hg import -
2089 2089
2090 2090 - export all the changesets between two revisions to a file with
2091 2091 rename information::
2092 2092
2093 2093 hg export --git -r 123:150 > changes.txt
2094 2094
2095 2095 - split outgoing changes into a series of patches with
2096 2096 descriptive names::
2097 2097
2098 2098 hg export -r "outgoing()" -o "%n-%m.patch"
2099 2099
2100 2100 Returns 0 on success.
2101 2101 """
2102 2102 opts = pycompat.byteskwargs(opts)
2103 2103 bookmark = opts.get('bookmark')
2104 2104 changesets += tuple(opts.get('rev', []))
2105 2105
2106 2106 if bookmark and changesets:
2107 2107 raise error.Abort(_("-r and -B are mutually exclusive"))
2108 2108
2109 2109 if bookmark:
2110 2110 if bookmark not in repo._bookmarks:
2111 2111 raise error.Abort(_("bookmark '%s' not found") % bookmark)
2112 2112
2113 2113 revs = scmutil.bookmarkrevs(repo, bookmark)
2114 2114 else:
2115 2115 if not changesets:
2116 2116 changesets = ['.']
2117 2117
2118 2118 repo = scmutil.unhidehashlikerevs(repo, changesets, 'nowarn')
2119 2119 revs = scmutil.revrange(repo, changesets)
2120 2120
2121 2121 if not revs:
2122 2122 raise error.Abort(_("export requires at least one changeset"))
2123 2123 if len(revs) > 1:
2124 2124 ui.note(_('exporting patches:\n'))
2125 2125 else:
2126 2126 ui.note(_('exporting patch:\n'))
2127 2127
2128 2128 fntemplate = opts.get('output')
2129 2129 if cmdutil.isstdiofilename(fntemplate):
2130 2130 fntemplate = ''
2131 2131
2132 2132 if fntemplate:
2133 2133 fm = formatter.nullformatter(ui, 'export', opts)
2134 2134 else:
2135 2135 ui.pager('export')
2136 2136 fm = ui.formatter('export', opts)
2137 2137 with fm:
2138 2138 cmdutil.export(repo, revs, fm, fntemplate=fntemplate,
2139 2139 switch_parent=opts.get('switch_parent'),
2140 2140 opts=patch.diffallopts(ui, opts))
2141 2141
2142 2142 @command('files',
2143 2143 [('r', 'rev', '', _('search the repository as it is in REV'), _('REV')),
2144 2144 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
2145 2145 ] + walkopts + formatteropts + subrepoopts,
2146 2146 _('[OPTION]... [FILE]...'),
2147 2147 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
2148 2148 intents={INTENT_READONLY})
2149 2149 def files(ui, repo, *pats, **opts):
2150 2150 """list tracked files
2151 2151
2152 2152 Print files under Mercurial control in the working directory or
2153 2153 specified revision for given files (excluding removed files).
2154 2154 Files can be specified as filenames or filesets.
2155 2155
2156 2156 If no files are given to match, this command prints the names
2157 2157 of all files under Mercurial control.
2158 2158
2159 2159 .. container:: verbose
2160 2160
2161 2161 Template:
2162 2162
2163 2163 The following keywords are supported in addition to the common template
2164 2164 keywords and functions. See also :hg:`help templates`.
2165 2165
2166 2166 :flags: String. Character denoting file's symlink and executable bits.
2167 2167 :path: String. Repository-absolute path of the file.
2168 2168 :size: Integer. Size of the file in bytes.
2169 2169
2170 2170 Examples:
2171 2171
2172 2172 - list all files under the current directory::
2173 2173
2174 2174 hg files .
2175 2175
2176 2176 - shows sizes and flags for current revision::
2177 2177
2178 2178 hg files -vr .
2179 2179
2180 2180 - list all files named README::
2181 2181
2182 2182 hg files -I "**/README"
2183 2183
2184 2184 - list all binary files::
2185 2185
2186 2186 hg files "set:binary()"
2187 2187
2188 2188 - find files containing a regular expression::
2189 2189
2190 2190 hg files "set:grep('bob')"
2191 2191
2192 2192 - search tracked file contents with xargs and grep::
2193 2193
2194 2194 hg files -0 | xargs -0 grep foo
2195 2195
2196 2196 See :hg:`help patterns` and :hg:`help filesets` for more information
2197 2197 on specifying file patterns.
2198 2198
2199 2199 Returns 0 if a match is found, 1 otherwise.
2200 2200
2201 2201 """
2202 2202
2203 2203 opts = pycompat.byteskwargs(opts)
2204 2204 rev = opts.get('rev')
2205 2205 if rev:
2206 2206 repo = scmutil.unhidehashlikerevs(repo, [rev], 'nowarn')
2207 2207 ctx = scmutil.revsingle(repo, rev, None)
2208 2208
2209 2209 end = '\n'
2210 2210 if opts.get('print0'):
2211 2211 end = '\0'
2212 2212 fmt = '%s' + end
2213 2213
2214 2214 m = scmutil.match(ctx, pats, opts)
2215 2215 ui.pager('files')
2216 2216 with ui.formatter('files', opts) as fm:
2217 2217 return cmdutil.files(ui, ctx, m, fm, fmt, opts.get('subrepos'))
2218 2218
2219 2219 @command(
2220 2220 'forget',
2221 2221 [('i', 'interactive', None, _('use interactive mode')),
2222 2222 ] + walkopts + dryrunopts,
2223 2223 _('[OPTION]... FILE...'),
2224 2224 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
2225 2225 helpbasic=True, inferrepo=True)
2226 2226 def forget(ui, repo, *pats, **opts):
2227 2227 """forget the specified files on the next commit
2228 2228
2229 2229 Mark the specified files so they will no longer be tracked
2230 2230 after the next commit.
2231 2231
2232 2232 This only removes files from the current branch, not from the
2233 2233 entire project history, and it does not delete them from the
2234 2234 working directory.
2235 2235
2236 2236 To delete the file from the working directory, see :hg:`remove`.
2237 2237
2238 2238 To undo a forget before the next commit, see :hg:`add`.
2239 2239
2240 2240 .. container:: verbose
2241 2241
2242 2242 Examples:
2243 2243
2244 2244 - forget newly-added binary files::
2245 2245
2246 2246 hg forget "set:added() and binary()"
2247 2247
2248 2248 - forget files that would be excluded by .hgignore::
2249 2249
2250 2250 hg forget "set:hgignore()"
2251 2251
2252 2252 Returns 0 on success.
2253 2253 """
2254 2254
2255 2255 opts = pycompat.byteskwargs(opts)
2256 2256 if not pats:
2257 2257 raise error.Abort(_('no files specified'))
2258 2258
2259 2259 m = scmutil.match(repo[None], pats, opts)
2260 2260 dryrun, interactive = opts.get('dry_run'), opts.get('interactive')
2261 rejected = cmdutil.forget(ui, repo, m, prefix="",
2261 uipathfn = scmutil.getuipathfn(repo, forcerelativevalue=True)
2262 rejected = cmdutil.forget(ui, repo, m, prefix="", uipathfn=uipathfn,
2262 2263 explicitonly=False, dryrun=dryrun,
2263 2264 interactive=interactive)[0]
2264 2265 return rejected and 1 or 0
2265 2266
2266 2267 @command(
2267 2268 'graft',
2268 2269 [('r', 'rev', [], _('revisions to graft'), _('REV')),
2269 2270 ('', 'base', '',
2270 2271 _('base revision when doing the graft merge (ADVANCED)'), _('REV')),
2271 2272 ('c', 'continue', False, _('resume interrupted graft')),
2272 2273 ('', 'stop', False, _('stop interrupted graft')),
2273 2274 ('', 'abort', False, _('abort interrupted graft')),
2274 2275 ('e', 'edit', False, _('invoke editor on commit messages')),
2275 2276 ('', 'log', None, _('append graft info to log message')),
2276 2277 ('', 'no-commit', None,
2277 2278 _("don't commit, just apply the changes in working directory")),
2278 2279 ('f', 'force', False, _('force graft')),
2279 2280 ('D', 'currentdate', False,
2280 2281 _('record the current date as commit date')),
2281 2282 ('U', 'currentuser', False,
2282 2283 _('record the current user as committer'))]
2283 2284 + commitopts2 + mergetoolopts + dryrunopts,
2284 2285 _('[OPTION]... [-r REV]... REV...'),
2285 2286 helpcategory=command.CATEGORY_CHANGE_MANAGEMENT)
2286 2287 def graft(ui, repo, *revs, **opts):
2287 2288 '''copy changes from other branches onto the current branch
2288 2289
2289 2290 This command uses Mercurial's merge logic to copy individual
2290 2291 changes from other branches without merging branches in the
2291 2292 history graph. This is sometimes known as 'backporting' or
2292 2293 'cherry-picking'. By default, graft will copy user, date, and
2293 2294 description from the source changesets.
2294 2295
2295 2296 Changesets that are ancestors of the current revision, that have
2296 2297 already been grafted, or that are merges will be skipped.
2297 2298
2298 2299 If --log is specified, log messages will have a comment appended
2299 2300 of the form::
2300 2301
2301 2302 (grafted from CHANGESETHASH)
2302 2303
2303 2304 If --force is specified, revisions will be grafted even if they
2304 2305 are already ancestors of, or have been grafted to, the destination.
2305 2306 This is useful when the revisions have since been backed out.
2306 2307
2307 2308 If a graft merge results in conflicts, the graft process is
2308 2309 interrupted so that the current merge can be manually resolved.
2309 2310 Once all conflicts are addressed, the graft process can be
2310 2311 continued with the -c/--continue option.
2311 2312
2312 2313 The -c/--continue option reapplies all the earlier options.
2313 2314
2314 2315 .. container:: verbose
2315 2316
2316 2317 The --base option exposes more of how graft internally uses merge with a
2317 2318 custom base revision. --base can be used to specify another ancestor than
2318 2319 the first and only parent.
2319 2320
2320 2321 The command::
2321 2322
2322 2323 hg graft -r 345 --base 234
2323 2324
2324 2325 is thus pretty much the same as::
2325 2326
2326 2327 hg diff -r 234 -r 345 | hg import
2327 2328
2328 2329 but using merge to resolve conflicts and track moved files.
2329 2330
2330 2331 The result of a merge can thus be backported as a single commit by
2331 2332 specifying one of the merge parents as base, and thus effectively
2332 2333 grafting the changes from the other side.
2333 2334
2334 2335 It is also possible to collapse multiple changesets and clean up history
2335 2336 by specifying another ancestor as base, much like rebase --collapse
2336 2337 --keep.
2337 2338
2338 2339 The commit message can be tweaked after the fact using commit --amend .
2339 2340
2340 2341 For using non-ancestors as the base to backout changes, see the backout
2341 2342 command and the hidden --parent option.
2342 2343
2343 2344 .. container:: verbose
2344 2345
2345 2346 Examples:
2346 2347
2347 2348 - copy a single change to the stable branch and edit its description::
2348 2349
2349 2350 hg update stable
2350 2351 hg graft --edit 9393
2351 2352
2352 2353 - graft a range of changesets with one exception, updating dates::
2353 2354
2354 2355 hg graft -D "2085::2093 and not 2091"
2355 2356
2356 2357 - continue a graft after resolving conflicts::
2357 2358
2358 2359 hg graft -c
2359 2360
2360 2361 - show the source of a grafted changeset::
2361 2362
2362 2363 hg log --debug -r .
2363 2364
2364 2365 - show revisions sorted by date::
2365 2366
2366 2367 hg log -r "sort(all(), date)"
2367 2368
2368 2369 - backport the result of a merge as a single commit::
2369 2370
2370 2371 hg graft -r 123 --base 123^
2371 2372
2372 2373 - land a feature branch as one changeset::
2373 2374
2374 2375 hg up -cr default
2375 2376 hg graft -r featureX --base "ancestor('featureX', 'default')"
2376 2377
2377 2378 See :hg:`help revisions` for more about specifying revisions.
2378 2379
2379 2380 Returns 0 on successful completion.
2380 2381 '''
2381 2382 with repo.wlock():
2382 2383 return _dograft(ui, repo, *revs, **opts)
2383 2384
2384 2385 def _dograft(ui, repo, *revs, **opts):
2385 2386 opts = pycompat.byteskwargs(opts)
2386 2387 if revs and opts.get('rev'):
2387 2388 ui.warn(_('warning: inconsistent use of --rev might give unexpected '
2388 2389 'revision ordering!\n'))
2389 2390
2390 2391 revs = list(revs)
2391 2392 revs.extend(opts.get('rev'))
2392 2393 basectx = None
2393 2394 if opts.get('base'):
2394 2395 basectx = scmutil.revsingle(repo, opts['base'], None)
2395 2396 # a dict of data to be stored in state file
2396 2397 statedata = {}
2397 2398 # list of new nodes created by ongoing graft
2398 2399 statedata['newnodes'] = []
2399 2400
2400 2401 if opts.get('user') and opts.get('currentuser'):
2401 2402 raise error.Abort(_('--user and --currentuser are mutually exclusive'))
2402 2403 if opts.get('date') and opts.get('currentdate'):
2403 2404 raise error.Abort(_('--date and --currentdate are mutually exclusive'))
2404 2405 if not opts.get('user') and opts.get('currentuser'):
2405 2406 opts['user'] = ui.username()
2406 2407 if not opts.get('date') and opts.get('currentdate'):
2407 2408 opts['date'] = "%d %d" % dateutil.makedate()
2408 2409
2409 2410 editor = cmdutil.getcommiteditor(editform='graft',
2410 2411 **pycompat.strkwargs(opts))
2411 2412
2412 2413 cont = False
2413 2414 if opts.get('no_commit'):
2414 2415 if opts.get('edit'):
2415 2416 raise error.Abort(_("cannot specify --no-commit and "
2416 2417 "--edit together"))
2417 2418 if opts.get('currentuser'):
2418 2419 raise error.Abort(_("cannot specify --no-commit and "
2419 2420 "--currentuser together"))
2420 2421 if opts.get('currentdate'):
2421 2422 raise error.Abort(_("cannot specify --no-commit and "
2422 2423 "--currentdate together"))
2423 2424 if opts.get('log'):
2424 2425 raise error.Abort(_("cannot specify --no-commit and "
2425 2426 "--log together"))
2426 2427
2427 2428 graftstate = statemod.cmdstate(repo, 'graftstate')
2428 2429
2429 2430 if opts.get('stop'):
2430 2431 if opts.get('continue'):
2431 2432 raise error.Abort(_("cannot use '--continue' and "
2432 2433 "'--stop' together"))
2433 2434 if opts.get('abort'):
2434 2435 raise error.Abort(_("cannot use '--abort' and '--stop' together"))
2435 2436
2436 2437 if any((opts.get('edit'), opts.get('log'), opts.get('user'),
2437 2438 opts.get('date'), opts.get('currentdate'),
2438 2439 opts.get('currentuser'), opts.get('rev'))):
2439 2440 raise error.Abort(_("cannot specify any other flag with '--stop'"))
2440 2441 return _stopgraft(ui, repo, graftstate)
2441 2442 elif opts.get('abort'):
2442 2443 if opts.get('continue'):
2443 2444 raise error.Abort(_("cannot use '--continue' and "
2444 2445 "'--abort' together"))
2445 2446 if any((opts.get('edit'), opts.get('log'), opts.get('user'),
2446 2447 opts.get('date'), opts.get('currentdate'),
2447 2448 opts.get('currentuser'), opts.get('rev'))):
2448 2449 raise error.Abort(_("cannot specify any other flag with '--abort'"))
2449 2450
2450 2451 return _abortgraft(ui, repo, graftstate)
2451 2452 elif opts.get('continue'):
2452 2453 cont = True
2453 2454 if revs:
2454 2455 raise error.Abort(_("can't specify --continue and revisions"))
2455 2456 # read in unfinished revisions
2456 2457 if graftstate.exists():
2457 2458 statedata = _readgraftstate(repo, graftstate)
2458 2459 if statedata.get('date'):
2459 2460 opts['date'] = statedata['date']
2460 2461 if statedata.get('user'):
2461 2462 opts['user'] = statedata['user']
2462 2463 if statedata.get('log'):
2463 2464 opts['log'] = True
2464 2465 if statedata.get('no_commit'):
2465 2466 opts['no_commit'] = statedata.get('no_commit')
2466 2467 nodes = statedata['nodes']
2467 2468 revs = [repo[node].rev() for node in nodes]
2468 2469 else:
2469 2470 cmdutil.wrongtooltocontinue(repo, _('graft'))
2470 2471 else:
2471 2472 if not revs:
2472 2473 raise error.Abort(_('no revisions specified'))
2473 2474 cmdutil.checkunfinished(repo)
2474 2475 cmdutil.bailifchanged(repo)
2475 2476 revs = scmutil.revrange(repo, revs)
2476 2477
2477 2478 skipped = set()
2478 2479 if basectx is None:
2479 2480 # check for merges
2480 2481 for rev in repo.revs('%ld and merge()', revs):
2481 2482 ui.warn(_('skipping ungraftable merge revision %d\n') % rev)
2482 2483 skipped.add(rev)
2483 2484 revs = [r for r in revs if r not in skipped]
2484 2485 if not revs:
2485 2486 return -1
2486 2487 if basectx is not None and len(revs) != 1:
2487 2488 raise error.Abort(_('only one revision allowed with --base '))
2488 2489
2489 2490 # Don't check in the --continue case, in effect retaining --force across
2490 2491 # --continues. That's because without --force, any revisions we decided to
2491 2492 # skip would have been filtered out here, so they wouldn't have made their
2492 2493 # way to the graftstate. With --force, any revisions we would have otherwise
2493 2494 # skipped would not have been filtered out, and if they hadn't been applied
2494 2495 # already, they'd have been in the graftstate.
2495 2496 if not (cont or opts.get('force')) and basectx is None:
2496 2497 # check for ancestors of dest branch
2497 2498 crev = repo['.'].rev()
2498 2499 ancestors = repo.changelog.ancestors([crev], inclusive=True)
2499 2500 # XXX make this lazy in the future
2500 2501 # don't mutate while iterating, create a copy
2501 2502 for rev in list(revs):
2502 2503 if rev in ancestors:
2503 2504 ui.warn(_('skipping ancestor revision %d:%s\n') %
2504 2505 (rev, repo[rev]))
2505 2506 # XXX remove on list is slow
2506 2507 revs.remove(rev)
2507 2508 if not revs:
2508 2509 return -1
2509 2510
2510 2511 # analyze revs for earlier grafts
2511 2512 ids = {}
2512 2513 for ctx in repo.set("%ld", revs):
2513 2514 ids[ctx.hex()] = ctx.rev()
2514 2515 n = ctx.extra().get('source')
2515 2516 if n:
2516 2517 ids[n] = ctx.rev()
2517 2518
2518 2519 # check ancestors for earlier grafts
2519 2520 ui.debug('scanning for duplicate grafts\n')
2520 2521
2521 2522 # The only changesets we can be sure doesn't contain grafts of any
2522 2523 # revs, are the ones that are common ancestors of *all* revs:
2523 2524 for rev in repo.revs('only(%d,ancestor(%ld))', crev, revs):
2524 2525 ctx = repo[rev]
2525 2526 n = ctx.extra().get('source')
2526 2527 if n in ids:
2527 2528 try:
2528 2529 r = repo[n].rev()
2529 2530 except error.RepoLookupError:
2530 2531 r = None
2531 2532 if r in revs:
2532 2533 ui.warn(_('skipping revision %d:%s '
2533 2534 '(already grafted to %d:%s)\n')
2534 2535 % (r, repo[r], rev, ctx))
2535 2536 revs.remove(r)
2536 2537 elif ids[n] in revs:
2537 2538 if r is None:
2538 2539 ui.warn(_('skipping already grafted revision %d:%s '
2539 2540 '(%d:%s also has unknown origin %s)\n')
2540 2541 % (ids[n], repo[ids[n]], rev, ctx, n[:12]))
2541 2542 else:
2542 2543 ui.warn(_('skipping already grafted revision %d:%s '
2543 2544 '(%d:%s also has origin %d:%s)\n')
2544 2545 % (ids[n], repo[ids[n]], rev, ctx, r, n[:12]))
2545 2546 revs.remove(ids[n])
2546 2547 elif ctx.hex() in ids:
2547 2548 r = ids[ctx.hex()]
2548 2549 if r in revs:
2549 2550 ui.warn(_('skipping already grafted revision %d:%s '
2550 2551 '(was grafted from %d:%s)\n') %
2551 2552 (r, repo[r], rev, ctx))
2552 2553 revs.remove(r)
2553 2554 if not revs:
2554 2555 return -1
2555 2556
2556 2557 if opts.get('no_commit'):
2557 2558 statedata['no_commit'] = True
2558 2559 for pos, ctx in enumerate(repo.set("%ld", revs)):
2559 2560 desc = '%d:%s "%s"' % (ctx.rev(), ctx,
2560 2561 ctx.description().split('\n', 1)[0])
2561 2562 names = repo.nodetags(ctx.node()) + repo.nodebookmarks(ctx.node())
2562 2563 if names:
2563 2564 desc += ' (%s)' % ' '.join(names)
2564 2565 ui.status(_('grafting %s\n') % desc)
2565 2566 if opts.get('dry_run'):
2566 2567 continue
2567 2568
2568 2569 source = ctx.extra().get('source')
2569 2570 extra = {}
2570 2571 if source:
2571 2572 extra['source'] = source
2572 2573 extra['intermediate-source'] = ctx.hex()
2573 2574 else:
2574 2575 extra['source'] = ctx.hex()
2575 2576 user = ctx.user()
2576 2577 if opts.get('user'):
2577 2578 user = opts['user']
2578 2579 statedata['user'] = user
2579 2580 date = ctx.date()
2580 2581 if opts.get('date'):
2581 2582 date = opts['date']
2582 2583 statedata['date'] = date
2583 2584 message = ctx.description()
2584 2585 if opts.get('log'):
2585 2586 message += '\n(grafted from %s)' % ctx.hex()
2586 2587 statedata['log'] = True
2587 2588
2588 2589 # we don't merge the first commit when continuing
2589 2590 if not cont:
2590 2591 # perform the graft merge with p1(rev) as 'ancestor'
2591 2592 overrides = {('ui', 'forcemerge'): opts.get('tool', '')}
2592 2593 base = ctx.p1() if basectx is None else basectx
2593 2594 with ui.configoverride(overrides, 'graft'):
2594 2595 stats = mergemod.graft(repo, ctx, base, ['local', 'graft'])
2595 2596 # report any conflicts
2596 2597 if stats.unresolvedcount > 0:
2597 2598 # write out state for --continue
2598 2599 nodes = [repo[rev].hex() for rev in revs[pos:]]
2599 2600 statedata['nodes'] = nodes
2600 2601 stateversion = 1
2601 2602 graftstate.save(stateversion, statedata)
2602 2603 hint = _("use 'hg resolve' and 'hg graft --continue'")
2603 2604 raise error.Abort(
2604 2605 _("unresolved conflicts, can't continue"),
2605 2606 hint=hint)
2606 2607 else:
2607 2608 cont = False
2608 2609
2609 2610 # commit if --no-commit is false
2610 2611 if not opts.get('no_commit'):
2611 2612 node = repo.commit(text=message, user=user, date=date, extra=extra,
2612 2613 editor=editor)
2613 2614 if node is None:
2614 2615 ui.warn(
2615 2616 _('note: graft of %d:%s created no changes to commit\n') %
2616 2617 (ctx.rev(), ctx))
2617 2618 # checking that newnodes exist because old state files won't have it
2618 2619 elif statedata.get('newnodes') is not None:
2619 2620 statedata['newnodes'].append(node)
2620 2621
2621 2622 # remove state when we complete successfully
2622 2623 if not opts.get('dry_run'):
2623 2624 graftstate.delete()
2624 2625
2625 2626 return 0
2626 2627
2627 2628 def _abortgraft(ui, repo, graftstate):
2628 2629 """abort the interrupted graft and rollbacks to the state before interrupted
2629 2630 graft"""
2630 2631 if not graftstate.exists():
2631 2632 raise error.Abort(_("no interrupted graft to abort"))
2632 2633 statedata = _readgraftstate(repo, graftstate)
2633 2634 newnodes = statedata.get('newnodes')
2634 2635 if newnodes is None:
2635 2636 # and old graft state which does not have all the data required to abort
2636 2637 # the graft
2637 2638 raise error.Abort(_("cannot abort using an old graftstate"))
2638 2639
2639 2640 # changeset from which graft operation was started
2640 2641 if len(newnodes) > 0:
2641 2642 startctx = repo[newnodes[0]].p1()
2642 2643 else:
2643 2644 startctx = repo['.']
2644 2645 # whether to strip or not
2645 2646 cleanup = False
2646 2647 if newnodes:
2647 2648 newnodes = [repo[r].rev() for r in newnodes]
2648 2649 cleanup = True
2649 2650 # checking that none of the newnodes turned public or is public
2650 2651 immutable = [c for c in newnodes if not repo[c].mutable()]
2651 2652 if immutable:
2652 2653 repo.ui.warn(_("cannot clean up public changesets %s\n")
2653 2654 % ', '.join(bytes(repo[r]) for r in immutable),
2654 2655 hint=_("see 'hg help phases' for details"))
2655 2656 cleanup = False
2656 2657
2657 2658 # checking that no new nodes are created on top of grafted revs
2658 2659 desc = set(repo.changelog.descendants(newnodes))
2659 2660 if desc - set(newnodes):
2660 2661 repo.ui.warn(_("new changesets detected on destination "
2661 2662 "branch, can't strip\n"))
2662 2663 cleanup = False
2663 2664
2664 2665 if cleanup:
2665 2666 with repo.wlock(), repo.lock():
2666 2667 hg.updaterepo(repo, startctx.node(), overwrite=True)
2667 2668 # stripping the new nodes created
2668 2669 strippoints = [c.node() for c in repo.set("roots(%ld)",
2669 2670 newnodes)]
2670 2671 repair.strip(repo.ui, repo, strippoints, backup=False)
2671 2672
2672 2673 if not cleanup:
2673 2674 # we don't update to the startnode if we can't strip
2674 2675 startctx = repo['.']
2675 2676 hg.updaterepo(repo, startctx.node(), overwrite=True)
2676 2677
2677 2678 ui.status(_("graft aborted\n"))
2678 2679 ui.status(_("working directory is now at %s\n") % startctx.hex()[:12])
2679 2680 graftstate.delete()
2680 2681 return 0
2681 2682
2682 2683 def _readgraftstate(repo, graftstate):
2683 2684 """read the graft state file and return a dict of the data stored in it"""
2684 2685 try:
2685 2686 return graftstate.read()
2686 2687 except error.CorruptedState:
2687 2688 nodes = repo.vfs.read('graftstate').splitlines()
2688 2689 return {'nodes': nodes}
2689 2690
2690 2691 def _stopgraft(ui, repo, graftstate):
2691 2692 """stop the interrupted graft"""
2692 2693 if not graftstate.exists():
2693 2694 raise error.Abort(_("no interrupted graft found"))
2694 2695 pctx = repo['.']
2695 2696 hg.updaterepo(repo, pctx.node(), overwrite=True)
2696 2697 graftstate.delete()
2697 2698 ui.status(_("stopped the interrupted graft\n"))
2698 2699 ui.status(_("working directory is now at %s\n") % pctx.hex()[:12])
2699 2700 return 0
2700 2701
2701 2702 @command('grep',
2702 2703 [('0', 'print0', None, _('end fields with NUL')),
2703 2704 ('', 'all', None, _('print all revisions that match (DEPRECATED) ')),
2704 2705 ('', 'diff', None, _('print all revisions when the term was introduced '
2705 2706 'or removed')),
2706 2707 ('a', 'text', None, _('treat all files as text')),
2707 2708 ('f', 'follow', None,
2708 2709 _('follow changeset history,'
2709 2710 ' or file history across copies and renames')),
2710 2711 ('i', 'ignore-case', None, _('ignore case when matching')),
2711 2712 ('l', 'files-with-matches', None,
2712 2713 _('print only filenames and revisions that match')),
2713 2714 ('n', 'line-number', None, _('print matching line numbers')),
2714 2715 ('r', 'rev', [],
2715 2716 _('only search files changed within revision range'), _('REV')),
2716 2717 ('', 'all-files', None,
2717 2718 _('include all files in the changeset while grepping (EXPERIMENTAL)')),
2718 2719 ('u', 'user', None, _('list the author (long with -v)')),
2719 2720 ('d', 'date', None, _('list the date (short with -q)')),
2720 2721 ] + formatteropts + walkopts,
2721 2722 _('[OPTION]... PATTERN [FILE]...'),
2722 2723 helpcategory=command.CATEGORY_FILE_CONTENTS,
2723 2724 inferrepo=True,
2724 2725 intents={INTENT_READONLY})
2725 2726 def grep(ui, repo, pattern, *pats, **opts):
2726 2727 """search revision history for a pattern in specified files
2727 2728
2728 2729 Search revision history for a regular expression in the specified
2729 2730 files or the entire project.
2730 2731
2731 2732 By default, grep prints the most recent revision number for each
2732 2733 file in which it finds a match. To get it to print every revision
2733 2734 that contains a change in match status ("-" for a match that becomes
2734 2735 a non-match, or "+" for a non-match that becomes a match), use the
2735 2736 --diff flag.
2736 2737
2737 2738 PATTERN can be any Python (roughly Perl-compatible) regular
2738 2739 expression.
2739 2740
2740 2741 If no FILEs are specified (and -f/--follow isn't set), all files in
2741 2742 the repository are searched, including those that don't exist in the
2742 2743 current branch or have been deleted in a prior changeset.
2743 2744
2744 2745 .. container:: verbose
2745 2746
2746 2747 Template:
2747 2748
2748 2749 The following keywords are supported in addition to the common template
2749 2750 keywords and functions. See also :hg:`help templates`.
2750 2751
2751 2752 :change: String. Character denoting insertion ``+`` or removal ``-``.
2752 2753 Available if ``--diff`` is specified.
2753 2754 :lineno: Integer. Line number of the match.
2754 2755 :path: String. Repository-absolute path of the file.
2755 2756 :texts: List of text chunks.
2756 2757
2757 2758 And each entry of ``{texts}`` provides the following sub-keywords.
2758 2759
2759 2760 :matched: Boolean. True if the chunk matches the specified pattern.
2760 2761 :text: String. Chunk content.
2761 2762
2762 2763 See :hg:`help templates.operators` for the list expansion syntax.
2763 2764
2764 2765 Returns 0 if a match is found, 1 otherwise.
2765 2766 """
2766 2767 opts = pycompat.byteskwargs(opts)
2767 2768 diff = opts.get('all') or opts.get('diff')
2768 2769 all_files = opts.get('all_files')
2769 2770 if diff and opts.get('all_files'):
2770 2771 raise error.Abort(_('--diff and --all-files are mutually exclusive'))
2771 2772 # TODO: remove "not opts.get('rev')" if --all-files -rMULTIREV gets working
2772 2773 if opts.get('all_files') is None and not opts.get('rev') and not diff:
2773 2774 # experimental config: commands.grep.all-files
2774 2775 opts['all_files'] = ui.configbool('commands', 'grep.all-files')
2775 2776 plaingrep = opts.get('all_files') and not opts.get('rev')
2776 2777 if plaingrep:
2777 2778 opts['rev'] = ['wdir()']
2778 2779
2779 2780 reflags = re.M
2780 2781 if opts.get('ignore_case'):
2781 2782 reflags |= re.I
2782 2783 try:
2783 2784 regexp = util.re.compile(pattern, reflags)
2784 2785 except re.error as inst:
2785 2786 ui.warn(_("grep: invalid match pattern: %s\n") % pycompat.bytestr(inst))
2786 2787 return 1
2787 2788 sep, eol = ':', '\n'
2788 2789 if opts.get('print0'):
2789 2790 sep = eol = '\0'
2790 2791
2791 2792 getfile = util.lrucachefunc(repo.file)
2792 2793
2793 2794 def matchlines(body):
2794 2795 begin = 0
2795 2796 linenum = 0
2796 2797 while begin < len(body):
2797 2798 match = regexp.search(body, begin)
2798 2799 if not match:
2799 2800 break
2800 2801 mstart, mend = match.span()
2801 2802 linenum += body.count('\n', begin, mstart) + 1
2802 2803 lstart = body.rfind('\n', begin, mstart) + 1 or begin
2803 2804 begin = body.find('\n', mend) + 1 or len(body) + 1
2804 2805 lend = begin - 1
2805 2806 yield linenum, mstart - lstart, mend - lstart, body[lstart:lend]
2806 2807
2807 2808 class linestate(object):
2808 2809 def __init__(self, line, linenum, colstart, colend):
2809 2810 self.line = line
2810 2811 self.linenum = linenum
2811 2812 self.colstart = colstart
2812 2813 self.colend = colend
2813 2814
2814 2815 def __hash__(self):
2815 2816 return hash((self.linenum, self.line))
2816 2817
2817 2818 def __eq__(self, other):
2818 2819 return self.line == other.line
2819 2820
2820 2821 def findpos(self):
2821 2822 """Iterate all (start, end) indices of matches"""
2822 2823 yield self.colstart, self.colend
2823 2824 p = self.colend
2824 2825 while p < len(self.line):
2825 2826 m = regexp.search(self.line, p)
2826 2827 if not m:
2827 2828 break
2828 2829 yield m.span()
2829 2830 p = m.end()
2830 2831
2831 2832 matches = {}
2832 2833 copies = {}
2833 2834 def grepbody(fn, rev, body):
2834 2835 matches[rev].setdefault(fn, [])
2835 2836 m = matches[rev][fn]
2836 2837 for lnum, cstart, cend, line in matchlines(body):
2837 2838 s = linestate(line, lnum, cstart, cend)
2838 2839 m.append(s)
2839 2840
2840 2841 def difflinestates(a, b):
2841 2842 sm = difflib.SequenceMatcher(None, a, b)
2842 2843 for tag, alo, ahi, blo, bhi in sm.get_opcodes():
2843 2844 if tag == r'insert':
2844 2845 for i in pycompat.xrange(blo, bhi):
2845 2846 yield ('+', b[i])
2846 2847 elif tag == r'delete':
2847 2848 for i in pycompat.xrange(alo, ahi):
2848 2849 yield ('-', a[i])
2849 2850 elif tag == r'replace':
2850 2851 for i in pycompat.xrange(alo, ahi):
2851 2852 yield ('-', a[i])
2852 2853 for i in pycompat.xrange(blo, bhi):
2853 2854 yield ('+', b[i])
2854 2855
2855 2856 uipathfn = scmutil.getuipathfn(repo)
2856 2857 def display(fm, fn, ctx, pstates, states):
2857 2858 rev = scmutil.intrev(ctx)
2858 2859 if fm.isplain():
2859 2860 formatuser = ui.shortuser
2860 2861 else:
2861 2862 formatuser = pycompat.bytestr
2862 2863 if ui.quiet:
2863 2864 datefmt = '%Y-%m-%d'
2864 2865 else:
2865 2866 datefmt = '%a %b %d %H:%M:%S %Y %1%2'
2866 2867 found = False
2867 2868 @util.cachefunc
2868 2869 def binary():
2869 2870 flog = getfile(fn)
2870 2871 try:
2871 2872 return stringutil.binary(flog.read(ctx.filenode(fn)))
2872 2873 except error.WdirUnsupported:
2873 2874 return ctx[fn].isbinary()
2874 2875
2875 2876 fieldnamemap = {'linenumber': 'lineno'}
2876 2877 if diff:
2877 2878 iter = difflinestates(pstates, states)
2878 2879 else:
2879 2880 iter = [('', l) for l in states]
2880 2881 for change, l in iter:
2881 2882 fm.startitem()
2882 2883 fm.context(ctx=ctx)
2883 2884 fm.data(node=fm.hexfunc(scmutil.binnode(ctx)), path=fn)
2884 2885 fm.plain(uipathfn(fn), label='grep.filename')
2885 2886
2886 2887 cols = [
2887 2888 ('rev', '%d', rev, not plaingrep),
2888 2889 ('linenumber', '%d', l.linenum, opts.get('line_number')),
2889 2890 ]
2890 2891 if diff:
2891 2892 cols.append(('change', '%s', change, True))
2892 2893 cols.extend([
2893 2894 ('user', '%s', formatuser(ctx.user()), opts.get('user')),
2894 2895 ('date', '%s', fm.formatdate(ctx.date(), datefmt),
2895 2896 opts.get('date')),
2896 2897 ])
2897 2898 for name, fmt, data, cond in cols:
2898 2899 if cond:
2899 2900 fm.plain(sep, label='grep.sep')
2900 2901 field = fieldnamemap.get(name, name)
2901 2902 fm.condwrite(cond, field, fmt, data, label='grep.%s' % name)
2902 2903 if not opts.get('files_with_matches'):
2903 2904 fm.plain(sep, label='grep.sep')
2904 2905 if not opts.get('text') and binary():
2905 2906 fm.plain(_(" Binary file matches"))
2906 2907 else:
2907 2908 displaymatches(fm.nested('texts', tmpl='{text}'), l)
2908 2909 fm.plain(eol)
2909 2910 found = True
2910 2911 if opts.get('files_with_matches'):
2911 2912 break
2912 2913 return found
2913 2914
2914 2915 def displaymatches(fm, l):
2915 2916 p = 0
2916 2917 for s, e in l.findpos():
2917 2918 if p < s:
2918 2919 fm.startitem()
2919 2920 fm.write('text', '%s', l.line[p:s])
2920 2921 fm.data(matched=False)
2921 2922 fm.startitem()
2922 2923 fm.write('text', '%s', l.line[s:e], label='grep.match')
2923 2924 fm.data(matched=True)
2924 2925 p = e
2925 2926 if p < len(l.line):
2926 2927 fm.startitem()
2927 2928 fm.write('text', '%s', l.line[p:])
2928 2929 fm.data(matched=False)
2929 2930 fm.end()
2930 2931
2931 2932 skip = set()
2932 2933 revfiles = {}
2933 2934 match = scmutil.match(repo[None], pats, opts)
2934 2935 found = False
2935 2936 follow = opts.get('follow')
2936 2937
2937 2938 def prep(ctx, fns):
2938 2939 rev = ctx.rev()
2939 2940 pctx = ctx.p1()
2940 2941 parent = pctx.rev()
2941 2942 matches.setdefault(rev, {})
2942 2943 matches.setdefault(parent, {})
2943 2944 files = revfiles.setdefault(rev, [])
2944 2945 for fn in fns:
2945 2946 flog = getfile(fn)
2946 2947 try:
2947 2948 fnode = ctx.filenode(fn)
2948 2949 except error.LookupError:
2949 2950 continue
2950 2951 copy = None
2951 2952 if follow:
2952 2953 try:
2953 2954 copied = flog.renamed(fnode)
2954 2955 except error.WdirUnsupported:
2955 2956 copied = ctx[fn].renamed()
2956 2957 copy = copied and copied[0]
2957 2958 if copy:
2958 2959 copies.setdefault(rev, {})[fn] = copy
2959 2960 if fn in skip:
2960 2961 skip.add(copy)
2961 2962 if fn in skip:
2962 2963 continue
2963 2964 files.append(fn)
2964 2965
2965 2966 if fn not in matches[rev]:
2966 2967 try:
2967 2968 content = flog.read(fnode)
2968 2969 except error.WdirUnsupported:
2969 2970 content = ctx[fn].data()
2970 2971 grepbody(fn, rev, content)
2971 2972
2972 2973 pfn = copy or fn
2973 2974 if pfn not in matches[parent]:
2974 2975 try:
2975 2976 fnode = pctx.filenode(pfn)
2976 2977 grepbody(pfn, parent, flog.read(fnode))
2977 2978 except error.LookupError:
2978 2979 pass
2979 2980
2980 2981 ui.pager('grep')
2981 2982 fm = ui.formatter('grep', opts)
2982 2983 for ctx in cmdutil.walkchangerevs(repo, match, opts, prep):
2983 2984 rev = ctx.rev()
2984 2985 parent = ctx.p1().rev()
2985 2986 for fn in sorted(revfiles.get(rev, [])):
2986 2987 states = matches[rev][fn]
2987 2988 copy = copies.get(rev, {}).get(fn)
2988 2989 if fn in skip:
2989 2990 if copy:
2990 2991 skip.add(copy)
2991 2992 continue
2992 2993 pstates = matches.get(parent, {}).get(copy or fn, [])
2993 2994 if pstates or states:
2994 2995 r = display(fm, fn, ctx, pstates, states)
2995 2996 found = found or r
2996 2997 if r and not diff and not all_files:
2997 2998 skip.add(fn)
2998 2999 if copy:
2999 3000 skip.add(copy)
3000 3001 del revfiles[rev]
3001 3002 # We will keep the matches dict for the duration of the window
3002 3003 # clear the matches dict once the window is over
3003 3004 if not revfiles:
3004 3005 matches.clear()
3005 3006 fm.end()
3006 3007
3007 3008 return not found
3008 3009
3009 3010 @command('heads',
3010 3011 [('r', 'rev', '',
3011 3012 _('show only heads which are descendants of STARTREV'), _('STARTREV')),
3012 3013 ('t', 'topo', False, _('show topological heads only')),
3013 3014 ('a', 'active', False, _('show active branchheads only (DEPRECATED)')),
3014 3015 ('c', 'closed', False, _('show normal and closed branch heads')),
3015 3016 ] + templateopts,
3016 3017 _('[-ct] [-r STARTREV] [REV]...'),
3017 3018 helpcategory=command.CATEGORY_CHANGE_NAVIGATION,
3018 3019 intents={INTENT_READONLY})
3019 3020 def heads(ui, repo, *branchrevs, **opts):
3020 3021 """show branch heads
3021 3022
3022 3023 With no arguments, show all open branch heads in the repository.
3023 3024 Branch heads are changesets that have no descendants on the
3024 3025 same branch. They are where development generally takes place and
3025 3026 are the usual targets for update and merge operations.
3026 3027
3027 3028 If one or more REVs are given, only open branch heads on the
3028 3029 branches associated with the specified changesets are shown. This
3029 3030 means that you can use :hg:`heads .` to see the heads on the
3030 3031 currently checked-out branch.
3031 3032
3032 3033 If -c/--closed is specified, also show branch heads marked closed
3033 3034 (see :hg:`commit --close-branch`).
3034 3035
3035 3036 If STARTREV is specified, only those heads that are descendants of
3036 3037 STARTREV will be displayed.
3037 3038
3038 3039 If -t/--topo is specified, named branch mechanics will be ignored and only
3039 3040 topological heads (changesets with no children) will be shown.
3040 3041
3041 3042 Returns 0 if matching heads are found, 1 if not.
3042 3043 """
3043 3044
3044 3045 opts = pycompat.byteskwargs(opts)
3045 3046 start = None
3046 3047 rev = opts.get('rev')
3047 3048 if rev:
3048 3049 repo = scmutil.unhidehashlikerevs(repo, [rev], 'nowarn')
3049 3050 start = scmutil.revsingle(repo, rev, None).node()
3050 3051
3051 3052 if opts.get('topo'):
3052 3053 heads = [repo[h] for h in repo.heads(start)]
3053 3054 else:
3054 3055 heads = []
3055 3056 for branch in repo.branchmap():
3056 3057 heads += repo.branchheads(branch, start, opts.get('closed'))
3057 3058 heads = [repo[h] for h in heads]
3058 3059
3059 3060 if branchrevs:
3060 3061 branches = set(repo[r].branch()
3061 3062 for r in scmutil.revrange(repo, branchrevs))
3062 3063 heads = [h for h in heads if h.branch() in branches]
3063 3064
3064 3065 if opts.get('active') and branchrevs:
3065 3066 dagheads = repo.heads(start)
3066 3067 heads = [h for h in heads if h.node() in dagheads]
3067 3068
3068 3069 if branchrevs:
3069 3070 haveheads = set(h.branch() for h in heads)
3070 3071 if branches - haveheads:
3071 3072 headless = ', '.join(b for b in branches - haveheads)
3072 3073 msg = _('no open branch heads found on branches %s')
3073 3074 if opts.get('rev'):
3074 3075 msg += _(' (started at %s)') % opts['rev']
3075 3076 ui.warn((msg + '\n') % headless)
3076 3077
3077 3078 if not heads:
3078 3079 return 1
3079 3080
3080 3081 ui.pager('heads')
3081 3082 heads = sorted(heads, key=lambda x: -x.rev())
3082 3083 displayer = logcmdutil.changesetdisplayer(ui, repo, opts)
3083 3084 for ctx in heads:
3084 3085 displayer.show(ctx)
3085 3086 displayer.close()
3086 3087
3087 3088 @command('help',
3088 3089 [('e', 'extension', None, _('show only help for extensions')),
3089 3090 ('c', 'command', None, _('show only help for commands')),
3090 3091 ('k', 'keyword', None, _('show topics matching keyword')),
3091 3092 ('s', 'system', [],
3092 3093 _('show help for specific platform(s)'), _('PLATFORM')),
3093 3094 ],
3094 3095 _('[-eck] [-s PLATFORM] [TOPIC]'),
3095 3096 helpcategory=command.CATEGORY_HELP,
3096 3097 norepo=True,
3097 3098 intents={INTENT_READONLY})
3098 3099 def help_(ui, name=None, **opts):
3099 3100 """show help for a given topic or a help overview
3100 3101
3101 3102 With no arguments, print a list of commands with short help messages.
3102 3103
3103 3104 Given a topic, extension, or command name, print help for that
3104 3105 topic.
3105 3106
3106 3107 Returns 0 if successful.
3107 3108 """
3108 3109
3109 3110 keep = opts.get(r'system') or []
3110 3111 if len(keep) == 0:
3111 3112 if pycompat.sysplatform.startswith('win'):
3112 3113 keep.append('windows')
3113 3114 elif pycompat.sysplatform == 'OpenVMS':
3114 3115 keep.append('vms')
3115 3116 elif pycompat.sysplatform == 'plan9':
3116 3117 keep.append('plan9')
3117 3118 else:
3118 3119 keep.append('unix')
3119 3120 keep.append(pycompat.sysplatform.lower())
3120 3121 if ui.verbose:
3121 3122 keep.append('verbose')
3122 3123
3123 3124 commands = sys.modules[__name__]
3124 3125 formatted = help.formattedhelp(ui, commands, name, keep=keep, **opts)
3125 3126 ui.pager('help')
3126 3127 ui.write(formatted)
3127 3128
3128 3129
3129 3130 @command('identify|id',
3130 3131 [('r', 'rev', '',
3131 3132 _('identify the specified revision'), _('REV')),
3132 3133 ('n', 'num', None, _('show local revision number')),
3133 3134 ('i', 'id', None, _('show global revision id')),
3134 3135 ('b', 'branch', None, _('show branch')),
3135 3136 ('t', 'tags', None, _('show tags')),
3136 3137 ('B', 'bookmarks', None, _('show bookmarks')),
3137 3138 ] + remoteopts + formatteropts,
3138 3139 _('[-nibtB] [-r REV] [SOURCE]'),
3139 3140 helpcategory=command.CATEGORY_CHANGE_NAVIGATION,
3140 3141 optionalrepo=True,
3141 3142 intents={INTENT_READONLY})
3142 3143 def identify(ui, repo, source=None, rev=None,
3143 3144 num=None, id=None, branch=None, tags=None, bookmarks=None, **opts):
3144 3145 """identify the working directory or specified revision
3145 3146
3146 3147 Print a summary identifying the repository state at REV using one or
3147 3148 two parent hash identifiers, followed by a "+" if the working
3148 3149 directory has uncommitted changes, the branch name (if not default),
3149 3150 a list of tags, and a list of bookmarks.
3150 3151
3151 3152 When REV is not given, print a summary of the current state of the
3152 3153 repository including the working directory. Specify -r. to get information
3153 3154 of the working directory parent without scanning uncommitted changes.
3154 3155
3155 3156 Specifying a path to a repository root or Mercurial bundle will
3156 3157 cause lookup to operate on that repository/bundle.
3157 3158
3158 3159 .. container:: verbose
3159 3160
3160 3161 Template:
3161 3162
3162 3163 The following keywords are supported in addition to the common template
3163 3164 keywords and functions. See also :hg:`help templates`.
3164 3165
3165 3166 :dirty: String. Character ``+`` denoting if the working directory has
3166 3167 uncommitted changes.
3167 3168 :id: String. One or two nodes, optionally followed by ``+``.
3168 3169 :parents: List of strings. Parent nodes of the changeset.
3169 3170
3170 3171 Examples:
3171 3172
3172 3173 - generate a build identifier for the working directory::
3173 3174
3174 3175 hg id --id > build-id.dat
3175 3176
3176 3177 - find the revision corresponding to a tag::
3177 3178
3178 3179 hg id -n -r 1.3
3179 3180
3180 3181 - check the most recent revision of a remote repository::
3181 3182
3182 3183 hg id -r tip https://www.mercurial-scm.org/repo/hg/
3183 3184
3184 3185 See :hg:`log` for generating more information about specific revisions,
3185 3186 including full hash identifiers.
3186 3187
3187 3188 Returns 0 if successful.
3188 3189 """
3189 3190
3190 3191 opts = pycompat.byteskwargs(opts)
3191 3192 if not repo and not source:
3192 3193 raise error.Abort(_("there is no Mercurial repository here "
3193 3194 "(.hg not found)"))
3194 3195
3195 3196 default = not (num or id or branch or tags or bookmarks)
3196 3197 output = []
3197 3198 revs = []
3198 3199
3199 3200 if source:
3200 3201 source, branches = hg.parseurl(ui.expandpath(source))
3201 3202 peer = hg.peer(repo or ui, opts, source) # only pass ui when no repo
3202 3203 repo = peer.local()
3203 3204 revs, checkout = hg.addbranchrevs(repo, peer, branches, None)
3204 3205
3205 3206 fm = ui.formatter('identify', opts)
3206 3207 fm.startitem()
3207 3208
3208 3209 if not repo:
3209 3210 if num or branch or tags:
3210 3211 raise error.Abort(
3211 3212 _("can't query remote revision number, branch, or tags"))
3212 3213 if not rev and revs:
3213 3214 rev = revs[0]
3214 3215 if not rev:
3215 3216 rev = "tip"
3216 3217
3217 3218 remoterev = peer.lookup(rev)
3218 3219 hexrev = fm.hexfunc(remoterev)
3219 3220 if default or id:
3220 3221 output = [hexrev]
3221 3222 fm.data(id=hexrev)
3222 3223
3223 3224 @util.cachefunc
3224 3225 def getbms():
3225 3226 bms = []
3226 3227
3227 3228 if 'bookmarks' in peer.listkeys('namespaces'):
3228 3229 hexremoterev = hex(remoterev)
3229 3230 bms = [bm for bm, bmr in peer.listkeys('bookmarks').iteritems()
3230 3231 if bmr == hexremoterev]
3231 3232
3232 3233 return sorted(bms)
3233 3234
3234 3235 if fm.isplain():
3235 3236 if bookmarks:
3236 3237 output.extend(getbms())
3237 3238 elif default and not ui.quiet:
3238 3239 # multiple bookmarks for a single parent separated by '/'
3239 3240 bm = '/'.join(getbms())
3240 3241 if bm:
3241 3242 output.append(bm)
3242 3243 else:
3243 3244 fm.data(node=hex(remoterev))
3244 3245 if bookmarks or 'bookmarks' in fm.datahint():
3245 3246 fm.data(bookmarks=fm.formatlist(getbms(), name='bookmark'))
3246 3247 else:
3247 3248 if rev:
3248 3249 repo = scmutil.unhidehashlikerevs(repo, [rev], 'nowarn')
3249 3250 ctx = scmutil.revsingle(repo, rev, None)
3250 3251
3251 3252 if ctx.rev() is None:
3252 3253 ctx = repo[None]
3253 3254 parents = ctx.parents()
3254 3255 taglist = []
3255 3256 for p in parents:
3256 3257 taglist.extend(p.tags())
3257 3258
3258 3259 dirty = ""
3259 3260 if ctx.dirty(missing=True, merge=False, branch=False):
3260 3261 dirty = '+'
3261 3262 fm.data(dirty=dirty)
3262 3263
3263 3264 hexoutput = [fm.hexfunc(p.node()) for p in parents]
3264 3265 if default or id:
3265 3266 output = ["%s%s" % ('+'.join(hexoutput), dirty)]
3266 3267 fm.data(id="%s%s" % ('+'.join(hexoutput), dirty))
3267 3268
3268 3269 if num:
3269 3270 numoutput = ["%d" % p.rev() for p in parents]
3270 3271 output.append("%s%s" % ('+'.join(numoutput), dirty))
3271 3272
3272 3273 fm.data(parents=fm.formatlist([fm.hexfunc(p.node())
3273 3274 for p in parents], name='node'))
3274 3275 else:
3275 3276 hexoutput = fm.hexfunc(ctx.node())
3276 3277 if default or id:
3277 3278 output = [hexoutput]
3278 3279 fm.data(id=hexoutput)
3279 3280
3280 3281 if num:
3281 3282 output.append(pycompat.bytestr(ctx.rev()))
3282 3283 taglist = ctx.tags()
3283 3284
3284 3285 if default and not ui.quiet:
3285 3286 b = ctx.branch()
3286 3287 if b != 'default':
3287 3288 output.append("(%s)" % b)
3288 3289
3289 3290 # multiple tags for a single parent separated by '/'
3290 3291 t = '/'.join(taglist)
3291 3292 if t:
3292 3293 output.append(t)
3293 3294
3294 3295 # multiple bookmarks for a single parent separated by '/'
3295 3296 bm = '/'.join(ctx.bookmarks())
3296 3297 if bm:
3297 3298 output.append(bm)
3298 3299 else:
3299 3300 if branch:
3300 3301 output.append(ctx.branch())
3301 3302
3302 3303 if tags:
3303 3304 output.extend(taglist)
3304 3305
3305 3306 if bookmarks:
3306 3307 output.extend(ctx.bookmarks())
3307 3308
3308 3309 fm.data(node=ctx.hex())
3309 3310 fm.data(branch=ctx.branch())
3310 3311 fm.data(tags=fm.formatlist(taglist, name='tag', sep=':'))
3311 3312 fm.data(bookmarks=fm.formatlist(ctx.bookmarks(), name='bookmark'))
3312 3313 fm.context(ctx=ctx)
3313 3314
3314 3315 fm.plain("%s\n" % ' '.join(output))
3315 3316 fm.end()
3316 3317
3317 3318 @command('import|patch',
3318 3319 [('p', 'strip', 1,
3319 3320 _('directory strip option for patch. This has the same '
3320 3321 'meaning as the corresponding patch option'), _('NUM')),
3321 3322 ('b', 'base', '', _('base path (DEPRECATED)'), _('PATH')),
3322 3323 ('e', 'edit', False, _('invoke editor on commit messages')),
3323 3324 ('f', 'force', None,
3324 3325 _('skip check for outstanding uncommitted changes (DEPRECATED)')),
3325 3326 ('', 'no-commit', None,
3326 3327 _("don't commit, just update the working directory")),
3327 3328 ('', 'bypass', None,
3328 3329 _("apply patch without touching the working directory")),
3329 3330 ('', 'partial', None,
3330 3331 _('commit even if some hunks fail')),
3331 3332 ('', 'exact', None,
3332 3333 _('abort if patch would apply lossily')),
3333 3334 ('', 'prefix', '',
3334 3335 _('apply patch to subdirectory'), _('DIR')),
3335 3336 ('', 'import-branch', None,
3336 3337 _('use any branch information in patch (implied by --exact)'))] +
3337 3338 commitopts + commitopts2 + similarityopts,
3338 3339 _('[OPTION]... PATCH...'),
3339 3340 helpcategory=command.CATEGORY_IMPORT_EXPORT)
3340 3341 def import_(ui, repo, patch1=None, *patches, **opts):
3341 3342 """import an ordered set of patches
3342 3343
3343 3344 Import a list of patches and commit them individually (unless
3344 3345 --no-commit is specified).
3345 3346
3346 3347 To read a patch from standard input (stdin), use "-" as the patch
3347 3348 name. If a URL is specified, the patch will be downloaded from
3348 3349 there.
3349 3350
3350 3351 Import first applies changes to the working directory (unless
3351 3352 --bypass is specified), import will abort if there are outstanding
3352 3353 changes.
3353 3354
3354 3355 Use --bypass to apply and commit patches directly to the
3355 3356 repository, without affecting the working directory. Without
3356 3357 --exact, patches will be applied on top of the working directory
3357 3358 parent revision.
3358 3359
3359 3360 You can import a patch straight from a mail message. Even patches
3360 3361 as attachments work (to use the body part, it must have type
3361 3362 text/plain or text/x-patch). From and Subject headers of email
3362 3363 message are used as default committer and commit message. All
3363 3364 text/plain body parts before first diff are added to the commit
3364 3365 message.
3365 3366
3366 3367 If the imported patch was generated by :hg:`export`, user and
3367 3368 description from patch override values from message headers and
3368 3369 body. Values given on command line with -m/--message and -u/--user
3369 3370 override these.
3370 3371
3371 3372 If --exact is specified, import will set the working directory to
3372 3373 the parent of each patch before applying it, and will abort if the
3373 3374 resulting changeset has a different ID than the one recorded in
3374 3375 the patch. This will guard against various ways that portable
3375 3376 patch formats and mail systems might fail to transfer Mercurial
3376 3377 data or metadata. See :hg:`bundle` for lossless transmission.
3377 3378
3378 3379 Use --partial to ensure a changeset will be created from the patch
3379 3380 even if some hunks fail to apply. Hunks that fail to apply will be
3380 3381 written to a <target-file>.rej file. Conflicts can then be resolved
3381 3382 by hand before :hg:`commit --amend` is run to update the created
3382 3383 changeset. This flag exists to let people import patches that
3383 3384 partially apply without losing the associated metadata (author,
3384 3385 date, description, ...).
3385 3386
3386 3387 .. note::
3387 3388
3388 3389 When no hunks apply cleanly, :hg:`import --partial` will create
3389 3390 an empty changeset, importing only the patch metadata.
3390 3391
3391 3392 With -s/--similarity, hg will attempt to discover renames and
3392 3393 copies in the patch in the same way as :hg:`addremove`.
3393 3394
3394 3395 It is possible to use external patch programs to perform the patch
3395 3396 by setting the ``ui.patch`` configuration option. For the default
3396 3397 internal tool, the fuzz can also be configured via ``patch.fuzz``.
3397 3398 See :hg:`help config` for more information about configuration
3398 3399 files and how to use these options.
3399 3400
3400 3401 See :hg:`help dates` for a list of formats valid for -d/--date.
3401 3402
3402 3403 .. container:: verbose
3403 3404
3404 3405 Examples:
3405 3406
3406 3407 - import a traditional patch from a website and detect renames::
3407 3408
3408 3409 hg import -s 80 http://example.com/bugfix.patch
3409 3410
3410 3411 - import a changeset from an hgweb server::
3411 3412
3412 3413 hg import https://www.mercurial-scm.org/repo/hg/rev/5ca8c111e9aa
3413 3414
3414 3415 - import all the patches in an Unix-style mbox::
3415 3416
3416 3417 hg import incoming-patches.mbox
3417 3418
3418 3419 - import patches from stdin::
3419 3420
3420 3421 hg import -
3421 3422
3422 3423 - attempt to exactly restore an exported changeset (not always
3423 3424 possible)::
3424 3425
3425 3426 hg import --exact proposed-fix.patch
3426 3427
3427 3428 - use an external tool to apply a patch which is too fuzzy for
3428 3429 the default internal tool.
3429 3430
3430 3431 hg import --config ui.patch="patch --merge" fuzzy.patch
3431 3432
3432 3433 - change the default fuzzing from 2 to a less strict 7
3433 3434
3434 3435 hg import --config ui.fuzz=7 fuzz.patch
3435 3436
3436 3437 Returns 0 on success, 1 on partial success (see --partial).
3437 3438 """
3438 3439
3439 3440 opts = pycompat.byteskwargs(opts)
3440 3441 if not patch1:
3441 3442 raise error.Abort(_('need at least one patch to import'))
3442 3443
3443 3444 patches = (patch1,) + patches
3444 3445
3445 3446 date = opts.get('date')
3446 3447 if date:
3447 3448 opts['date'] = dateutil.parsedate(date)
3448 3449
3449 3450 exact = opts.get('exact')
3450 3451 update = not opts.get('bypass')
3451 3452 if not update and opts.get('no_commit'):
3452 3453 raise error.Abort(_('cannot use --no-commit with --bypass'))
3453 3454 try:
3454 3455 sim = float(opts.get('similarity') or 0)
3455 3456 except ValueError:
3456 3457 raise error.Abort(_('similarity must be a number'))
3457 3458 if sim < 0 or sim > 100:
3458 3459 raise error.Abort(_('similarity must be between 0 and 100'))
3459 3460 if sim and not update:
3460 3461 raise error.Abort(_('cannot use --similarity with --bypass'))
3461 3462 if exact:
3462 3463 if opts.get('edit'):
3463 3464 raise error.Abort(_('cannot use --exact with --edit'))
3464 3465 if opts.get('prefix'):
3465 3466 raise error.Abort(_('cannot use --exact with --prefix'))
3466 3467
3467 3468 base = opts["base"]
3468 3469 msgs = []
3469 3470 ret = 0
3470 3471
3471 3472 with repo.wlock():
3472 3473 if update:
3473 3474 cmdutil.checkunfinished(repo)
3474 3475 if (exact or not opts.get('force')):
3475 3476 cmdutil.bailifchanged(repo)
3476 3477
3477 3478 if not opts.get('no_commit'):
3478 3479 lock = repo.lock
3479 3480 tr = lambda: repo.transaction('import')
3480 3481 dsguard = util.nullcontextmanager
3481 3482 else:
3482 3483 lock = util.nullcontextmanager
3483 3484 tr = util.nullcontextmanager
3484 3485 dsguard = lambda: dirstateguard.dirstateguard(repo, 'import')
3485 3486 with lock(), tr(), dsguard():
3486 3487 parents = repo[None].parents()
3487 3488 for patchurl in patches:
3488 3489 if patchurl == '-':
3489 3490 ui.status(_('applying patch from stdin\n'))
3490 3491 patchfile = ui.fin
3491 3492 patchurl = 'stdin' # for error message
3492 3493 else:
3493 3494 patchurl = os.path.join(base, patchurl)
3494 3495 ui.status(_('applying %s\n') % patchurl)
3495 3496 patchfile = hg.openpath(ui, patchurl)
3496 3497
3497 3498 haspatch = False
3498 3499 for hunk in patch.split(patchfile):
3499 3500 with patch.extract(ui, hunk) as patchdata:
3500 3501 msg, node, rej = cmdutil.tryimportone(ui, repo,
3501 3502 patchdata,
3502 3503 parents, opts,
3503 3504 msgs, hg.clean)
3504 3505 if msg:
3505 3506 haspatch = True
3506 3507 ui.note(msg + '\n')
3507 3508 if update or exact:
3508 3509 parents = repo[None].parents()
3509 3510 else:
3510 3511 parents = [repo[node]]
3511 3512 if rej:
3512 3513 ui.write_err(_("patch applied partially\n"))
3513 3514 ui.write_err(_("(fix the .rej files and run "
3514 3515 "`hg commit --amend`)\n"))
3515 3516 ret = 1
3516 3517 break
3517 3518
3518 3519 if not haspatch:
3519 3520 raise error.Abort(_('%s: no diffs found') % patchurl)
3520 3521
3521 3522 if msgs:
3522 3523 repo.savecommitmessage('\n* * *\n'.join(msgs))
3523 3524 return ret
3524 3525
3525 3526 @command('incoming|in',
3526 3527 [('f', 'force', None,
3527 3528 _('run even if remote repository is unrelated')),
3528 3529 ('n', 'newest-first', None, _('show newest record first')),
3529 3530 ('', 'bundle', '',
3530 3531 _('file to store the bundles into'), _('FILE')),
3531 3532 ('r', 'rev', [], _('a remote changeset intended to be added'), _('REV')),
3532 3533 ('B', 'bookmarks', False, _("compare bookmarks")),
3533 3534 ('b', 'branch', [],
3534 3535 _('a specific branch you would like to pull'), _('BRANCH')),
3535 3536 ] + logopts + remoteopts + subrepoopts,
3536 3537 _('[-p] [-n] [-M] [-f] [-r REV]... [--bundle FILENAME] [SOURCE]'),
3537 3538 helpcategory=command.CATEGORY_REMOTE_REPO_MANAGEMENT)
3538 3539 def incoming(ui, repo, source="default", **opts):
3539 3540 """show new changesets found in source
3540 3541
3541 3542 Show new changesets found in the specified path/URL or the default
3542 3543 pull location. These are the changesets that would have been pulled
3543 3544 by :hg:`pull` at the time you issued this command.
3544 3545
3545 3546 See pull for valid source format details.
3546 3547
3547 3548 .. container:: verbose
3548 3549
3549 3550 With -B/--bookmarks, the result of bookmark comparison between
3550 3551 local and remote repositories is displayed. With -v/--verbose,
3551 3552 status is also displayed for each bookmark like below::
3552 3553
3553 3554 BM1 01234567890a added
3554 3555 BM2 1234567890ab advanced
3555 3556 BM3 234567890abc diverged
3556 3557 BM4 34567890abcd changed
3557 3558
3558 3559 The action taken locally when pulling depends on the
3559 3560 status of each bookmark:
3560 3561
3561 3562 :``added``: pull will create it
3562 3563 :``advanced``: pull will update it
3563 3564 :``diverged``: pull will create a divergent bookmark
3564 3565 :``changed``: result depends on remote changesets
3565 3566
3566 3567 From the point of view of pulling behavior, bookmark
3567 3568 existing only in the remote repository are treated as ``added``,
3568 3569 even if it is in fact locally deleted.
3569 3570
3570 3571 .. container:: verbose
3571 3572
3572 3573 For remote repository, using --bundle avoids downloading the
3573 3574 changesets twice if the incoming is followed by a pull.
3574 3575
3575 3576 Examples:
3576 3577
3577 3578 - show incoming changes with patches and full description::
3578 3579
3579 3580 hg incoming -vp
3580 3581
3581 3582 - show incoming changes excluding merges, store a bundle::
3582 3583
3583 3584 hg in -vpM --bundle incoming.hg
3584 3585 hg pull incoming.hg
3585 3586
3586 3587 - briefly list changes inside a bundle::
3587 3588
3588 3589 hg in changes.hg -T "{desc|firstline}\\n"
3589 3590
3590 3591 Returns 0 if there are incoming changes, 1 otherwise.
3591 3592 """
3592 3593 opts = pycompat.byteskwargs(opts)
3593 3594 if opts.get('graph'):
3594 3595 logcmdutil.checkunsupportedgraphflags([], opts)
3595 3596 def display(other, chlist, displayer):
3596 3597 revdag = logcmdutil.graphrevs(other, chlist, opts)
3597 3598 logcmdutil.displaygraph(ui, repo, revdag, displayer,
3598 3599 graphmod.asciiedges)
3599 3600
3600 3601 hg._incoming(display, lambda: 1, ui, repo, source, opts, buffered=True)
3601 3602 return 0
3602 3603
3603 3604 if opts.get('bundle') and opts.get('subrepos'):
3604 3605 raise error.Abort(_('cannot combine --bundle and --subrepos'))
3605 3606
3606 3607 if opts.get('bookmarks'):
3607 3608 source, branches = hg.parseurl(ui.expandpath(source),
3608 3609 opts.get('branch'))
3609 3610 other = hg.peer(repo, opts, source)
3610 3611 if 'bookmarks' not in other.listkeys('namespaces'):
3611 3612 ui.warn(_("remote doesn't support bookmarks\n"))
3612 3613 return 0
3613 3614 ui.pager('incoming')
3614 3615 ui.status(_('comparing with %s\n') % util.hidepassword(source))
3615 3616 return bookmarks.incoming(ui, repo, other)
3616 3617
3617 3618 repo._subtoppath = ui.expandpath(source)
3618 3619 try:
3619 3620 return hg.incoming(ui, repo, source, opts)
3620 3621 finally:
3621 3622 del repo._subtoppath
3622 3623
3623 3624
3624 3625 @command('init', remoteopts, _('[-e CMD] [--remotecmd CMD] [DEST]'),
3625 3626 helpcategory=command.CATEGORY_REPO_CREATION,
3626 3627 helpbasic=True, norepo=True)
3627 3628 def init(ui, dest=".", **opts):
3628 3629 """create a new repository in the given directory
3629 3630
3630 3631 Initialize a new repository in the given directory. If the given
3631 3632 directory does not exist, it will be created.
3632 3633
3633 3634 If no directory is given, the current directory is used.
3634 3635
3635 3636 It is possible to specify an ``ssh://`` URL as the destination.
3636 3637 See :hg:`help urls` for more information.
3637 3638
3638 3639 Returns 0 on success.
3639 3640 """
3640 3641 opts = pycompat.byteskwargs(opts)
3641 3642 hg.peer(ui, opts, ui.expandpath(dest), create=True)
3642 3643
3643 3644 @command('locate',
3644 3645 [('r', 'rev', '', _('search the repository as it is in REV'), _('REV')),
3645 3646 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
3646 3647 ('f', 'fullpath', None, _('print complete paths from the filesystem root')),
3647 3648 ] + walkopts,
3648 3649 _('[OPTION]... [PATTERN]...'),
3649 3650 helpcategory=command.CATEGORY_WORKING_DIRECTORY)
3650 3651 def locate(ui, repo, *pats, **opts):
3651 3652 """locate files matching specific patterns (DEPRECATED)
3652 3653
3653 3654 Print files under Mercurial control in the working directory whose
3654 3655 names match the given patterns.
3655 3656
3656 3657 By default, this command searches all directories in the working
3657 3658 directory. To search just the current directory and its
3658 3659 subdirectories, use "--include .".
3659 3660
3660 3661 If no patterns are given to match, this command prints the names
3661 3662 of all files under Mercurial control in the working directory.
3662 3663
3663 3664 If you want to feed the output of this command into the "xargs"
3664 3665 command, use the -0 option to both this command and "xargs". This
3665 3666 will avoid the problem of "xargs" treating single filenames that
3666 3667 contain whitespace as multiple filenames.
3667 3668
3668 3669 See :hg:`help files` for a more versatile command.
3669 3670
3670 3671 Returns 0 if a match is found, 1 otherwise.
3671 3672 """
3672 3673 opts = pycompat.byteskwargs(opts)
3673 3674 if opts.get('print0'):
3674 3675 end = '\0'
3675 3676 else:
3676 3677 end = '\n'
3677 3678 ctx = scmutil.revsingle(repo, opts.get('rev'), None)
3678 3679
3679 3680 ret = 1
3680 3681 m = scmutil.match(ctx, pats, opts, default='relglob',
3681 3682 badfn=lambda x, y: False)
3682 3683
3683 3684 ui.pager('locate')
3684 3685 if ctx.rev() is None:
3685 3686 # When run on the working copy, "locate" includes removed files, so
3686 3687 # we get the list of files from the dirstate.
3687 3688 filesgen = sorted(repo.dirstate.matches(m))
3688 3689 else:
3689 3690 filesgen = ctx.matches(m)
3690 3691 uipathfn = scmutil.getuipathfn(repo, legacyrelativevalue=bool(pats))
3691 3692 for abs in filesgen:
3692 3693 if opts.get('fullpath'):
3693 3694 ui.write(repo.wjoin(abs), end)
3694 3695 else:
3695 3696 ui.write(uipathfn(abs), end)
3696 3697 ret = 0
3697 3698
3698 3699 return ret
3699 3700
3700 3701 @command('log|history',
3701 3702 [('f', 'follow', None,
3702 3703 _('follow changeset history, or file history across copies and renames')),
3703 3704 ('', 'follow-first', None,
3704 3705 _('only follow the first parent of merge changesets (DEPRECATED)')),
3705 3706 ('d', 'date', '', _('show revisions matching date spec'), _('DATE')),
3706 3707 ('C', 'copies', None, _('show copied files')),
3707 3708 ('k', 'keyword', [],
3708 3709 _('do case-insensitive search for a given text'), _('TEXT')),
3709 3710 ('r', 'rev', [], _('show the specified revision or revset'), _('REV')),
3710 3711 ('L', 'line-range', [],
3711 3712 _('follow line range of specified file (EXPERIMENTAL)'),
3712 3713 _('FILE,RANGE')),
3713 3714 ('', 'removed', None, _('include revisions where files were removed')),
3714 3715 ('m', 'only-merges', None, _('show only merges (DEPRECATED)')),
3715 3716 ('u', 'user', [], _('revisions committed by user'), _('USER')),
3716 3717 ('', 'only-branch', [],
3717 3718 _('show only changesets within the given named branch (DEPRECATED)'),
3718 3719 _('BRANCH')),
3719 3720 ('b', 'branch', [],
3720 3721 _('show changesets within the given named branch'), _('BRANCH')),
3721 3722 ('P', 'prune', [],
3722 3723 _('do not display revision or any of its ancestors'), _('REV')),
3723 3724 ] + logopts + walkopts,
3724 3725 _('[OPTION]... [FILE]'),
3725 3726 helpcategory=command.CATEGORY_CHANGE_NAVIGATION,
3726 3727 helpbasic=True, inferrepo=True,
3727 3728 intents={INTENT_READONLY})
3728 3729 def log(ui, repo, *pats, **opts):
3729 3730 """show revision history of entire repository or files
3730 3731
3731 3732 Print the revision history of the specified files or the entire
3732 3733 project.
3733 3734
3734 3735 If no revision range is specified, the default is ``tip:0`` unless
3735 3736 --follow is set, in which case the working directory parent is
3736 3737 used as the starting revision.
3737 3738
3738 3739 File history is shown without following rename or copy history of
3739 3740 files. Use -f/--follow with a filename to follow history across
3740 3741 renames and copies. --follow without a filename will only show
3741 3742 ancestors of the starting revision.
3742 3743
3743 3744 By default this command prints revision number and changeset id,
3744 3745 tags, non-trivial parents, user, date and time, and a summary for
3745 3746 each commit. When the -v/--verbose switch is used, the list of
3746 3747 changed files and full commit message are shown.
3747 3748
3748 3749 With --graph the revisions are shown as an ASCII art DAG with the most
3749 3750 recent changeset at the top.
3750 3751 'o' is a changeset, '@' is a working directory parent, '_' closes a branch,
3751 3752 'x' is obsolete, '*' is unstable, and '+' represents a fork where the
3752 3753 changeset from the lines below is a parent of the 'o' merge on the same
3753 3754 line.
3754 3755 Paths in the DAG are represented with '|', '/' and so forth. ':' in place
3755 3756 of a '|' indicates one or more revisions in a path are omitted.
3756 3757
3757 3758 .. container:: verbose
3758 3759
3759 3760 Use -L/--line-range FILE,M:N options to follow the history of lines
3760 3761 from M to N in FILE. With -p/--patch only diff hunks affecting
3761 3762 specified line range will be shown. This option requires --follow;
3762 3763 it can be specified multiple times. Currently, this option is not
3763 3764 compatible with --graph. This option is experimental.
3764 3765
3765 3766 .. note::
3766 3767
3767 3768 :hg:`log --patch` may generate unexpected diff output for merge
3768 3769 changesets, as it will only compare the merge changeset against
3769 3770 its first parent. Also, only files different from BOTH parents
3770 3771 will appear in files:.
3771 3772
3772 3773 .. note::
3773 3774
3774 3775 For performance reasons, :hg:`log FILE` may omit duplicate changes
3775 3776 made on branches and will not show removals or mode changes. To
3776 3777 see all such changes, use the --removed switch.
3777 3778
3778 3779 .. container:: verbose
3779 3780
3780 3781 .. note::
3781 3782
3782 3783 The history resulting from -L/--line-range options depends on diff
3783 3784 options; for instance if white-spaces are ignored, respective changes
3784 3785 with only white-spaces in specified line range will not be listed.
3785 3786
3786 3787 .. container:: verbose
3787 3788
3788 3789 Some examples:
3789 3790
3790 3791 - changesets with full descriptions and file lists::
3791 3792
3792 3793 hg log -v
3793 3794
3794 3795 - changesets ancestral to the working directory::
3795 3796
3796 3797 hg log -f
3797 3798
3798 3799 - last 10 commits on the current branch::
3799 3800
3800 3801 hg log -l 10 -b .
3801 3802
3802 3803 - changesets showing all modifications of a file, including removals::
3803 3804
3804 3805 hg log --removed file.c
3805 3806
3806 3807 - all changesets that touch a directory, with diffs, excluding merges::
3807 3808
3808 3809 hg log -Mp lib/
3809 3810
3810 3811 - all revision numbers that match a keyword::
3811 3812
3812 3813 hg log -k bug --template "{rev}\\n"
3813 3814
3814 3815 - the full hash identifier of the working directory parent::
3815 3816
3816 3817 hg log -r . --template "{node}\\n"
3817 3818
3818 3819 - list available log templates::
3819 3820
3820 3821 hg log -T list
3821 3822
3822 3823 - check if a given changeset is included in a tagged release::
3823 3824
3824 3825 hg log -r "a21ccf and ancestor(1.9)"
3825 3826
3826 3827 - find all changesets by some user in a date range::
3827 3828
3828 3829 hg log -k alice -d "may 2008 to jul 2008"
3829 3830
3830 3831 - summary of all changesets after the last tag::
3831 3832
3832 3833 hg log -r "last(tagged())::" --template "{desc|firstline}\\n"
3833 3834
3834 3835 - changesets touching lines 13 to 23 for file.c::
3835 3836
3836 3837 hg log -L file.c,13:23
3837 3838
3838 3839 - changesets touching lines 13 to 23 for file.c and lines 2 to 6 of
3839 3840 main.c with patch::
3840 3841
3841 3842 hg log -L file.c,13:23 -L main.c,2:6 -p
3842 3843
3843 3844 See :hg:`help dates` for a list of formats valid for -d/--date.
3844 3845
3845 3846 See :hg:`help revisions` for more about specifying and ordering
3846 3847 revisions.
3847 3848
3848 3849 See :hg:`help templates` for more about pre-packaged styles and
3849 3850 specifying custom templates. The default template used by the log
3850 3851 command can be customized via the ``ui.logtemplate`` configuration
3851 3852 setting.
3852 3853
3853 3854 Returns 0 on success.
3854 3855
3855 3856 """
3856 3857 opts = pycompat.byteskwargs(opts)
3857 3858 linerange = opts.get('line_range')
3858 3859
3859 3860 if linerange and not opts.get('follow'):
3860 3861 raise error.Abort(_('--line-range requires --follow'))
3861 3862
3862 3863 if linerange and pats:
3863 3864 # TODO: take pats as patterns with no line-range filter
3864 3865 raise error.Abort(
3865 3866 _('FILE arguments are not compatible with --line-range option')
3866 3867 )
3867 3868
3868 3869 repo = scmutil.unhidehashlikerevs(repo, opts.get('rev'), 'nowarn')
3869 3870 revs, differ = logcmdutil.getrevs(repo, pats, opts)
3870 3871 if linerange:
3871 3872 # TODO: should follow file history from logcmdutil._initialrevs(),
3872 3873 # then filter the result by logcmdutil._makerevset() and --limit
3873 3874 revs, differ = logcmdutil.getlinerangerevs(repo, revs, opts)
3874 3875
3875 3876 getrenamed = None
3876 3877 if opts.get('copies'):
3877 3878 endrev = None
3878 3879 if revs:
3879 3880 endrev = revs.max() + 1
3880 3881 getrenamed = templatekw.getrenamedfn(repo, endrev=endrev)
3881 3882
3882 3883 ui.pager('log')
3883 3884 displayer = logcmdutil.changesetdisplayer(ui, repo, opts, differ,
3884 3885 buffered=True)
3885 3886 if opts.get('graph'):
3886 3887 displayfn = logcmdutil.displaygraphrevs
3887 3888 else:
3888 3889 displayfn = logcmdutil.displayrevs
3889 3890 displayfn(ui, repo, revs, displayer, getrenamed)
3890 3891
3891 3892 @command('manifest',
3892 3893 [('r', 'rev', '', _('revision to display'), _('REV')),
3893 3894 ('', 'all', False, _("list files from all revisions"))]
3894 3895 + formatteropts,
3895 3896 _('[-r REV]'),
3896 3897 helpcategory=command.CATEGORY_MAINTENANCE,
3897 3898 intents={INTENT_READONLY})
3898 3899 def manifest(ui, repo, node=None, rev=None, **opts):
3899 3900 """output the current or given revision of the project manifest
3900 3901
3901 3902 Print a list of version controlled files for the given revision.
3902 3903 If no revision is given, the first parent of the working directory
3903 3904 is used, or the null revision if no revision is checked out.
3904 3905
3905 3906 With -v, print file permissions, symlink and executable bits.
3906 3907 With --debug, print file revision hashes.
3907 3908
3908 3909 If option --all is specified, the list of all files from all revisions
3909 3910 is printed. This includes deleted and renamed files.
3910 3911
3911 3912 Returns 0 on success.
3912 3913 """
3913 3914 opts = pycompat.byteskwargs(opts)
3914 3915 fm = ui.formatter('manifest', opts)
3915 3916
3916 3917 if opts.get('all'):
3917 3918 if rev or node:
3918 3919 raise error.Abort(_("can't specify a revision with --all"))
3919 3920
3920 3921 res = set()
3921 3922 for rev in repo:
3922 3923 ctx = repo[rev]
3923 3924 res |= set(ctx.files())
3924 3925
3925 3926 ui.pager('manifest')
3926 3927 for f in sorted(res):
3927 3928 fm.startitem()
3928 3929 fm.write("path", '%s\n', f)
3929 3930 fm.end()
3930 3931 return
3931 3932
3932 3933 if rev and node:
3933 3934 raise error.Abort(_("please specify just one revision"))
3934 3935
3935 3936 if not node:
3936 3937 node = rev
3937 3938
3938 3939 char = {'l': '@', 'x': '*', '': '', 't': 'd'}
3939 3940 mode = {'l': '644', 'x': '755', '': '644', 't': '755'}
3940 3941 if node:
3941 3942 repo = scmutil.unhidehashlikerevs(repo, [node], 'nowarn')
3942 3943 ctx = scmutil.revsingle(repo, node)
3943 3944 mf = ctx.manifest()
3944 3945 ui.pager('manifest')
3945 3946 for f in ctx:
3946 3947 fm.startitem()
3947 3948 fm.context(ctx=ctx)
3948 3949 fl = ctx[f].flags()
3949 3950 fm.condwrite(ui.debugflag, 'hash', '%s ', hex(mf[f]))
3950 3951 fm.condwrite(ui.verbose, 'mode type', '%s %1s ', mode[fl], char[fl])
3951 3952 fm.write('path', '%s\n', f)
3952 3953 fm.end()
3953 3954
3954 3955 @command('merge',
3955 3956 [('f', 'force', None,
3956 3957 _('force a merge including outstanding changes (DEPRECATED)')),
3957 3958 ('r', 'rev', '', _('revision to merge'), _('REV')),
3958 3959 ('P', 'preview', None,
3959 3960 _('review revisions to merge (no merge is performed)')),
3960 3961 ('', 'abort', None, _('abort the ongoing merge')),
3961 3962 ] + mergetoolopts,
3962 3963 _('[-P] [[-r] REV]'),
3963 3964 helpcategory=command.CATEGORY_CHANGE_MANAGEMENT, helpbasic=True)
3964 3965 def merge(ui, repo, node=None, **opts):
3965 3966 """merge another revision into working directory
3966 3967
3967 3968 The current working directory is updated with all changes made in
3968 3969 the requested revision since the last common predecessor revision.
3969 3970
3970 3971 Files that changed between either parent are marked as changed for
3971 3972 the next commit and a commit must be performed before any further
3972 3973 updates to the repository are allowed. The next commit will have
3973 3974 two parents.
3974 3975
3975 3976 ``--tool`` can be used to specify the merge tool used for file
3976 3977 merges. It overrides the HGMERGE environment variable and your
3977 3978 configuration files. See :hg:`help merge-tools` for options.
3978 3979
3979 3980 If no revision is specified, the working directory's parent is a
3980 3981 head revision, and the current branch contains exactly one other
3981 3982 head, the other head is merged with by default. Otherwise, an
3982 3983 explicit revision with which to merge with must be provided.
3983 3984
3984 3985 See :hg:`help resolve` for information on handling file conflicts.
3985 3986
3986 3987 To undo an uncommitted merge, use :hg:`merge --abort` which
3987 3988 will check out a clean copy of the original merge parent, losing
3988 3989 all changes.
3989 3990
3990 3991 Returns 0 on success, 1 if there are unresolved files.
3991 3992 """
3992 3993
3993 3994 opts = pycompat.byteskwargs(opts)
3994 3995 abort = opts.get('abort')
3995 3996 if abort and repo.dirstate.p2() == nullid:
3996 3997 cmdutil.wrongtooltocontinue(repo, _('merge'))
3997 3998 if abort:
3998 3999 if node:
3999 4000 raise error.Abort(_("cannot specify a node with --abort"))
4000 4001 if opts.get('rev'):
4001 4002 raise error.Abort(_("cannot specify both --rev and --abort"))
4002 4003 if opts.get('preview'):
4003 4004 raise error.Abort(_("cannot specify --preview with --abort"))
4004 4005 if opts.get('rev') and node:
4005 4006 raise error.Abort(_("please specify just one revision"))
4006 4007 if not node:
4007 4008 node = opts.get('rev')
4008 4009
4009 4010 if node:
4010 4011 node = scmutil.revsingle(repo, node).node()
4011 4012
4012 4013 if not node and not abort:
4013 4014 node = repo[destutil.destmerge(repo)].node()
4014 4015
4015 4016 if opts.get('preview'):
4016 4017 # find nodes that are ancestors of p2 but not of p1
4017 4018 p1 = repo.lookup('.')
4018 4019 p2 = node
4019 4020 nodes = repo.changelog.findmissing(common=[p1], heads=[p2])
4020 4021
4021 4022 displayer = logcmdutil.changesetdisplayer(ui, repo, opts)
4022 4023 for node in nodes:
4023 4024 displayer.show(repo[node])
4024 4025 displayer.close()
4025 4026 return 0
4026 4027
4027 4028 # ui.forcemerge is an internal variable, do not document
4028 4029 overrides = {('ui', 'forcemerge'): opts.get('tool', '')}
4029 4030 with ui.configoverride(overrides, 'merge'):
4030 4031 force = opts.get('force')
4031 4032 labels = ['working copy', 'merge rev']
4032 4033 return hg.merge(repo, node, force=force, mergeforce=force,
4033 4034 labels=labels, abort=abort)
4034 4035
4035 4036 @command('outgoing|out',
4036 4037 [('f', 'force', None, _('run even when the destination is unrelated')),
4037 4038 ('r', 'rev', [],
4038 4039 _('a changeset intended to be included in the destination'), _('REV')),
4039 4040 ('n', 'newest-first', None, _('show newest record first')),
4040 4041 ('B', 'bookmarks', False, _('compare bookmarks')),
4041 4042 ('b', 'branch', [], _('a specific branch you would like to push'),
4042 4043 _('BRANCH')),
4043 4044 ] + logopts + remoteopts + subrepoopts,
4044 4045 _('[-M] [-p] [-n] [-f] [-r REV]... [DEST]'),
4045 4046 helpcategory=command.CATEGORY_REMOTE_REPO_MANAGEMENT)
4046 4047 def outgoing(ui, repo, dest=None, **opts):
4047 4048 """show changesets not found in the destination
4048 4049
4049 4050 Show changesets not found in the specified destination repository
4050 4051 or the default push location. These are the changesets that would
4051 4052 be pushed if a push was requested.
4052 4053
4053 4054 See pull for details of valid destination formats.
4054 4055
4055 4056 .. container:: verbose
4056 4057
4057 4058 With -B/--bookmarks, the result of bookmark comparison between
4058 4059 local and remote repositories is displayed. With -v/--verbose,
4059 4060 status is also displayed for each bookmark like below::
4060 4061
4061 4062 BM1 01234567890a added
4062 4063 BM2 deleted
4063 4064 BM3 234567890abc advanced
4064 4065 BM4 34567890abcd diverged
4065 4066 BM5 4567890abcde changed
4066 4067
4067 4068 The action taken when pushing depends on the
4068 4069 status of each bookmark:
4069 4070
4070 4071 :``added``: push with ``-B`` will create it
4071 4072 :``deleted``: push with ``-B`` will delete it
4072 4073 :``advanced``: push will update it
4073 4074 :``diverged``: push with ``-B`` will update it
4074 4075 :``changed``: push with ``-B`` will update it
4075 4076
4076 4077 From the point of view of pushing behavior, bookmarks
4077 4078 existing only in the remote repository are treated as
4078 4079 ``deleted``, even if it is in fact added remotely.
4079 4080
4080 4081 Returns 0 if there are outgoing changes, 1 otherwise.
4081 4082 """
4082 4083 # hg._outgoing() needs to re-resolve the path in order to handle #branch
4083 4084 # style URLs, so don't overwrite dest.
4084 4085 path = ui.paths.getpath(dest, default=('default-push', 'default'))
4085 4086 if not path:
4086 4087 raise error.Abort(_('default repository not configured!'),
4087 4088 hint=_("see 'hg help config.paths'"))
4088 4089
4089 4090 opts = pycompat.byteskwargs(opts)
4090 4091 if opts.get('graph'):
4091 4092 logcmdutil.checkunsupportedgraphflags([], opts)
4092 4093 o, other = hg._outgoing(ui, repo, dest, opts)
4093 4094 if not o:
4094 4095 cmdutil.outgoinghooks(ui, repo, other, opts, o)
4095 4096 return
4096 4097
4097 4098 revdag = logcmdutil.graphrevs(repo, o, opts)
4098 4099 ui.pager('outgoing')
4099 4100 displayer = logcmdutil.changesetdisplayer(ui, repo, opts, buffered=True)
4100 4101 logcmdutil.displaygraph(ui, repo, revdag, displayer,
4101 4102 graphmod.asciiedges)
4102 4103 cmdutil.outgoinghooks(ui, repo, other, opts, o)
4103 4104 return 0
4104 4105
4105 4106 if opts.get('bookmarks'):
4106 4107 dest = path.pushloc or path.loc
4107 4108 other = hg.peer(repo, opts, dest)
4108 4109 if 'bookmarks' not in other.listkeys('namespaces'):
4109 4110 ui.warn(_("remote doesn't support bookmarks\n"))
4110 4111 return 0
4111 4112 ui.status(_('comparing with %s\n') % util.hidepassword(dest))
4112 4113 ui.pager('outgoing')
4113 4114 return bookmarks.outgoing(ui, repo, other)
4114 4115
4115 4116 repo._subtoppath = path.pushloc or path.loc
4116 4117 try:
4117 4118 return hg.outgoing(ui, repo, dest, opts)
4118 4119 finally:
4119 4120 del repo._subtoppath
4120 4121
4121 4122 @command('parents',
4122 4123 [('r', 'rev', '', _('show parents of the specified revision'), _('REV')),
4123 4124 ] + templateopts,
4124 4125 _('[-r REV] [FILE]'),
4125 4126 helpcategory=command.CATEGORY_CHANGE_NAVIGATION,
4126 4127 inferrepo=True)
4127 4128 def parents(ui, repo, file_=None, **opts):
4128 4129 """show the parents of the working directory or revision (DEPRECATED)
4129 4130
4130 4131 Print the working directory's parent revisions. If a revision is
4131 4132 given via -r/--rev, the parent of that revision will be printed.
4132 4133 If a file argument is given, the revision in which the file was
4133 4134 last changed (before the working directory revision or the
4134 4135 argument to --rev if given) is printed.
4135 4136
4136 4137 This command is equivalent to::
4137 4138
4138 4139 hg log -r "p1()+p2()" or
4139 4140 hg log -r "p1(REV)+p2(REV)" or
4140 4141 hg log -r "max(::p1() and file(FILE))+max(::p2() and file(FILE))" or
4141 4142 hg log -r "max(::p1(REV) and file(FILE))+max(::p2(REV) and file(FILE))"
4142 4143
4143 4144 See :hg:`summary` and :hg:`help revsets` for related information.
4144 4145
4145 4146 Returns 0 on success.
4146 4147 """
4147 4148
4148 4149 opts = pycompat.byteskwargs(opts)
4149 4150 rev = opts.get('rev')
4150 4151 if rev:
4151 4152 repo = scmutil.unhidehashlikerevs(repo, [rev], 'nowarn')
4152 4153 ctx = scmutil.revsingle(repo, rev, None)
4153 4154
4154 4155 if file_:
4155 4156 m = scmutil.match(ctx, (file_,), opts)
4156 4157 if m.anypats() or len(m.files()) != 1:
4157 4158 raise error.Abort(_('can only specify an explicit filename'))
4158 4159 file_ = m.files()[0]
4159 4160 filenodes = []
4160 4161 for cp in ctx.parents():
4161 4162 if not cp:
4162 4163 continue
4163 4164 try:
4164 4165 filenodes.append(cp.filenode(file_))
4165 4166 except error.LookupError:
4166 4167 pass
4167 4168 if not filenodes:
4168 4169 raise error.Abort(_("'%s' not found in manifest!") % file_)
4169 4170 p = []
4170 4171 for fn in filenodes:
4171 4172 fctx = repo.filectx(file_, fileid=fn)
4172 4173 p.append(fctx.node())
4173 4174 else:
4174 4175 p = [cp.node() for cp in ctx.parents()]
4175 4176
4176 4177 displayer = logcmdutil.changesetdisplayer(ui, repo, opts)
4177 4178 for n in p:
4178 4179 if n != nullid:
4179 4180 displayer.show(repo[n])
4180 4181 displayer.close()
4181 4182
4182 4183 @command('paths', formatteropts, _('[NAME]'),
4183 4184 helpcategory=command.CATEGORY_REMOTE_REPO_MANAGEMENT,
4184 4185 optionalrepo=True, intents={INTENT_READONLY})
4185 4186 def paths(ui, repo, search=None, **opts):
4186 4187 """show aliases for remote repositories
4187 4188
4188 4189 Show definition of symbolic path name NAME. If no name is given,
4189 4190 show definition of all available names.
4190 4191
4191 4192 Option -q/--quiet suppresses all output when searching for NAME
4192 4193 and shows only the path names when listing all definitions.
4193 4194
4194 4195 Path names are defined in the [paths] section of your
4195 4196 configuration file and in ``/etc/mercurial/hgrc``. If run inside a
4196 4197 repository, ``.hg/hgrc`` is used, too.
4197 4198
4198 4199 The path names ``default`` and ``default-push`` have a special
4199 4200 meaning. When performing a push or pull operation, they are used
4200 4201 as fallbacks if no location is specified on the command-line.
4201 4202 When ``default-push`` is set, it will be used for push and
4202 4203 ``default`` will be used for pull; otherwise ``default`` is used
4203 4204 as the fallback for both. When cloning a repository, the clone
4204 4205 source is written as ``default`` in ``.hg/hgrc``.
4205 4206
4206 4207 .. note::
4207 4208
4208 4209 ``default`` and ``default-push`` apply to all inbound (e.g.
4209 4210 :hg:`incoming`) and outbound (e.g. :hg:`outgoing`, :hg:`email`
4210 4211 and :hg:`bundle`) operations.
4211 4212
4212 4213 See :hg:`help urls` for more information.
4213 4214
4214 4215 .. container:: verbose
4215 4216
4216 4217 Template:
4217 4218
4218 4219 The following keywords are supported. See also :hg:`help templates`.
4219 4220
4220 4221 :name: String. Symbolic name of the path alias.
4221 4222 :pushurl: String. URL for push operations.
4222 4223 :url: String. URL or directory path for the other operations.
4223 4224
4224 4225 Returns 0 on success.
4225 4226 """
4226 4227
4227 4228 opts = pycompat.byteskwargs(opts)
4228 4229 ui.pager('paths')
4229 4230 if search:
4230 4231 pathitems = [(name, path) for name, path in ui.paths.iteritems()
4231 4232 if name == search]
4232 4233 else:
4233 4234 pathitems = sorted(ui.paths.iteritems())
4234 4235
4235 4236 fm = ui.formatter('paths', opts)
4236 4237 if fm.isplain():
4237 4238 hidepassword = util.hidepassword
4238 4239 else:
4239 4240 hidepassword = bytes
4240 4241 if ui.quiet:
4241 4242 namefmt = '%s\n'
4242 4243 else:
4243 4244 namefmt = '%s = '
4244 4245 showsubopts = not search and not ui.quiet
4245 4246
4246 4247 for name, path in pathitems:
4247 4248 fm.startitem()
4248 4249 fm.condwrite(not search, 'name', namefmt, name)
4249 4250 fm.condwrite(not ui.quiet, 'url', '%s\n', hidepassword(path.rawloc))
4250 4251 for subopt, value in sorted(path.suboptions.items()):
4251 4252 assert subopt not in ('name', 'url')
4252 4253 if showsubopts:
4253 4254 fm.plain('%s:%s = ' % (name, subopt))
4254 4255 fm.condwrite(showsubopts, subopt, '%s\n', value)
4255 4256
4256 4257 fm.end()
4257 4258
4258 4259 if search and not pathitems:
4259 4260 if not ui.quiet:
4260 4261 ui.warn(_("not found!\n"))
4261 4262 return 1
4262 4263 else:
4263 4264 return 0
4264 4265
4265 4266 @command('phase',
4266 4267 [('p', 'public', False, _('set changeset phase to public')),
4267 4268 ('d', 'draft', False, _('set changeset phase to draft')),
4268 4269 ('s', 'secret', False, _('set changeset phase to secret')),
4269 4270 ('f', 'force', False, _('allow to move boundary backward')),
4270 4271 ('r', 'rev', [], _('target revision'), _('REV')),
4271 4272 ],
4272 4273 _('[-p|-d|-s] [-f] [-r] [REV...]'),
4273 4274 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION)
4274 4275 def phase(ui, repo, *revs, **opts):
4275 4276 """set or show the current phase name
4276 4277
4277 4278 With no argument, show the phase name of the current revision(s).
4278 4279
4279 4280 With one of -p/--public, -d/--draft or -s/--secret, change the
4280 4281 phase value of the specified revisions.
4281 4282
4282 4283 Unless -f/--force is specified, :hg:`phase` won't move changesets from a
4283 4284 lower phase to a higher phase. Phases are ordered as follows::
4284 4285
4285 4286 public < draft < secret
4286 4287
4287 4288 Returns 0 on success, 1 if some phases could not be changed.
4288 4289
4289 4290 (For more information about the phases concept, see :hg:`help phases`.)
4290 4291 """
4291 4292 opts = pycompat.byteskwargs(opts)
4292 4293 # search for a unique phase argument
4293 4294 targetphase = None
4294 4295 for idx, name in enumerate(phases.cmdphasenames):
4295 4296 if opts[name]:
4296 4297 if targetphase is not None:
4297 4298 raise error.Abort(_('only one phase can be specified'))
4298 4299 targetphase = idx
4299 4300
4300 4301 # look for specified revision
4301 4302 revs = list(revs)
4302 4303 revs.extend(opts['rev'])
4303 4304 if not revs:
4304 4305 # display both parents as the second parent phase can influence
4305 4306 # the phase of a merge commit
4306 4307 revs = [c.rev() for c in repo[None].parents()]
4307 4308
4308 4309 revs = scmutil.revrange(repo, revs)
4309 4310
4310 4311 ret = 0
4311 4312 if targetphase is None:
4312 4313 # display
4313 4314 for r in revs:
4314 4315 ctx = repo[r]
4315 4316 ui.write('%i: %s\n' % (ctx.rev(), ctx.phasestr()))
4316 4317 else:
4317 4318 with repo.lock(), repo.transaction("phase") as tr:
4318 4319 # set phase
4319 4320 if not revs:
4320 4321 raise error.Abort(_('empty revision set'))
4321 4322 nodes = [repo[r].node() for r in revs]
4322 4323 # moving revision from public to draft may hide them
4323 4324 # We have to check result on an unfiltered repository
4324 4325 unfi = repo.unfiltered()
4325 4326 getphase = unfi._phasecache.phase
4326 4327 olddata = [getphase(unfi, r) for r in unfi]
4327 4328 phases.advanceboundary(repo, tr, targetphase, nodes)
4328 4329 if opts['force']:
4329 4330 phases.retractboundary(repo, tr, targetphase, nodes)
4330 4331 getphase = unfi._phasecache.phase
4331 4332 newdata = [getphase(unfi, r) for r in unfi]
4332 4333 changes = sum(newdata[r] != olddata[r] for r in unfi)
4333 4334 cl = unfi.changelog
4334 4335 rejected = [n for n in nodes
4335 4336 if newdata[cl.rev(n)] < targetphase]
4336 4337 if rejected:
4337 4338 ui.warn(_('cannot move %i changesets to a higher '
4338 4339 'phase, use --force\n') % len(rejected))
4339 4340 ret = 1
4340 4341 if changes:
4341 4342 msg = _('phase changed for %i changesets\n') % changes
4342 4343 if ret:
4343 4344 ui.status(msg)
4344 4345 else:
4345 4346 ui.note(msg)
4346 4347 else:
4347 4348 ui.warn(_('no phases changed\n'))
4348 4349 return ret
4349 4350
4350 4351 def postincoming(ui, repo, modheads, optupdate, checkout, brev):
4351 4352 """Run after a changegroup has been added via pull/unbundle
4352 4353
4353 4354 This takes arguments below:
4354 4355
4355 4356 :modheads: change of heads by pull/unbundle
4356 4357 :optupdate: updating working directory is needed or not
4357 4358 :checkout: update destination revision (or None to default destination)
4358 4359 :brev: a name, which might be a bookmark to be activated after updating
4359 4360 """
4360 4361 if modheads == 0:
4361 4362 return
4362 4363 if optupdate:
4363 4364 try:
4364 4365 return hg.updatetotally(ui, repo, checkout, brev)
4365 4366 except error.UpdateAbort as inst:
4366 4367 msg = _("not updating: %s") % stringutil.forcebytestr(inst)
4367 4368 hint = inst.hint
4368 4369 raise error.UpdateAbort(msg, hint=hint)
4369 4370 if modheads is not None and modheads > 1:
4370 4371 currentbranchheads = len(repo.branchheads())
4371 4372 if currentbranchheads == modheads:
4372 4373 ui.status(_("(run 'hg heads' to see heads, 'hg merge' to merge)\n"))
4373 4374 elif currentbranchheads > 1:
4374 4375 ui.status(_("(run 'hg heads .' to see heads, 'hg merge' to "
4375 4376 "merge)\n"))
4376 4377 else:
4377 4378 ui.status(_("(run 'hg heads' to see heads)\n"))
4378 4379 elif not ui.configbool('commands', 'update.requiredest'):
4379 4380 ui.status(_("(run 'hg update' to get a working copy)\n"))
4380 4381
4381 4382 @command('pull',
4382 4383 [('u', 'update', None,
4383 4384 _('update to new branch head if new descendants were pulled')),
4384 4385 ('f', 'force', None, _('run even when remote repository is unrelated')),
4385 4386 ('r', 'rev', [], _('a remote changeset intended to be added'), _('REV')),
4386 4387 ('B', 'bookmark', [], _("bookmark to pull"), _('BOOKMARK')),
4387 4388 ('b', 'branch', [], _('a specific branch you would like to pull'),
4388 4389 _('BRANCH')),
4389 4390 ] + remoteopts,
4390 4391 _('[-u] [-f] [-r REV]... [-e CMD] [--remotecmd CMD] [SOURCE]'),
4391 4392 helpcategory=command.CATEGORY_REMOTE_REPO_MANAGEMENT,
4392 4393 helpbasic=True)
4393 4394 def pull(ui, repo, source="default", **opts):
4394 4395 """pull changes from the specified source
4395 4396
4396 4397 Pull changes from a remote repository to a local one.
4397 4398
4398 4399 This finds all changes from the repository at the specified path
4399 4400 or URL and adds them to a local repository (the current one unless
4400 4401 -R is specified). By default, this does not update the copy of the
4401 4402 project in the working directory.
4402 4403
4403 4404 When cloning from servers that support it, Mercurial may fetch
4404 4405 pre-generated data. When this is done, hooks operating on incoming
4405 4406 changesets and changegroups may fire more than once, once for each
4406 4407 pre-generated bundle and as well as for any additional remaining
4407 4408 data. See :hg:`help -e clonebundles` for more.
4408 4409
4409 4410 Use :hg:`incoming` if you want to see what would have been added
4410 4411 by a pull at the time you issued this command. If you then decide
4411 4412 to add those changes to the repository, you should use :hg:`pull
4412 4413 -r X` where ``X`` is the last changeset listed by :hg:`incoming`.
4413 4414
4414 4415 If SOURCE is omitted, the 'default' path will be used.
4415 4416 See :hg:`help urls` for more information.
4416 4417
4417 4418 Specifying bookmark as ``.`` is equivalent to specifying the active
4418 4419 bookmark's name.
4419 4420
4420 4421 Returns 0 on success, 1 if an update had unresolved files.
4421 4422 """
4422 4423
4423 4424 opts = pycompat.byteskwargs(opts)
4424 4425 if ui.configbool('commands', 'update.requiredest') and opts.get('update'):
4425 4426 msg = _('update destination required by configuration')
4426 4427 hint = _('use hg pull followed by hg update DEST')
4427 4428 raise error.Abort(msg, hint=hint)
4428 4429
4429 4430 source, branches = hg.parseurl(ui.expandpath(source), opts.get('branch'))
4430 4431 ui.status(_('pulling from %s\n') % util.hidepassword(source))
4431 4432 other = hg.peer(repo, opts, source)
4432 4433 try:
4433 4434 revs, checkout = hg.addbranchrevs(repo, other, branches,
4434 4435 opts.get('rev'))
4435 4436
4436 4437 pullopargs = {}
4437 4438
4438 4439 nodes = None
4439 4440 if opts.get('bookmark') or revs:
4440 4441 # The list of bookmark used here is the same used to actually update
4441 4442 # the bookmark names, to avoid the race from issue 4689 and we do
4442 4443 # all lookup and bookmark queries in one go so they see the same
4443 4444 # version of the server state (issue 4700).
4444 4445 nodes = []
4445 4446 fnodes = []
4446 4447 revs = revs or []
4447 4448 if revs and not other.capable('lookup'):
4448 4449 err = _("other repository doesn't support revision lookup, "
4449 4450 "so a rev cannot be specified.")
4450 4451 raise error.Abort(err)
4451 4452 with other.commandexecutor() as e:
4452 4453 fremotebookmarks = e.callcommand('listkeys', {
4453 4454 'namespace': 'bookmarks'
4454 4455 })
4455 4456 for r in revs:
4456 4457 fnodes.append(e.callcommand('lookup', {'key': r}))
4457 4458 remotebookmarks = fremotebookmarks.result()
4458 4459 remotebookmarks = bookmarks.unhexlifybookmarks(remotebookmarks)
4459 4460 pullopargs['remotebookmarks'] = remotebookmarks
4460 4461 for b in opts.get('bookmark', []):
4461 4462 b = repo._bookmarks.expandname(b)
4462 4463 if b not in remotebookmarks:
4463 4464 raise error.Abort(_('remote bookmark %s not found!') % b)
4464 4465 nodes.append(remotebookmarks[b])
4465 4466 for i, rev in enumerate(revs):
4466 4467 node = fnodes[i].result()
4467 4468 nodes.append(node)
4468 4469 if rev == checkout:
4469 4470 checkout = node
4470 4471
4471 4472 wlock = util.nullcontextmanager()
4472 4473 if opts.get('update'):
4473 4474 wlock = repo.wlock()
4474 4475 with wlock:
4475 4476 pullopargs.update(opts.get('opargs', {}))
4476 4477 modheads = exchange.pull(repo, other, heads=nodes,
4477 4478 force=opts.get('force'),
4478 4479 bookmarks=opts.get('bookmark', ()),
4479 4480 opargs=pullopargs).cgresult
4480 4481
4481 4482 # brev is a name, which might be a bookmark to be activated at
4482 4483 # the end of the update. In other words, it is an explicit
4483 4484 # destination of the update
4484 4485 brev = None
4485 4486
4486 4487 if checkout:
4487 4488 checkout = repo.changelog.rev(checkout)
4488 4489
4489 4490 # order below depends on implementation of
4490 4491 # hg.addbranchrevs(). opts['bookmark'] is ignored,
4491 4492 # because 'checkout' is determined without it.
4492 4493 if opts.get('rev'):
4493 4494 brev = opts['rev'][0]
4494 4495 elif opts.get('branch'):
4495 4496 brev = opts['branch'][0]
4496 4497 else:
4497 4498 brev = branches[0]
4498 4499 repo._subtoppath = source
4499 4500 try:
4500 4501 ret = postincoming(ui, repo, modheads, opts.get('update'),
4501 4502 checkout, brev)
4502 4503
4503 4504 finally:
4504 4505 del repo._subtoppath
4505 4506
4506 4507 finally:
4507 4508 other.close()
4508 4509 return ret
4509 4510
4510 4511 @command('push',
4511 4512 [('f', 'force', None, _('force push')),
4512 4513 ('r', 'rev', [],
4513 4514 _('a changeset intended to be included in the destination'),
4514 4515 _('REV')),
4515 4516 ('B', 'bookmark', [], _("bookmark to push"), _('BOOKMARK')),
4516 4517 ('b', 'branch', [],
4517 4518 _('a specific branch you would like to push'), _('BRANCH')),
4518 4519 ('', 'new-branch', False, _('allow pushing a new branch')),
4519 4520 ('', 'pushvars', [], _('variables that can be sent to server (ADVANCED)')),
4520 4521 ('', 'publish', False, _('push the changeset as public (EXPERIMENTAL)')),
4521 4522 ] + remoteopts,
4522 4523 _('[-f] [-r REV]... [-e CMD] [--remotecmd CMD] [DEST]'),
4523 4524 helpcategory=command.CATEGORY_REMOTE_REPO_MANAGEMENT,
4524 4525 helpbasic=True)
4525 4526 def push(ui, repo, dest=None, **opts):
4526 4527 """push changes to the specified destination
4527 4528
4528 4529 Push changesets from the local repository to the specified
4529 4530 destination.
4530 4531
4531 4532 This operation is symmetrical to pull: it is identical to a pull
4532 4533 in the destination repository from the current one.
4533 4534
4534 4535 By default, push will not allow creation of new heads at the
4535 4536 destination, since multiple heads would make it unclear which head
4536 4537 to use. In this situation, it is recommended to pull and merge
4537 4538 before pushing.
4538 4539
4539 4540 Use --new-branch if you want to allow push to create a new named
4540 4541 branch that is not present at the destination. This allows you to
4541 4542 only create a new branch without forcing other changes.
4542 4543
4543 4544 .. note::
4544 4545
4545 4546 Extra care should be taken with the -f/--force option,
4546 4547 which will push all new heads on all branches, an action which will
4547 4548 almost always cause confusion for collaborators.
4548 4549
4549 4550 If -r/--rev is used, the specified revision and all its ancestors
4550 4551 will be pushed to the remote repository.
4551 4552
4552 4553 If -B/--bookmark is used, the specified bookmarked revision, its
4553 4554 ancestors, and the bookmark will be pushed to the remote
4554 4555 repository. Specifying ``.`` is equivalent to specifying the active
4555 4556 bookmark's name.
4556 4557
4557 4558 Please see :hg:`help urls` for important details about ``ssh://``
4558 4559 URLs. If DESTINATION is omitted, a default path will be used.
4559 4560
4560 4561 .. container:: verbose
4561 4562
4562 4563 The --pushvars option sends strings to the server that become
4563 4564 environment variables prepended with ``HG_USERVAR_``. For example,
4564 4565 ``--pushvars ENABLE_FEATURE=true``, provides the server side hooks with
4565 4566 ``HG_USERVAR_ENABLE_FEATURE=true`` as part of their environment.
4566 4567
4567 4568 pushvars can provide for user-overridable hooks as well as set debug
4568 4569 levels. One example is having a hook that blocks commits containing
4569 4570 conflict markers, but enables the user to override the hook if the file
4570 4571 is using conflict markers for testing purposes or the file format has
4571 4572 strings that look like conflict markers.
4572 4573
4573 4574 By default, servers will ignore `--pushvars`. To enable it add the
4574 4575 following to your configuration file::
4575 4576
4576 4577 [push]
4577 4578 pushvars.server = true
4578 4579
4579 4580 Returns 0 if push was successful, 1 if nothing to push.
4580 4581 """
4581 4582
4582 4583 opts = pycompat.byteskwargs(opts)
4583 4584 if opts.get('bookmark'):
4584 4585 ui.setconfig('bookmarks', 'pushing', opts['bookmark'], 'push')
4585 4586 for b in opts['bookmark']:
4586 4587 # translate -B options to -r so changesets get pushed
4587 4588 b = repo._bookmarks.expandname(b)
4588 4589 if b in repo._bookmarks:
4589 4590 opts.setdefault('rev', []).append(b)
4590 4591 else:
4591 4592 # if we try to push a deleted bookmark, translate it to null
4592 4593 # this lets simultaneous -r, -b options continue working
4593 4594 opts.setdefault('rev', []).append("null")
4594 4595
4595 4596 path = ui.paths.getpath(dest, default=('default-push', 'default'))
4596 4597 if not path:
4597 4598 raise error.Abort(_('default repository not configured!'),
4598 4599 hint=_("see 'hg help config.paths'"))
4599 4600 dest = path.pushloc or path.loc
4600 4601 branches = (path.branch, opts.get('branch') or [])
4601 4602 ui.status(_('pushing to %s\n') % util.hidepassword(dest))
4602 4603 revs, checkout = hg.addbranchrevs(repo, repo, branches, opts.get('rev'))
4603 4604 other = hg.peer(repo, opts, dest)
4604 4605
4605 4606 if revs:
4606 4607 revs = [repo[r].node() for r in scmutil.revrange(repo, revs)]
4607 4608 if not revs:
4608 4609 raise error.Abort(_("specified revisions evaluate to an empty set"),
4609 4610 hint=_("use different revision arguments"))
4610 4611 elif path.pushrev:
4611 4612 # It doesn't make any sense to specify ancestor revisions. So limit
4612 4613 # to DAG heads to make discovery simpler.
4613 4614 expr = revsetlang.formatspec('heads(%r)', path.pushrev)
4614 4615 revs = scmutil.revrange(repo, [expr])
4615 4616 revs = [repo[rev].node() for rev in revs]
4616 4617 if not revs:
4617 4618 raise error.Abort(_('default push revset for path evaluates to an '
4618 4619 'empty set'))
4619 4620
4620 4621 repo._subtoppath = dest
4621 4622 try:
4622 4623 # push subrepos depth-first for coherent ordering
4623 4624 c = repo['.']
4624 4625 subs = c.substate # only repos that are committed
4625 4626 for s in sorted(subs):
4626 4627 result = c.sub(s).push(opts)
4627 4628 if result == 0:
4628 4629 return not result
4629 4630 finally:
4630 4631 del repo._subtoppath
4631 4632
4632 4633 opargs = dict(opts.get('opargs', {})) # copy opargs since we may mutate it
4633 4634 opargs.setdefault('pushvars', []).extend(opts.get('pushvars', []))
4634 4635
4635 4636 pushop = exchange.push(repo, other, opts.get('force'), revs=revs,
4636 4637 newbranch=opts.get('new_branch'),
4637 4638 bookmarks=opts.get('bookmark', ()),
4638 4639 publish=opts.get('publish'),
4639 4640 opargs=opargs)
4640 4641
4641 4642 result = not pushop.cgresult
4642 4643
4643 4644 if pushop.bkresult is not None:
4644 4645 if pushop.bkresult == 2:
4645 4646 result = 2
4646 4647 elif not result and pushop.bkresult:
4647 4648 result = 2
4648 4649
4649 4650 return result
4650 4651
4651 4652 @command('recover', [], helpcategory=command.CATEGORY_MAINTENANCE)
4652 4653 def recover(ui, repo):
4653 4654 """roll back an interrupted transaction
4654 4655
4655 4656 Recover from an interrupted commit or pull.
4656 4657
4657 4658 This command tries to fix the repository status after an
4658 4659 interrupted operation. It should only be necessary when Mercurial
4659 4660 suggests it.
4660 4661
4661 4662 Returns 0 if successful, 1 if nothing to recover or verify fails.
4662 4663 """
4663 4664 if repo.recover():
4664 4665 return hg.verify(repo)
4665 4666 return 1
4666 4667
4667 4668 @command('remove|rm',
4668 4669 [('A', 'after', None, _('record delete for missing files')),
4669 4670 ('f', 'force', None,
4670 4671 _('forget added files, delete modified files')),
4671 4672 ] + subrepoopts + walkopts + dryrunopts,
4672 4673 _('[OPTION]... FILE...'),
4673 4674 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
4674 4675 helpbasic=True, inferrepo=True)
4675 4676 def remove(ui, repo, *pats, **opts):
4676 4677 """remove the specified files on the next commit
4677 4678
4678 4679 Schedule the indicated files for removal from the current branch.
4679 4680
4680 4681 This command schedules the files to be removed at the next commit.
4681 4682 To undo a remove before that, see :hg:`revert`. To undo added
4682 4683 files, see :hg:`forget`.
4683 4684
4684 4685 .. container:: verbose
4685 4686
4686 4687 -A/--after can be used to remove only files that have already
4687 4688 been deleted, -f/--force can be used to force deletion, and -Af
4688 4689 can be used to remove files from the next revision without
4689 4690 deleting them from the working directory.
4690 4691
4691 4692 The following table details the behavior of remove for different
4692 4693 file states (columns) and option combinations (rows). The file
4693 4694 states are Added [A], Clean [C], Modified [M] and Missing [!]
4694 4695 (as reported by :hg:`status`). The actions are Warn, Remove
4695 4696 (from branch) and Delete (from disk):
4696 4697
4697 4698 ========= == == == ==
4698 4699 opt/state A C M !
4699 4700 ========= == == == ==
4700 4701 none W RD W R
4701 4702 -f R RD RD R
4702 4703 -A W W W R
4703 4704 -Af R R R R
4704 4705 ========= == == == ==
4705 4706
4706 4707 .. note::
4707 4708
4708 4709 :hg:`remove` never deletes files in Added [A] state from the
4709 4710 working directory, not even if ``--force`` is specified.
4710 4711
4711 4712 Returns 0 on success, 1 if any warnings encountered.
4712 4713 """
4713 4714
4714 4715 opts = pycompat.byteskwargs(opts)
4715 4716 after, force = opts.get('after'), opts.get('force')
4716 4717 dryrun = opts.get('dry_run')
4717 4718 if not pats and not after:
4718 4719 raise error.Abort(_('no files specified'))
4719 4720
4720 4721 m = scmutil.match(repo[None], pats, opts)
4721 4722 subrepos = opts.get('subrepos')
4722 4723 uipathfn = scmutil.getuipathfn(repo, forcerelativevalue=True)
4723 4724 return cmdutil.remove(ui, repo, m, "", uipathfn, after, force, subrepos,
4724 4725 dryrun=dryrun)
4725 4726
4726 4727 @command('rename|move|mv',
4727 4728 [('A', 'after', None, _('record a rename that has already occurred')),
4728 4729 ('f', 'force', None, _('forcibly copy over an existing managed file')),
4729 4730 ] + walkopts + dryrunopts,
4730 4731 _('[OPTION]... SOURCE... DEST'),
4731 4732 helpcategory=command.CATEGORY_WORKING_DIRECTORY)
4732 4733 def rename(ui, repo, *pats, **opts):
4733 4734 """rename files; equivalent of copy + remove
4734 4735
4735 4736 Mark dest as copies of sources; mark sources for deletion. If dest
4736 4737 is a directory, copies are put in that directory. If dest is a
4737 4738 file, there can only be one source.
4738 4739
4739 4740 By default, this command copies the contents of files as they
4740 4741 exist in the working directory. If invoked with -A/--after, the
4741 4742 operation is recorded, but no copying is performed.
4742 4743
4743 4744 This command takes effect at the next commit. To undo a rename
4744 4745 before that, see :hg:`revert`.
4745 4746
4746 4747 Returns 0 on success, 1 if errors are encountered.
4747 4748 """
4748 4749 opts = pycompat.byteskwargs(opts)
4749 4750 with repo.wlock(False):
4750 4751 return cmdutil.copy(ui, repo, pats, opts, rename=True)
4751 4752
4752 4753 @command('resolve',
4753 4754 [('a', 'all', None, _('select all unresolved files')),
4754 4755 ('l', 'list', None, _('list state of files needing merge')),
4755 4756 ('m', 'mark', None, _('mark files as resolved')),
4756 4757 ('u', 'unmark', None, _('mark files as unresolved')),
4757 4758 ('n', 'no-status', None, _('hide status prefix')),
4758 4759 ('', 're-merge', None, _('re-merge files'))]
4759 4760 + mergetoolopts + walkopts + formatteropts,
4760 4761 _('[OPTION]... [FILE]...'),
4761 4762 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
4762 4763 inferrepo=True)
4763 4764 def resolve(ui, repo, *pats, **opts):
4764 4765 """redo merges or set/view the merge status of files
4765 4766
4766 4767 Merges with unresolved conflicts are often the result of
4767 4768 non-interactive merging using the ``internal:merge`` configuration
4768 4769 setting, or a command-line merge tool like ``diff3``. The resolve
4769 4770 command is used to manage the files involved in a merge, after
4770 4771 :hg:`merge` has been run, and before :hg:`commit` is run (i.e. the
4771 4772 working directory must have two parents). See :hg:`help
4772 4773 merge-tools` for information on configuring merge tools.
4773 4774
4774 4775 The resolve command can be used in the following ways:
4775 4776
4776 4777 - :hg:`resolve [--re-merge] [--tool TOOL] FILE...`: attempt to re-merge
4777 4778 the specified files, discarding any previous merge attempts. Re-merging
4778 4779 is not performed for files already marked as resolved. Use ``--all/-a``
4779 4780 to select all unresolved files. ``--tool`` can be used to specify
4780 4781 the merge tool used for the given files. It overrides the HGMERGE
4781 4782 environment variable and your configuration files. Previous file
4782 4783 contents are saved with a ``.orig`` suffix.
4783 4784
4784 4785 - :hg:`resolve -m [FILE]`: mark a file as having been resolved
4785 4786 (e.g. after having manually fixed-up the files). The default is
4786 4787 to mark all unresolved files.
4787 4788
4788 4789 - :hg:`resolve -u [FILE]...`: mark a file as unresolved. The
4789 4790 default is to mark all resolved files.
4790 4791
4791 4792 - :hg:`resolve -l`: list files which had or still have conflicts.
4792 4793 In the printed list, ``U`` = unresolved and ``R`` = resolved.
4793 4794 You can use ``set:unresolved()`` or ``set:resolved()`` to filter
4794 4795 the list. See :hg:`help filesets` for details.
4795 4796
4796 4797 .. note::
4797 4798
4798 4799 Mercurial will not let you commit files with unresolved merge
4799 4800 conflicts. You must use :hg:`resolve -m ...` before you can
4800 4801 commit after a conflicting merge.
4801 4802
4802 4803 .. container:: verbose
4803 4804
4804 4805 Template:
4805 4806
4806 4807 The following keywords are supported in addition to the common template
4807 4808 keywords and functions. See also :hg:`help templates`.
4808 4809
4809 4810 :mergestatus: String. Character denoting merge conflicts, ``U`` or ``R``.
4810 4811 :path: String. Repository-absolute path of the file.
4811 4812
4812 4813 Returns 0 on success, 1 if any files fail a resolve attempt.
4813 4814 """
4814 4815
4815 4816 opts = pycompat.byteskwargs(opts)
4816 4817 confirm = ui.configbool('commands', 'resolve.confirm')
4817 4818 flaglist = 'all mark unmark list no_status re_merge'.split()
4818 4819 all, mark, unmark, show, nostatus, remerge = \
4819 4820 [opts.get(o) for o in flaglist]
4820 4821
4821 4822 actioncount = len(list(filter(None, [show, mark, unmark, remerge])))
4822 4823 if actioncount > 1:
4823 4824 raise error.Abort(_("too many actions specified"))
4824 4825 elif (actioncount == 0
4825 4826 and ui.configbool('commands', 'resolve.explicit-re-merge')):
4826 4827 hint = _('use --mark, --unmark, --list or --re-merge')
4827 4828 raise error.Abort(_('no action specified'), hint=hint)
4828 4829 if pats and all:
4829 4830 raise error.Abort(_("can't specify --all and patterns"))
4830 4831 if not (all or pats or show or mark or unmark):
4831 4832 raise error.Abort(_('no files or directories specified'),
4832 4833 hint=('use --all to re-merge all unresolved files'))
4833 4834
4834 4835 if confirm:
4835 4836 if all:
4836 4837 if ui.promptchoice(_(b're-merge all unresolved files (yn)?'
4837 4838 b'$$ &Yes $$ &No')):
4838 4839 raise error.Abort(_('user quit'))
4839 4840 if mark and not pats:
4840 4841 if ui.promptchoice(_(b'mark all unresolved files as resolved (yn)?'
4841 4842 b'$$ &Yes $$ &No')):
4842 4843 raise error.Abort(_('user quit'))
4843 4844 if unmark and not pats:
4844 4845 if ui.promptchoice(_(b'mark all resolved files as unresolved (yn)?'
4845 4846 b'$$ &Yes $$ &No')):
4846 4847 raise error.Abort(_('user quit'))
4847 4848
4848 4849 uipathfn = scmutil.getuipathfn(repo)
4849 4850
4850 4851 if show:
4851 4852 ui.pager('resolve')
4852 4853 fm = ui.formatter('resolve', opts)
4853 4854 ms = mergemod.mergestate.read(repo)
4854 4855 wctx = repo[None]
4855 4856 m = scmutil.match(wctx, pats, opts)
4856 4857
4857 4858 # Labels and keys based on merge state. Unresolved path conflicts show
4858 4859 # as 'P'. Resolved path conflicts show as 'R', the same as normal
4859 4860 # resolved conflicts.
4860 4861 mergestateinfo = {
4861 4862 mergemod.MERGE_RECORD_UNRESOLVED: ('resolve.unresolved', 'U'),
4862 4863 mergemod.MERGE_RECORD_RESOLVED: ('resolve.resolved', 'R'),
4863 4864 mergemod.MERGE_RECORD_UNRESOLVED_PATH: ('resolve.unresolved', 'P'),
4864 4865 mergemod.MERGE_RECORD_RESOLVED_PATH: ('resolve.resolved', 'R'),
4865 4866 mergemod.MERGE_RECORD_DRIVER_RESOLVED: ('resolve.driverresolved',
4866 4867 'D'),
4867 4868 }
4868 4869
4869 4870 for f in ms:
4870 4871 if not m(f):
4871 4872 continue
4872 4873
4873 4874 label, key = mergestateinfo[ms[f]]
4874 4875 fm.startitem()
4875 4876 fm.context(ctx=wctx)
4876 4877 fm.condwrite(not nostatus, 'mergestatus', '%s ', key, label=label)
4877 4878 fm.data(path=f)
4878 4879 fm.plain('%s\n' % uipathfn(f), label=label)
4879 4880 fm.end()
4880 4881 return 0
4881 4882
4882 4883 with repo.wlock():
4883 4884 ms = mergemod.mergestate.read(repo)
4884 4885
4885 4886 if not (ms.active() or repo.dirstate.p2() != nullid):
4886 4887 raise error.Abort(
4887 4888 _('resolve command not applicable when not merging'))
4888 4889
4889 4890 wctx = repo[None]
4890 4891
4891 4892 if (ms.mergedriver
4892 4893 and ms.mdstate() == mergemod.MERGE_DRIVER_STATE_UNMARKED):
4893 4894 proceed = mergemod.driverpreprocess(repo, ms, wctx)
4894 4895 ms.commit()
4895 4896 # allow mark and unmark to go through
4896 4897 if not mark and not unmark and not proceed:
4897 4898 return 1
4898 4899
4899 4900 m = scmutil.match(wctx, pats, opts)
4900 4901 ret = 0
4901 4902 didwork = False
4902 4903 runconclude = False
4903 4904
4904 4905 tocomplete = []
4905 4906 hasconflictmarkers = []
4906 4907 if mark:
4907 4908 markcheck = ui.config('commands', 'resolve.mark-check')
4908 4909 if markcheck not in ['warn', 'abort']:
4909 4910 # Treat all invalid / unrecognized values as 'none'.
4910 4911 markcheck = False
4911 4912 for f in ms:
4912 4913 if not m(f):
4913 4914 continue
4914 4915
4915 4916 didwork = True
4916 4917
4917 4918 # don't let driver-resolved files be marked, and run the conclude
4918 4919 # step if asked to resolve
4919 4920 if ms[f] == mergemod.MERGE_RECORD_DRIVER_RESOLVED:
4920 4921 exact = m.exact(f)
4921 4922 if mark:
4922 4923 if exact:
4923 4924 ui.warn(_('not marking %s as it is driver-resolved\n')
4924 4925 % f)
4925 4926 elif unmark:
4926 4927 if exact:
4927 4928 ui.warn(_('not unmarking %s as it is driver-resolved\n')
4928 4929 % f)
4929 4930 else:
4930 4931 runconclude = True
4931 4932 continue
4932 4933
4933 4934 # path conflicts must be resolved manually
4934 4935 if ms[f] in (mergemod.MERGE_RECORD_UNRESOLVED_PATH,
4935 4936 mergemod.MERGE_RECORD_RESOLVED_PATH):
4936 4937 if mark:
4937 4938 ms.mark(f, mergemod.MERGE_RECORD_RESOLVED_PATH)
4938 4939 elif unmark:
4939 4940 ms.mark(f, mergemod.MERGE_RECORD_UNRESOLVED_PATH)
4940 4941 elif ms[f] == mergemod.MERGE_RECORD_UNRESOLVED_PATH:
4941 4942 ui.warn(_('%s: path conflict must be resolved manually\n')
4942 4943 % f)
4943 4944 continue
4944 4945
4945 4946 if mark:
4946 4947 if markcheck:
4947 4948 fdata = repo.wvfs.tryread(f)
4948 4949 if filemerge.hasconflictmarkers(fdata) and \
4949 4950 ms[f] != mergemod.MERGE_RECORD_RESOLVED:
4950 4951 hasconflictmarkers.append(f)
4951 4952 ms.mark(f, mergemod.MERGE_RECORD_RESOLVED)
4952 4953 elif unmark:
4953 4954 ms.mark(f, mergemod.MERGE_RECORD_UNRESOLVED)
4954 4955 else:
4955 4956 # backup pre-resolve (merge uses .orig for its own purposes)
4956 4957 a = repo.wjoin(f)
4957 4958 try:
4958 4959 util.copyfile(a, a + ".resolve")
4959 4960 except (IOError, OSError) as inst:
4960 4961 if inst.errno != errno.ENOENT:
4961 4962 raise
4962 4963
4963 4964 try:
4964 4965 # preresolve file
4965 4966 overrides = {('ui', 'forcemerge'): opts.get('tool', '')}
4966 4967 with ui.configoverride(overrides, 'resolve'):
4967 4968 complete, r = ms.preresolve(f, wctx)
4968 4969 if not complete:
4969 4970 tocomplete.append(f)
4970 4971 elif r:
4971 4972 ret = 1
4972 4973 finally:
4973 4974 ms.commit()
4974 4975
4975 4976 # replace filemerge's .orig file with our resolve file, but only
4976 4977 # for merges that are complete
4977 4978 if complete:
4978 4979 try:
4979 4980 util.rename(a + ".resolve",
4980 4981 scmutil.backuppath(ui, repo, f))
4981 4982 except OSError as inst:
4982 4983 if inst.errno != errno.ENOENT:
4983 4984 raise
4984 4985
4985 4986 if hasconflictmarkers:
4986 4987 ui.warn(_('warning: the following files still have conflict '
4987 4988 'markers:\n ') + '\n '.join(hasconflictmarkers) + '\n')
4988 4989 if markcheck == 'abort' and not all and not pats:
4989 4990 raise error.Abort(_('conflict markers detected'),
4990 4991 hint=_('use --all to mark anyway'))
4991 4992
4992 4993 for f in tocomplete:
4993 4994 try:
4994 4995 # resolve file
4995 4996 overrides = {('ui', 'forcemerge'): opts.get('tool', '')}
4996 4997 with ui.configoverride(overrides, 'resolve'):
4997 4998 r = ms.resolve(f, wctx)
4998 4999 if r:
4999 5000 ret = 1
5000 5001 finally:
5001 5002 ms.commit()
5002 5003
5003 5004 # replace filemerge's .orig file with our resolve file
5004 5005 a = repo.wjoin(f)
5005 5006 try:
5006 5007 util.rename(a + ".resolve", scmutil.backuppath(ui, repo, f))
5007 5008 except OSError as inst:
5008 5009 if inst.errno != errno.ENOENT:
5009 5010 raise
5010 5011
5011 5012 ms.commit()
5012 5013 ms.recordactions()
5013 5014
5014 5015 if not didwork and pats:
5015 5016 hint = None
5016 5017 if not any([p for p in pats if p.find(':') >= 0]):
5017 5018 pats = ['path:%s' % p for p in pats]
5018 5019 m = scmutil.match(wctx, pats, opts)
5019 5020 for f in ms:
5020 5021 if not m(f):
5021 5022 continue
5022 5023 def flag(o):
5023 5024 if o == 're_merge':
5024 5025 return '--re-merge '
5025 5026 return '-%s ' % o[0:1]
5026 5027 flags = ''.join([flag(o) for o in flaglist if opts.get(o)])
5027 5028 hint = _("(try: hg resolve %s%s)\n") % (
5028 5029 flags,
5029 5030 ' '.join(pats))
5030 5031 break
5031 5032 ui.warn(_("arguments do not match paths that need resolving\n"))
5032 5033 if hint:
5033 5034 ui.warn(hint)
5034 5035 elif ms.mergedriver and ms.mdstate() != 's':
5035 5036 # run conclude step when either a driver-resolved file is requested
5036 5037 # or there are no driver-resolved files
5037 5038 # we can't use 'ret' to determine whether any files are unresolved
5038 5039 # because we might not have tried to resolve some
5039 5040 if ((runconclude or not list(ms.driverresolved()))
5040 5041 and not list(ms.unresolved())):
5041 5042 proceed = mergemod.driverconclude(repo, ms, wctx)
5042 5043 ms.commit()
5043 5044 if not proceed:
5044 5045 return 1
5045 5046
5046 5047 # Nudge users into finishing an unfinished operation
5047 5048 unresolvedf = list(ms.unresolved())
5048 5049 driverresolvedf = list(ms.driverresolved())
5049 5050 if not unresolvedf and not driverresolvedf:
5050 5051 ui.status(_('(no more unresolved files)\n'))
5051 5052 cmdutil.checkafterresolved(repo)
5052 5053 elif not unresolvedf:
5053 5054 ui.status(_('(no more unresolved files -- '
5054 5055 'run "hg resolve --all" to conclude)\n'))
5055 5056
5056 5057 return ret
5057 5058
5058 5059 @command('revert',
5059 5060 [('a', 'all', None, _('revert all changes when no arguments given')),
5060 5061 ('d', 'date', '', _('tipmost revision matching date'), _('DATE')),
5061 5062 ('r', 'rev', '', _('revert to the specified revision'), _('REV')),
5062 5063 ('C', 'no-backup', None, _('do not save backup copies of files')),
5063 5064 ('i', 'interactive', None, _('interactively select the changes')),
5064 5065 ] + walkopts + dryrunopts,
5065 5066 _('[OPTION]... [-r REV] [NAME]...'),
5066 5067 helpcategory=command.CATEGORY_WORKING_DIRECTORY)
5067 5068 def revert(ui, repo, *pats, **opts):
5068 5069 """restore files to their checkout state
5069 5070
5070 5071 .. note::
5071 5072
5072 5073 To check out earlier revisions, you should use :hg:`update REV`.
5073 5074 To cancel an uncommitted merge (and lose your changes),
5074 5075 use :hg:`merge --abort`.
5075 5076
5076 5077 With no revision specified, revert the specified files or directories
5077 5078 to the contents they had in the parent of the working directory.
5078 5079 This restores the contents of files to an unmodified
5079 5080 state and unschedules adds, removes, copies, and renames. If the
5080 5081 working directory has two parents, you must explicitly specify a
5081 5082 revision.
5082 5083
5083 5084 Using the -r/--rev or -d/--date options, revert the given files or
5084 5085 directories to their states as of a specific revision. Because
5085 5086 revert does not change the working directory parents, this will
5086 5087 cause these files to appear modified. This can be helpful to "back
5087 5088 out" some or all of an earlier change. See :hg:`backout` for a
5088 5089 related method.
5089 5090
5090 5091 Modified files are saved with a .orig suffix before reverting.
5091 5092 To disable these backups, use --no-backup. It is possible to store
5092 5093 the backup files in a custom directory relative to the root of the
5093 5094 repository by setting the ``ui.origbackuppath`` configuration
5094 5095 option.
5095 5096
5096 5097 See :hg:`help dates` for a list of formats valid for -d/--date.
5097 5098
5098 5099 See :hg:`help backout` for a way to reverse the effect of an
5099 5100 earlier changeset.
5100 5101
5101 5102 Returns 0 on success.
5102 5103 """
5103 5104
5104 5105 opts = pycompat.byteskwargs(opts)
5105 5106 if opts.get("date"):
5106 5107 if opts.get("rev"):
5107 5108 raise error.Abort(_("you can't specify a revision and a date"))
5108 5109 opts["rev"] = cmdutil.finddate(ui, repo, opts["date"])
5109 5110
5110 5111 parent, p2 = repo.dirstate.parents()
5111 5112 if not opts.get('rev') and p2 != nullid:
5112 5113 # revert after merge is a trap for new users (issue2915)
5113 5114 raise error.Abort(_('uncommitted merge with no revision specified'),
5114 5115 hint=_("use 'hg update' or see 'hg help revert'"))
5115 5116
5116 5117 rev = opts.get('rev')
5117 5118 if rev:
5118 5119 repo = scmutil.unhidehashlikerevs(repo, [rev], 'nowarn')
5119 5120 ctx = scmutil.revsingle(repo, rev)
5120 5121
5121 5122 if (not (pats or opts.get('include') or opts.get('exclude') or
5122 5123 opts.get('all') or opts.get('interactive'))):
5123 5124 msg = _("no files or directories specified")
5124 5125 if p2 != nullid:
5125 5126 hint = _("uncommitted merge, use --all to discard all changes,"
5126 5127 " or 'hg update -C .' to abort the merge")
5127 5128 raise error.Abort(msg, hint=hint)
5128 5129 dirty = any(repo.status())
5129 5130 node = ctx.node()
5130 5131 if node != parent:
5131 5132 if dirty:
5132 5133 hint = _("uncommitted changes, use --all to discard all"
5133 5134 " changes, or 'hg update %d' to update") % ctx.rev()
5134 5135 else:
5135 5136 hint = _("use --all to revert all files,"
5136 5137 " or 'hg update %d' to update") % ctx.rev()
5137 5138 elif dirty:
5138 5139 hint = _("uncommitted changes, use --all to discard all changes")
5139 5140 else:
5140 5141 hint = _("use --all to revert all files")
5141 5142 raise error.Abort(msg, hint=hint)
5142 5143
5143 5144 return cmdutil.revert(ui, repo, ctx, (parent, p2), *pats,
5144 5145 **pycompat.strkwargs(opts))
5145 5146
5146 5147 @command(
5147 5148 'rollback',
5148 5149 dryrunopts + [('f', 'force', False, _('ignore safety measures'))],
5149 5150 helpcategory=command.CATEGORY_MAINTENANCE)
5150 5151 def rollback(ui, repo, **opts):
5151 5152 """roll back the last transaction (DANGEROUS) (DEPRECATED)
5152 5153
5153 5154 Please use :hg:`commit --amend` instead of rollback to correct
5154 5155 mistakes in the last commit.
5155 5156
5156 5157 This command should be used with care. There is only one level of
5157 5158 rollback, and there is no way to undo a rollback. It will also
5158 5159 restore the dirstate at the time of the last transaction, losing
5159 5160 any dirstate changes since that time. This command does not alter
5160 5161 the working directory.
5161 5162
5162 5163 Transactions are used to encapsulate the effects of all commands
5163 5164 that create new changesets or propagate existing changesets into a
5164 5165 repository.
5165 5166
5166 5167 .. container:: verbose
5167 5168
5168 5169 For example, the following commands are transactional, and their
5169 5170 effects can be rolled back:
5170 5171
5171 5172 - commit
5172 5173 - import
5173 5174 - pull
5174 5175 - push (with this repository as the destination)
5175 5176 - unbundle
5176 5177
5177 5178 To avoid permanent data loss, rollback will refuse to rollback a
5178 5179 commit transaction if it isn't checked out. Use --force to
5179 5180 override this protection.
5180 5181
5181 5182 The rollback command can be entirely disabled by setting the
5182 5183 ``ui.rollback`` configuration setting to false. If you're here
5183 5184 because you want to use rollback and it's disabled, you can
5184 5185 re-enable the command by setting ``ui.rollback`` to true.
5185 5186
5186 5187 This command is not intended for use on public repositories. Once
5187 5188 changes are visible for pull by other users, rolling a transaction
5188 5189 back locally is ineffective (someone else may already have pulled
5189 5190 the changes). Furthermore, a race is possible with readers of the
5190 5191 repository; for example an in-progress pull from the repository
5191 5192 may fail if a rollback is performed.
5192 5193
5193 5194 Returns 0 on success, 1 if no rollback data is available.
5194 5195 """
5195 5196 if not ui.configbool('ui', 'rollback'):
5196 5197 raise error.Abort(_('rollback is disabled because it is unsafe'),
5197 5198 hint=('see `hg help -v rollback` for information'))
5198 5199 return repo.rollback(dryrun=opts.get(r'dry_run'),
5199 5200 force=opts.get(r'force'))
5200 5201
5201 5202 @command(
5202 5203 'root', [], intents={INTENT_READONLY},
5203 5204 helpcategory=command.CATEGORY_WORKING_DIRECTORY)
5204 5205 def root(ui, repo):
5205 5206 """print the root (top) of the current working directory
5206 5207
5207 5208 Print the root directory of the current repository.
5208 5209
5209 5210 Returns 0 on success.
5210 5211 """
5211 5212 ui.write(repo.root + "\n")
5212 5213
5213 5214 @command('serve',
5214 5215 [('A', 'accesslog', '', _('name of access log file to write to'),
5215 5216 _('FILE')),
5216 5217 ('d', 'daemon', None, _('run server in background')),
5217 5218 ('', 'daemon-postexec', [], _('used internally by daemon mode')),
5218 5219 ('E', 'errorlog', '', _('name of error log file to write to'), _('FILE')),
5219 5220 # use string type, then we can check if something was passed
5220 5221 ('p', 'port', '', _('port to listen on (default: 8000)'), _('PORT')),
5221 5222 ('a', 'address', '', _('address to listen on (default: all interfaces)'),
5222 5223 _('ADDR')),
5223 5224 ('', 'prefix', '', _('prefix path to serve from (default: server root)'),
5224 5225 _('PREFIX')),
5225 5226 ('n', 'name', '',
5226 5227 _('name to show in web pages (default: working directory)'), _('NAME')),
5227 5228 ('', 'web-conf', '',
5228 5229 _("name of the hgweb config file (see 'hg help hgweb')"), _('FILE')),
5229 5230 ('', 'webdir-conf', '', _('name of the hgweb config file (DEPRECATED)'),
5230 5231 _('FILE')),
5231 5232 ('', 'pid-file', '', _('name of file to write process ID to'), _('FILE')),
5232 5233 ('', 'stdio', None, _('for remote clients (ADVANCED)')),
5233 5234 ('', 'cmdserver', '', _('for remote clients (ADVANCED)'), _('MODE')),
5234 5235 ('t', 'templates', '', _('web templates to use'), _('TEMPLATE')),
5235 5236 ('', 'style', '', _('template style to use'), _('STYLE')),
5236 5237 ('6', 'ipv6', None, _('use IPv6 in addition to IPv4')),
5237 5238 ('', 'certificate', '', _('SSL certificate file'), _('FILE')),
5238 5239 ('', 'print-url', None, _('start and print only the URL'))]
5239 5240 + subrepoopts,
5240 5241 _('[OPTION]...'),
5241 5242 helpcategory=command.CATEGORY_REMOTE_REPO_MANAGEMENT,
5242 5243 helpbasic=True, optionalrepo=True)
5243 5244 def serve(ui, repo, **opts):
5244 5245 """start stand-alone webserver
5245 5246
5246 5247 Start a local HTTP repository browser and pull server. You can use
5247 5248 this for ad-hoc sharing and browsing of repositories. It is
5248 5249 recommended to use a real web server to serve a repository for
5249 5250 longer periods of time.
5250 5251
5251 5252 Please note that the server does not implement access control.
5252 5253 This means that, by default, anybody can read from the server and
5253 5254 nobody can write to it by default. Set the ``web.allow-push``
5254 5255 option to ``*`` to allow everybody to push to the server. You
5255 5256 should use a real web server if you need to authenticate users.
5256 5257
5257 5258 By default, the server logs accesses to stdout and errors to
5258 5259 stderr. Use the -A/--accesslog and -E/--errorlog options to log to
5259 5260 files.
5260 5261
5261 5262 To have the server choose a free port number to listen on, specify
5262 5263 a port number of 0; in this case, the server will print the port
5263 5264 number it uses.
5264 5265
5265 5266 Returns 0 on success.
5266 5267 """
5267 5268
5268 5269 opts = pycompat.byteskwargs(opts)
5269 5270 if opts["stdio"] and opts["cmdserver"]:
5270 5271 raise error.Abort(_("cannot use --stdio with --cmdserver"))
5271 5272 if opts["print_url"] and ui.verbose:
5272 5273 raise error.Abort(_("cannot use --print-url with --verbose"))
5273 5274
5274 5275 if opts["stdio"]:
5275 5276 if repo is None:
5276 5277 raise error.RepoError(_("there is no Mercurial repository here"
5277 5278 " (.hg not found)"))
5278 5279 s = wireprotoserver.sshserver(ui, repo)
5279 5280 s.serve_forever()
5280 5281
5281 5282 service = server.createservice(ui, repo, opts)
5282 5283 return server.runservice(opts, initfn=service.init, runfn=service.run)
5283 5284
5284 5285 _NOTTERSE = 'nothing'
5285 5286
5286 5287 @command('status|st',
5287 5288 [('A', 'all', None, _('show status of all files')),
5288 5289 ('m', 'modified', None, _('show only modified files')),
5289 5290 ('a', 'added', None, _('show only added files')),
5290 5291 ('r', 'removed', None, _('show only removed files')),
5291 5292 ('d', 'deleted', None, _('show only deleted (but tracked) files')),
5292 5293 ('c', 'clean', None, _('show only files without changes')),
5293 5294 ('u', 'unknown', None, _('show only unknown (not tracked) files')),
5294 5295 ('i', 'ignored', None, _('show only ignored files')),
5295 5296 ('n', 'no-status', None, _('hide status prefix')),
5296 5297 ('t', 'terse', _NOTTERSE, _('show the terse output (EXPERIMENTAL)')),
5297 5298 ('C', 'copies', None, _('show source of copied files')),
5298 5299 ('0', 'print0', None, _('end filenames with NUL, for use with xargs')),
5299 5300 ('', 'rev', [], _('show difference from revision'), _('REV')),
5300 5301 ('', 'change', '', _('list the changed files of a revision'), _('REV')),
5301 5302 ] + walkopts + subrepoopts + formatteropts,
5302 5303 _('[OPTION]... [FILE]...'),
5303 5304 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
5304 5305 helpbasic=True, inferrepo=True,
5305 5306 intents={INTENT_READONLY})
5306 5307 def status(ui, repo, *pats, **opts):
5307 5308 """show changed files in the working directory
5308 5309
5309 5310 Show status of files in the repository. If names are given, only
5310 5311 files that match are shown. Files that are clean or ignored or
5311 5312 the source of a copy/move operation, are not listed unless
5312 5313 -c/--clean, -i/--ignored, -C/--copies or -A/--all are given.
5313 5314 Unless options described with "show only ..." are given, the
5314 5315 options -mardu are used.
5315 5316
5316 5317 Option -q/--quiet hides untracked (unknown and ignored) files
5317 5318 unless explicitly requested with -u/--unknown or -i/--ignored.
5318 5319
5319 5320 .. note::
5320 5321
5321 5322 :hg:`status` may appear to disagree with diff if permissions have
5322 5323 changed or a merge has occurred. The standard diff format does
5323 5324 not report permission changes and diff only reports changes
5324 5325 relative to one merge parent.
5325 5326
5326 5327 If one revision is given, it is used as the base revision.
5327 5328 If two revisions are given, the differences between them are
5328 5329 shown. The --change option can also be used as a shortcut to list
5329 5330 the changed files of a revision from its first parent.
5330 5331
5331 5332 The codes used to show the status of files are::
5332 5333
5333 5334 M = modified
5334 5335 A = added
5335 5336 R = removed
5336 5337 C = clean
5337 5338 ! = missing (deleted by non-hg command, but still tracked)
5338 5339 ? = not tracked
5339 5340 I = ignored
5340 5341 = origin of the previous file (with --copies)
5341 5342
5342 5343 .. container:: verbose
5343 5344
5344 5345 The -t/--terse option abbreviates the output by showing only the directory
5345 5346 name if all the files in it share the same status. The option takes an
5346 5347 argument indicating the statuses to abbreviate: 'm' for 'modified', 'a'
5347 5348 for 'added', 'r' for 'removed', 'd' for 'deleted', 'u' for 'unknown', 'i'
5348 5349 for 'ignored' and 'c' for clean.
5349 5350
5350 5351 It abbreviates only those statuses which are passed. Note that clean and
5351 5352 ignored files are not displayed with '--terse ic' unless the -c/--clean
5352 5353 and -i/--ignored options are also used.
5353 5354
5354 5355 The -v/--verbose option shows information when the repository is in an
5355 5356 unfinished merge, shelve, rebase state etc. You can have this behavior
5356 5357 turned on by default by enabling the ``commands.status.verbose`` option.
5357 5358
5358 5359 You can skip displaying some of these states by setting
5359 5360 ``commands.status.skipstates`` to one or more of: 'bisect', 'graft',
5360 5361 'histedit', 'merge', 'rebase', or 'unshelve'.
5361 5362
5362 5363 Template:
5363 5364
5364 5365 The following keywords are supported in addition to the common template
5365 5366 keywords and functions. See also :hg:`help templates`.
5366 5367
5367 5368 :path: String. Repository-absolute path of the file.
5368 5369 :source: String. Repository-absolute path of the file originated from.
5369 5370 Available if ``--copies`` is specified.
5370 5371 :status: String. Character denoting file's status.
5371 5372
5372 5373 Examples:
5373 5374
5374 5375 - show changes in the working directory relative to a
5375 5376 changeset::
5376 5377
5377 5378 hg status --rev 9353
5378 5379
5379 5380 - show changes in the working directory relative to the
5380 5381 current directory (see :hg:`help patterns` for more information)::
5381 5382
5382 5383 hg status re:
5383 5384
5384 5385 - show all changes including copies in an existing changeset::
5385 5386
5386 5387 hg status --copies --change 9353
5387 5388
5388 5389 - get a NUL separated list of added files, suitable for xargs::
5389 5390
5390 5391 hg status -an0
5391 5392
5392 5393 - show more information about the repository status, abbreviating
5393 5394 added, removed, modified, deleted, and untracked paths::
5394 5395
5395 5396 hg status -v -t mardu
5396 5397
5397 5398 Returns 0 on success.
5398 5399
5399 5400 """
5400 5401
5401 5402 opts = pycompat.byteskwargs(opts)
5402 5403 revs = opts.get('rev')
5403 5404 change = opts.get('change')
5404 5405 terse = opts.get('terse')
5405 5406 if terse is _NOTTERSE:
5406 5407 if revs:
5407 5408 terse = ''
5408 5409 else:
5409 5410 terse = ui.config('commands', 'status.terse')
5410 5411
5411 5412 if revs and change:
5412 5413 msg = _('cannot specify --rev and --change at the same time')
5413 5414 raise error.Abort(msg)
5414 5415 elif revs and terse:
5415 5416 msg = _('cannot use --terse with --rev')
5416 5417 raise error.Abort(msg)
5417 5418 elif change:
5418 5419 repo = scmutil.unhidehashlikerevs(repo, [change], 'nowarn')
5419 5420 ctx2 = scmutil.revsingle(repo, change, None)
5420 5421 ctx1 = ctx2.p1()
5421 5422 else:
5422 5423 repo = scmutil.unhidehashlikerevs(repo, revs, 'nowarn')
5423 5424 ctx1, ctx2 = scmutil.revpair(repo, revs)
5424 5425
5425 5426 forcerelativevalue = None
5426 5427 if ui.hasconfig('commands', 'status.relative'):
5427 5428 forcerelativevalue = ui.configbool('commands', 'status.relative')
5428 5429 uipathfn = scmutil.getuipathfn(repo, legacyrelativevalue=bool(pats),
5429 5430 forcerelativevalue=forcerelativevalue)
5430 5431
5431 5432 if opts.get('print0'):
5432 5433 end = '\0'
5433 5434 else:
5434 5435 end = '\n'
5435 5436 copy = {}
5436 5437 states = 'modified added removed deleted unknown ignored clean'.split()
5437 5438 show = [k for k in states if opts.get(k)]
5438 5439 if opts.get('all'):
5439 5440 show += ui.quiet and (states[:4] + ['clean']) or states
5440 5441
5441 5442 if not show:
5442 5443 if ui.quiet:
5443 5444 show = states[:4]
5444 5445 else:
5445 5446 show = states[:5]
5446 5447
5447 5448 m = scmutil.match(ctx2, pats, opts)
5448 5449 if terse:
5449 5450 # we need to compute clean and unknown to terse
5450 5451 stat = repo.status(ctx1.node(), ctx2.node(), m,
5451 5452 'ignored' in show or 'i' in terse,
5452 5453 clean=True, unknown=True,
5453 5454 listsubrepos=opts.get('subrepos'))
5454 5455
5455 5456 stat = cmdutil.tersedir(stat, terse)
5456 5457 else:
5457 5458 stat = repo.status(ctx1.node(), ctx2.node(), m,
5458 5459 'ignored' in show, 'clean' in show,
5459 5460 'unknown' in show, opts.get('subrepos'))
5460 5461
5461 5462 changestates = zip(states, pycompat.iterbytestr('MAR!?IC'), stat)
5462 5463
5463 5464 if (opts.get('all') or opts.get('copies')
5464 5465 or ui.configbool('ui', 'statuscopies')) and not opts.get('no_status'):
5465 5466 copy = copies.pathcopies(ctx1, ctx2, m)
5466 5467
5467 5468 ui.pager('status')
5468 5469 fm = ui.formatter('status', opts)
5469 5470 fmt = '%s' + end
5470 5471 showchar = not opts.get('no_status')
5471 5472
5472 5473 for state, char, files in changestates:
5473 5474 if state in show:
5474 5475 label = 'status.' + state
5475 5476 for f in files:
5476 5477 fm.startitem()
5477 5478 fm.context(ctx=ctx2)
5478 5479 fm.data(path=f)
5479 5480 fm.condwrite(showchar, 'status', '%s ', char, label=label)
5480 5481 fm.plain(fmt % uipathfn(f), label=label)
5481 5482 if f in copy:
5482 5483 fm.data(source=copy[f])
5483 5484 fm.plain((' %s' + end) % uipathfn(copy[f]),
5484 5485 label='status.copied')
5485 5486
5486 5487 if ((ui.verbose or ui.configbool('commands', 'status.verbose'))
5487 5488 and not ui.plain()):
5488 5489 cmdutil.morestatus(repo, fm)
5489 5490 fm.end()
5490 5491
5491 5492 @command('summary|sum',
5492 5493 [('', 'remote', None, _('check for push and pull'))],
5493 5494 '[--remote]',
5494 5495 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
5495 5496 helpbasic=True,
5496 5497 intents={INTENT_READONLY})
5497 5498 def summary(ui, repo, **opts):
5498 5499 """summarize working directory state
5499 5500
5500 5501 This generates a brief summary of the working directory state,
5501 5502 including parents, branch, commit status, phase and available updates.
5502 5503
5503 5504 With the --remote option, this will check the default paths for
5504 5505 incoming and outgoing changes. This can be time-consuming.
5505 5506
5506 5507 Returns 0 on success.
5507 5508 """
5508 5509
5509 5510 opts = pycompat.byteskwargs(opts)
5510 5511 ui.pager('summary')
5511 5512 ctx = repo[None]
5512 5513 parents = ctx.parents()
5513 5514 pnode = parents[0].node()
5514 5515 marks = []
5515 5516
5516 5517 try:
5517 5518 ms = mergemod.mergestate.read(repo)
5518 5519 except error.UnsupportedMergeRecords as e:
5519 5520 s = ' '.join(e.recordtypes)
5520 5521 ui.warn(
5521 5522 _('warning: merge state has unsupported record types: %s\n') % s)
5522 5523 unresolved = []
5523 5524 else:
5524 5525 unresolved = list(ms.unresolved())
5525 5526
5526 5527 for p in parents:
5527 5528 # label with log.changeset (instead of log.parent) since this
5528 5529 # shows a working directory parent *changeset*:
5529 5530 # i18n: column positioning for "hg summary"
5530 5531 ui.write(_('parent: %d:%s ') % (p.rev(), p),
5531 5532 label=logcmdutil.changesetlabels(p))
5532 5533 ui.write(' '.join(p.tags()), label='log.tag')
5533 5534 if p.bookmarks():
5534 5535 marks.extend(p.bookmarks())
5535 5536 if p.rev() == -1:
5536 5537 if not len(repo):
5537 5538 ui.write(_(' (empty repository)'))
5538 5539 else:
5539 5540 ui.write(_(' (no revision checked out)'))
5540 5541 if p.obsolete():
5541 5542 ui.write(_(' (obsolete)'))
5542 5543 if p.isunstable():
5543 5544 instabilities = (ui.label(instability, 'trouble.%s' % instability)
5544 5545 for instability in p.instabilities())
5545 5546 ui.write(' ('
5546 5547 + ', '.join(instabilities)
5547 5548 + ')')
5548 5549 ui.write('\n')
5549 5550 if p.description():
5550 5551 ui.status(' ' + p.description().splitlines()[0].strip() + '\n',
5551 5552 label='log.summary')
5552 5553
5553 5554 branch = ctx.branch()
5554 5555 bheads = repo.branchheads(branch)
5555 5556 # i18n: column positioning for "hg summary"
5556 5557 m = _('branch: %s\n') % branch
5557 5558 if branch != 'default':
5558 5559 ui.write(m, label='log.branch')
5559 5560 else:
5560 5561 ui.status(m, label='log.branch')
5561 5562
5562 5563 if marks:
5563 5564 active = repo._activebookmark
5564 5565 # i18n: column positioning for "hg summary"
5565 5566 ui.write(_('bookmarks:'), label='log.bookmark')
5566 5567 if active is not None:
5567 5568 if active in marks:
5568 5569 ui.write(' *' + active, label=bookmarks.activebookmarklabel)
5569 5570 marks.remove(active)
5570 5571 else:
5571 5572 ui.write(' [%s]' % active, label=bookmarks.activebookmarklabel)
5572 5573 for m in marks:
5573 5574 ui.write(' ' + m, label='log.bookmark')
5574 5575 ui.write('\n', label='log.bookmark')
5575 5576
5576 5577 status = repo.status(unknown=True)
5577 5578
5578 5579 c = repo.dirstate.copies()
5579 5580 copied, renamed = [], []
5580 5581 for d, s in c.iteritems():
5581 5582 if s in status.removed:
5582 5583 status.removed.remove(s)
5583 5584 renamed.append(d)
5584 5585 else:
5585 5586 copied.append(d)
5586 5587 if d in status.added:
5587 5588 status.added.remove(d)
5588 5589
5589 5590 subs = [s for s in ctx.substate if ctx.sub(s).dirty()]
5590 5591
5591 5592 labels = [(ui.label(_('%d modified'), 'status.modified'), status.modified),
5592 5593 (ui.label(_('%d added'), 'status.added'), status.added),
5593 5594 (ui.label(_('%d removed'), 'status.removed'), status.removed),
5594 5595 (ui.label(_('%d renamed'), 'status.copied'), renamed),
5595 5596 (ui.label(_('%d copied'), 'status.copied'), copied),
5596 5597 (ui.label(_('%d deleted'), 'status.deleted'), status.deleted),
5597 5598 (ui.label(_('%d unknown'), 'status.unknown'), status.unknown),
5598 5599 (ui.label(_('%d unresolved'), 'resolve.unresolved'), unresolved),
5599 5600 (ui.label(_('%d subrepos'), 'status.modified'), subs)]
5600 5601 t = []
5601 5602 for l, s in labels:
5602 5603 if s:
5603 5604 t.append(l % len(s))
5604 5605
5605 5606 t = ', '.join(t)
5606 5607 cleanworkdir = False
5607 5608
5608 5609 if repo.vfs.exists('graftstate'):
5609 5610 t += _(' (graft in progress)')
5610 5611 if repo.vfs.exists('updatestate'):
5611 5612 t += _(' (interrupted update)')
5612 5613 elif len(parents) > 1:
5613 5614 t += _(' (merge)')
5614 5615 elif branch != parents[0].branch():
5615 5616 t += _(' (new branch)')
5616 5617 elif (parents[0].closesbranch() and
5617 5618 pnode in repo.branchheads(branch, closed=True)):
5618 5619 t += _(' (head closed)')
5619 5620 elif not (status.modified or status.added or status.removed or renamed or
5620 5621 copied or subs):
5621 5622 t += _(' (clean)')
5622 5623 cleanworkdir = True
5623 5624 elif pnode not in bheads:
5624 5625 t += _(' (new branch head)')
5625 5626
5626 5627 if parents:
5627 5628 pendingphase = max(p.phase() for p in parents)
5628 5629 else:
5629 5630 pendingphase = phases.public
5630 5631
5631 5632 if pendingphase > phases.newcommitphase(ui):
5632 5633 t += ' (%s)' % phases.phasenames[pendingphase]
5633 5634
5634 5635 if cleanworkdir:
5635 5636 # i18n: column positioning for "hg summary"
5636 5637 ui.status(_('commit: %s\n') % t.strip())
5637 5638 else:
5638 5639 # i18n: column positioning for "hg summary"
5639 5640 ui.write(_('commit: %s\n') % t.strip())
5640 5641
5641 5642 # all ancestors of branch heads - all ancestors of parent = new csets
5642 5643 new = len(repo.changelog.findmissing([pctx.node() for pctx in parents],
5643 5644 bheads))
5644 5645
5645 5646 if new == 0:
5646 5647 # i18n: column positioning for "hg summary"
5647 5648 ui.status(_('update: (current)\n'))
5648 5649 elif pnode not in bheads:
5649 5650 # i18n: column positioning for "hg summary"
5650 5651 ui.write(_('update: %d new changesets (update)\n') % new)
5651 5652 else:
5652 5653 # i18n: column positioning for "hg summary"
5653 5654 ui.write(_('update: %d new changesets, %d branch heads (merge)\n') %
5654 5655 (new, len(bheads)))
5655 5656
5656 5657 t = []
5657 5658 draft = len(repo.revs('draft()'))
5658 5659 if draft:
5659 5660 t.append(_('%d draft') % draft)
5660 5661 secret = len(repo.revs('secret()'))
5661 5662 if secret:
5662 5663 t.append(_('%d secret') % secret)
5663 5664
5664 5665 if draft or secret:
5665 5666 ui.status(_('phases: %s\n') % ', '.join(t))
5666 5667
5667 5668 if obsolete.isenabled(repo, obsolete.createmarkersopt):
5668 5669 for trouble in ("orphan", "contentdivergent", "phasedivergent"):
5669 5670 numtrouble = len(repo.revs(trouble + "()"))
5670 5671 # We write all the possibilities to ease translation
5671 5672 troublemsg = {
5672 5673 "orphan": _("orphan: %d changesets"),
5673 5674 "contentdivergent": _("content-divergent: %d changesets"),
5674 5675 "phasedivergent": _("phase-divergent: %d changesets"),
5675 5676 }
5676 5677 if numtrouble > 0:
5677 5678 ui.status(troublemsg[trouble] % numtrouble + "\n")
5678 5679
5679 5680 cmdutil.summaryhooks(ui, repo)
5680 5681
5681 5682 if opts.get('remote'):
5682 5683 needsincoming, needsoutgoing = True, True
5683 5684 else:
5684 5685 needsincoming, needsoutgoing = False, False
5685 5686 for i, o in cmdutil.summaryremotehooks(ui, repo, opts, None):
5686 5687 if i:
5687 5688 needsincoming = True
5688 5689 if o:
5689 5690 needsoutgoing = True
5690 5691 if not needsincoming and not needsoutgoing:
5691 5692 return
5692 5693
5693 5694 def getincoming():
5694 5695 source, branches = hg.parseurl(ui.expandpath('default'))
5695 5696 sbranch = branches[0]
5696 5697 try:
5697 5698 other = hg.peer(repo, {}, source)
5698 5699 except error.RepoError:
5699 5700 if opts.get('remote'):
5700 5701 raise
5701 5702 return source, sbranch, None, None, None
5702 5703 revs, checkout = hg.addbranchrevs(repo, other, branches, None)
5703 5704 if revs:
5704 5705 revs = [other.lookup(rev) for rev in revs]
5705 5706 ui.debug('comparing with %s\n' % util.hidepassword(source))
5706 5707 repo.ui.pushbuffer()
5707 5708 commoninc = discovery.findcommonincoming(repo, other, heads=revs)
5708 5709 repo.ui.popbuffer()
5709 5710 return source, sbranch, other, commoninc, commoninc[1]
5710 5711
5711 5712 if needsincoming:
5712 5713 source, sbranch, sother, commoninc, incoming = getincoming()
5713 5714 else:
5714 5715 source = sbranch = sother = commoninc = incoming = None
5715 5716
5716 5717 def getoutgoing():
5717 5718 dest, branches = hg.parseurl(ui.expandpath('default-push', 'default'))
5718 5719 dbranch = branches[0]
5719 5720 revs, checkout = hg.addbranchrevs(repo, repo, branches, None)
5720 5721 if source != dest:
5721 5722 try:
5722 5723 dother = hg.peer(repo, {}, dest)
5723 5724 except error.RepoError:
5724 5725 if opts.get('remote'):
5725 5726 raise
5726 5727 return dest, dbranch, None, None
5727 5728 ui.debug('comparing with %s\n' % util.hidepassword(dest))
5728 5729 elif sother is None:
5729 5730 # there is no explicit destination peer, but source one is invalid
5730 5731 return dest, dbranch, None, None
5731 5732 else:
5732 5733 dother = sother
5733 5734 if (source != dest or (sbranch is not None and sbranch != dbranch)):
5734 5735 common = None
5735 5736 else:
5736 5737 common = commoninc
5737 5738 if revs:
5738 5739 revs = [repo.lookup(rev) for rev in revs]
5739 5740 repo.ui.pushbuffer()
5740 5741 outgoing = discovery.findcommonoutgoing(repo, dother, onlyheads=revs,
5741 5742 commoninc=common)
5742 5743 repo.ui.popbuffer()
5743 5744 return dest, dbranch, dother, outgoing
5744 5745
5745 5746 if needsoutgoing:
5746 5747 dest, dbranch, dother, outgoing = getoutgoing()
5747 5748 else:
5748 5749 dest = dbranch = dother = outgoing = None
5749 5750
5750 5751 if opts.get('remote'):
5751 5752 t = []
5752 5753 if incoming:
5753 5754 t.append(_('1 or more incoming'))
5754 5755 o = outgoing.missing
5755 5756 if o:
5756 5757 t.append(_('%d outgoing') % len(o))
5757 5758 other = dother or sother
5758 5759 if 'bookmarks' in other.listkeys('namespaces'):
5759 5760 counts = bookmarks.summary(repo, other)
5760 5761 if counts[0] > 0:
5761 5762 t.append(_('%d incoming bookmarks') % counts[0])
5762 5763 if counts[1] > 0:
5763 5764 t.append(_('%d outgoing bookmarks') % counts[1])
5764 5765
5765 5766 if t:
5766 5767 # i18n: column positioning for "hg summary"
5767 5768 ui.write(_('remote: %s\n') % (', '.join(t)))
5768 5769 else:
5769 5770 # i18n: column positioning for "hg summary"
5770 5771 ui.status(_('remote: (synced)\n'))
5771 5772
5772 5773 cmdutil.summaryremotehooks(ui, repo, opts,
5773 5774 ((source, sbranch, sother, commoninc),
5774 5775 (dest, dbranch, dother, outgoing)))
5775 5776
5776 5777 @command('tag',
5777 5778 [('f', 'force', None, _('force tag')),
5778 5779 ('l', 'local', None, _('make the tag local')),
5779 5780 ('r', 'rev', '', _('revision to tag'), _('REV')),
5780 5781 ('', 'remove', None, _('remove a tag')),
5781 5782 # -l/--local is already there, commitopts cannot be used
5782 5783 ('e', 'edit', None, _('invoke editor on commit messages')),
5783 5784 ('m', 'message', '', _('use text as commit message'), _('TEXT')),
5784 5785 ] + commitopts2,
5785 5786 _('[-f] [-l] [-m TEXT] [-d DATE] [-u USER] [-r REV] NAME...'),
5786 5787 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION)
5787 5788 def tag(ui, repo, name1, *names, **opts):
5788 5789 """add one or more tags for the current or given revision
5789 5790
5790 5791 Name a particular revision using <name>.
5791 5792
5792 5793 Tags are used to name particular revisions of the repository and are
5793 5794 very useful to compare different revisions, to go back to significant
5794 5795 earlier versions or to mark branch points as releases, etc. Changing
5795 5796 an existing tag is normally disallowed; use -f/--force to override.
5796 5797
5797 5798 If no revision is given, the parent of the working directory is
5798 5799 used.
5799 5800
5800 5801 To facilitate version control, distribution, and merging of tags,
5801 5802 they are stored as a file named ".hgtags" which is managed similarly
5802 5803 to other project files and can be hand-edited if necessary. This
5803 5804 also means that tagging creates a new commit. The file
5804 5805 ".hg/localtags" is used for local tags (not shared among
5805 5806 repositories).
5806 5807
5807 5808 Tag commits are usually made at the head of a branch. If the parent
5808 5809 of the working directory is not a branch head, :hg:`tag` aborts; use
5809 5810 -f/--force to force the tag commit to be based on a non-head
5810 5811 changeset.
5811 5812
5812 5813 See :hg:`help dates` for a list of formats valid for -d/--date.
5813 5814
5814 5815 Since tag names have priority over branch names during revision
5815 5816 lookup, using an existing branch name as a tag name is discouraged.
5816 5817
5817 5818 Returns 0 on success.
5818 5819 """
5819 5820 opts = pycompat.byteskwargs(opts)
5820 5821 with repo.wlock(), repo.lock():
5821 5822 rev_ = "."
5822 5823 names = [t.strip() for t in (name1,) + names]
5823 5824 if len(names) != len(set(names)):
5824 5825 raise error.Abort(_('tag names must be unique'))
5825 5826 for n in names:
5826 5827 scmutil.checknewlabel(repo, n, 'tag')
5827 5828 if not n:
5828 5829 raise error.Abort(_('tag names cannot consist entirely of '
5829 5830 'whitespace'))
5830 5831 if opts.get('rev') and opts.get('remove'):
5831 5832 raise error.Abort(_("--rev and --remove are incompatible"))
5832 5833 if opts.get('rev'):
5833 5834 rev_ = opts['rev']
5834 5835 message = opts.get('message')
5835 5836 if opts.get('remove'):
5836 5837 if opts.get('local'):
5837 5838 expectedtype = 'local'
5838 5839 else:
5839 5840 expectedtype = 'global'
5840 5841
5841 5842 for n in names:
5842 5843 if repo.tagtype(n) == 'global':
5843 5844 alltags = tagsmod.findglobaltags(ui, repo)
5844 5845 if alltags[n][0] == nullid:
5845 5846 raise error.Abort(_("tag '%s' is already removed") % n)
5846 5847 if not repo.tagtype(n):
5847 5848 raise error.Abort(_("tag '%s' does not exist") % n)
5848 5849 if repo.tagtype(n) != expectedtype:
5849 5850 if expectedtype == 'global':
5850 5851 raise error.Abort(_("tag '%s' is not a global tag") % n)
5851 5852 else:
5852 5853 raise error.Abort(_("tag '%s' is not a local tag") % n)
5853 5854 rev_ = 'null'
5854 5855 if not message:
5855 5856 # we don't translate commit messages
5856 5857 message = 'Removed tag %s' % ', '.join(names)
5857 5858 elif not opts.get('force'):
5858 5859 for n in names:
5859 5860 if n in repo.tags():
5860 5861 raise error.Abort(_("tag '%s' already exists "
5861 5862 "(use -f to force)") % n)
5862 5863 if not opts.get('local'):
5863 5864 p1, p2 = repo.dirstate.parents()
5864 5865 if p2 != nullid:
5865 5866 raise error.Abort(_('uncommitted merge'))
5866 5867 bheads = repo.branchheads()
5867 5868 if not opts.get('force') and bheads and p1 not in bheads:
5868 5869 raise error.Abort(_('working directory is not at a branch head '
5869 5870 '(use -f to force)'))
5870 5871 node = scmutil.revsingle(repo, rev_).node()
5871 5872
5872 5873 if not message:
5873 5874 # we don't translate commit messages
5874 5875 message = ('Added tag %s for changeset %s' %
5875 5876 (', '.join(names), short(node)))
5876 5877
5877 5878 date = opts.get('date')
5878 5879 if date:
5879 5880 date = dateutil.parsedate(date)
5880 5881
5881 5882 if opts.get('remove'):
5882 5883 editform = 'tag.remove'
5883 5884 else:
5884 5885 editform = 'tag.add'
5885 5886 editor = cmdutil.getcommiteditor(editform=editform,
5886 5887 **pycompat.strkwargs(opts))
5887 5888
5888 5889 # don't allow tagging the null rev
5889 5890 if (not opts.get('remove') and
5890 5891 scmutil.revsingle(repo, rev_).rev() == nullrev):
5891 5892 raise error.Abort(_("cannot tag null revision"))
5892 5893
5893 5894 tagsmod.tag(repo, names, node, message, opts.get('local'),
5894 5895 opts.get('user'), date, editor=editor)
5895 5896
5896 5897 @command(
5897 5898 'tags', formatteropts, '',
5898 5899 helpcategory=command.CATEGORY_CHANGE_ORGANIZATION,
5899 5900 intents={INTENT_READONLY})
5900 5901 def tags(ui, repo, **opts):
5901 5902 """list repository tags
5902 5903
5903 5904 This lists both regular and local tags. When the -v/--verbose
5904 5905 switch is used, a third column "local" is printed for local tags.
5905 5906 When the -q/--quiet switch is used, only the tag name is printed.
5906 5907
5907 5908 .. container:: verbose
5908 5909
5909 5910 Template:
5910 5911
5911 5912 The following keywords are supported in addition to the common template
5912 5913 keywords and functions such as ``{tag}``. See also
5913 5914 :hg:`help templates`.
5914 5915
5915 5916 :type: String. ``local`` for local tags.
5916 5917
5917 5918 Returns 0 on success.
5918 5919 """
5919 5920
5920 5921 opts = pycompat.byteskwargs(opts)
5921 5922 ui.pager('tags')
5922 5923 fm = ui.formatter('tags', opts)
5923 5924 hexfunc = fm.hexfunc
5924 5925
5925 5926 for t, n in reversed(repo.tagslist()):
5926 5927 hn = hexfunc(n)
5927 5928 label = 'tags.normal'
5928 5929 tagtype = ''
5929 5930 if repo.tagtype(t) == 'local':
5930 5931 label = 'tags.local'
5931 5932 tagtype = 'local'
5932 5933
5933 5934 fm.startitem()
5934 5935 fm.context(repo=repo)
5935 5936 fm.write('tag', '%s', t, label=label)
5936 5937 fmt = " " * (30 - encoding.colwidth(t)) + ' %5d:%s'
5937 5938 fm.condwrite(not ui.quiet, 'rev node', fmt,
5938 5939 repo.changelog.rev(n), hn, label=label)
5939 5940 fm.condwrite(ui.verbose and tagtype, 'type', ' %s',
5940 5941 tagtype, label=label)
5941 5942 fm.plain('\n')
5942 5943 fm.end()
5943 5944
5944 5945 @command('tip',
5945 5946 [('p', 'patch', None, _('show patch')),
5946 5947 ('g', 'git', None, _('use git extended diff format')),
5947 5948 ] + templateopts,
5948 5949 _('[-p] [-g]'),
5949 5950 helpcategory=command.CATEGORY_CHANGE_NAVIGATION)
5950 5951 def tip(ui, repo, **opts):
5951 5952 """show the tip revision (DEPRECATED)
5952 5953
5953 5954 The tip revision (usually just called the tip) is the changeset
5954 5955 most recently added to the repository (and therefore the most
5955 5956 recently changed head).
5956 5957
5957 5958 If you have just made a commit, that commit will be the tip. If
5958 5959 you have just pulled changes from another repository, the tip of
5959 5960 that repository becomes the current tip. The "tip" tag is special
5960 5961 and cannot be renamed or assigned to a different changeset.
5961 5962
5962 5963 This command is deprecated, please use :hg:`heads` instead.
5963 5964
5964 5965 Returns 0 on success.
5965 5966 """
5966 5967 opts = pycompat.byteskwargs(opts)
5967 5968 displayer = logcmdutil.changesetdisplayer(ui, repo, opts)
5968 5969 displayer.show(repo['tip'])
5969 5970 displayer.close()
5970 5971
5971 5972 @command('unbundle',
5972 5973 [('u', 'update', None,
5973 5974 _('update to new branch head if changesets were unbundled'))],
5974 5975 _('[-u] FILE...'),
5975 5976 helpcategory=command.CATEGORY_IMPORT_EXPORT)
5976 5977 def unbundle(ui, repo, fname1, *fnames, **opts):
5977 5978 """apply one or more bundle files
5978 5979
5979 5980 Apply one or more bundle files generated by :hg:`bundle`.
5980 5981
5981 5982 Returns 0 on success, 1 if an update has unresolved files.
5982 5983 """
5983 5984 fnames = (fname1,) + fnames
5984 5985
5985 5986 with repo.lock():
5986 5987 for fname in fnames:
5987 5988 f = hg.openpath(ui, fname)
5988 5989 gen = exchange.readbundle(ui, f, fname)
5989 5990 if isinstance(gen, streamclone.streamcloneapplier):
5990 5991 raise error.Abort(
5991 5992 _('packed bundles cannot be applied with '
5992 5993 '"hg unbundle"'),
5993 5994 hint=_('use "hg debugapplystreamclonebundle"'))
5994 5995 url = 'bundle:' + fname
5995 5996 try:
5996 5997 txnname = 'unbundle'
5997 5998 if not isinstance(gen, bundle2.unbundle20):
5998 5999 txnname = 'unbundle\n%s' % util.hidepassword(url)
5999 6000 with repo.transaction(txnname) as tr:
6000 6001 op = bundle2.applybundle(repo, gen, tr, source='unbundle',
6001 6002 url=url)
6002 6003 except error.BundleUnknownFeatureError as exc:
6003 6004 raise error.Abort(
6004 6005 _('%s: unknown bundle feature, %s') % (fname, exc),
6005 6006 hint=_("see https://mercurial-scm.org/"
6006 6007 "wiki/BundleFeature for more "
6007 6008 "information"))
6008 6009 modheads = bundle2.combinechangegroupresults(op)
6009 6010
6010 6011 return postincoming(ui, repo, modheads, opts.get(r'update'), None, None)
6011 6012
6012 6013 @command('update|up|checkout|co',
6013 6014 [('C', 'clean', None, _('discard uncommitted changes (no backup)')),
6014 6015 ('c', 'check', None, _('require clean working directory')),
6015 6016 ('m', 'merge', None, _('merge uncommitted changes')),
6016 6017 ('d', 'date', '', _('tipmost revision matching date'), _('DATE')),
6017 6018 ('r', 'rev', '', _('revision'), _('REV'))
6018 6019 ] + mergetoolopts,
6019 6020 _('[-C|-c|-m] [-d DATE] [[-r] REV]'),
6020 6021 helpcategory=command.CATEGORY_WORKING_DIRECTORY,
6021 6022 helpbasic=True)
6022 6023 def update(ui, repo, node=None, **opts):
6023 6024 """update working directory (or switch revisions)
6024 6025
6025 6026 Update the repository's working directory to the specified
6026 6027 changeset. If no changeset is specified, update to the tip of the
6027 6028 current named branch and move the active bookmark (see :hg:`help
6028 6029 bookmarks`).
6029 6030
6030 6031 Update sets the working directory's parent revision to the specified
6031 6032 changeset (see :hg:`help parents`).
6032 6033
6033 6034 If the changeset is not a descendant or ancestor of the working
6034 6035 directory's parent and there are uncommitted changes, the update is
6035 6036 aborted. With the -c/--check option, the working directory is checked
6036 6037 for uncommitted changes; if none are found, the working directory is
6037 6038 updated to the specified changeset.
6038 6039
6039 6040 .. container:: verbose
6040 6041
6041 6042 The -C/--clean, -c/--check, and -m/--merge options control what
6042 6043 happens if the working directory contains uncommitted changes.
6043 6044 At most of one of them can be specified.
6044 6045
6045 6046 1. If no option is specified, and if
6046 6047 the requested changeset is an ancestor or descendant of
6047 6048 the working directory's parent, the uncommitted changes
6048 6049 are merged into the requested changeset and the merged
6049 6050 result is left uncommitted. If the requested changeset is
6050 6051 not an ancestor or descendant (that is, it is on another
6051 6052 branch), the update is aborted and the uncommitted changes
6052 6053 are preserved.
6053 6054
6054 6055 2. With the -m/--merge option, the update is allowed even if the
6055 6056 requested changeset is not an ancestor or descendant of
6056 6057 the working directory's parent.
6057 6058
6058 6059 3. With the -c/--check option, the update is aborted and the
6059 6060 uncommitted changes are preserved.
6060 6061
6061 6062 4. With the -C/--clean option, uncommitted changes are discarded and
6062 6063 the working directory is updated to the requested changeset.
6063 6064
6064 6065 To cancel an uncommitted merge (and lose your changes), use
6065 6066 :hg:`merge --abort`.
6066 6067
6067 6068 Use null as the changeset to remove the working directory (like
6068 6069 :hg:`clone -U`).
6069 6070
6070 6071 If you want to revert just one file to an older revision, use
6071 6072 :hg:`revert [-r REV] NAME`.
6072 6073
6073 6074 See :hg:`help dates` for a list of formats valid for -d/--date.
6074 6075
6075 6076 Returns 0 on success, 1 if there are unresolved files.
6076 6077 """
6077 6078 rev = opts.get(r'rev')
6078 6079 date = opts.get(r'date')
6079 6080 clean = opts.get(r'clean')
6080 6081 check = opts.get(r'check')
6081 6082 merge = opts.get(r'merge')
6082 6083 if rev and node:
6083 6084 raise error.Abort(_("please specify just one revision"))
6084 6085
6085 6086 if ui.configbool('commands', 'update.requiredest'):
6086 6087 if not node and not rev and not date:
6087 6088 raise error.Abort(_('you must specify a destination'),
6088 6089 hint=_('for example: hg update ".::"'))
6089 6090
6090 6091 if rev is None or rev == '':
6091 6092 rev = node
6092 6093
6093 6094 if date and rev is not None:
6094 6095 raise error.Abort(_("you can't specify a revision and a date"))
6095 6096
6096 6097 if len([x for x in (clean, check, merge) if x]) > 1:
6097 6098 raise error.Abort(_("can only specify one of -C/--clean, -c/--check, "
6098 6099 "or -m/--merge"))
6099 6100
6100 6101 updatecheck = None
6101 6102 if check:
6102 6103 updatecheck = 'abort'
6103 6104 elif merge:
6104 6105 updatecheck = 'none'
6105 6106
6106 6107 with repo.wlock():
6107 6108 cmdutil.clearunfinished(repo)
6108 6109
6109 6110 if date:
6110 6111 rev = cmdutil.finddate(ui, repo, date)
6111 6112
6112 6113 # if we defined a bookmark, we have to remember the original name
6113 6114 brev = rev
6114 6115 if rev:
6115 6116 repo = scmutil.unhidehashlikerevs(repo, [rev], 'nowarn')
6116 6117 ctx = scmutil.revsingle(repo, rev, default=None)
6117 6118 rev = ctx.rev()
6118 6119 hidden = ctx.hidden()
6119 6120 overrides = {('ui', 'forcemerge'): opts.get(r'tool', '')}
6120 6121 with ui.configoverride(overrides, 'update'):
6121 6122 ret = hg.updatetotally(ui, repo, rev, brev, clean=clean,
6122 6123 updatecheck=updatecheck)
6123 6124 if hidden:
6124 6125 ctxstr = ctx.hex()[:12]
6125 6126 ui.warn(_("updated to hidden changeset %s\n") % ctxstr)
6126 6127
6127 6128 if ctx.obsolete():
6128 6129 obsfatemsg = obsutil._getfilteredreason(repo, ctxstr, ctx)
6129 6130 ui.warn("(%s)\n" % obsfatemsg)
6130 6131 return ret
6131 6132
6132 6133 @command('verify', [], helpcategory=command.CATEGORY_MAINTENANCE)
6133 6134 def verify(ui, repo):
6134 6135 """verify the integrity of the repository
6135 6136
6136 6137 Verify the integrity of the current repository.
6137 6138
6138 6139 This will perform an extensive check of the repository's
6139 6140 integrity, validating the hashes and checksums of each entry in
6140 6141 the changelog, manifest, and tracked files, as well as the
6141 6142 integrity of their crosslinks and indices.
6142 6143
6143 6144 Please see https://mercurial-scm.org/wiki/RepositoryCorruption
6144 6145 for more information about recovery from corruption of the
6145 6146 repository.
6146 6147
6147 6148 Returns 0 on success, 1 if errors are encountered.
6148 6149 """
6149 6150 return hg.verify(repo)
6150 6151
6151 6152 @command(
6152 6153 'version', [] + formatteropts, helpcategory=command.CATEGORY_HELP,
6153 6154 norepo=True, intents={INTENT_READONLY})
6154 6155 def version_(ui, **opts):
6155 6156 """output version and copyright information
6156 6157
6157 6158 .. container:: verbose
6158 6159
6159 6160 Template:
6160 6161
6161 6162 The following keywords are supported. See also :hg:`help templates`.
6162 6163
6163 6164 :extensions: List of extensions.
6164 6165 :ver: String. Version number.
6165 6166
6166 6167 And each entry of ``{extensions}`` provides the following sub-keywords
6167 6168 in addition to ``{ver}``.
6168 6169
6169 6170 :bundled: Boolean. True if included in the release.
6170 6171 :name: String. Extension name.
6171 6172 """
6172 6173 opts = pycompat.byteskwargs(opts)
6173 6174 if ui.verbose:
6174 6175 ui.pager('version')
6175 6176 fm = ui.formatter("version", opts)
6176 6177 fm.startitem()
6177 6178 fm.write("ver", _("Mercurial Distributed SCM (version %s)\n"),
6178 6179 util.version())
6179 6180 license = _(
6180 6181 "(see https://mercurial-scm.org for more information)\n"
6181 6182 "\nCopyright (C) 2005-2019 Matt Mackall and others\n"
6182 6183 "This is free software; see the source for copying conditions. "
6183 6184 "There is NO\nwarranty; "
6184 6185 "not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n"
6185 6186 )
6186 6187 if not ui.quiet:
6187 6188 fm.plain(license)
6188 6189
6189 6190 if ui.verbose:
6190 6191 fm.plain(_("\nEnabled extensions:\n\n"))
6191 6192 # format names and versions into columns
6192 6193 names = []
6193 6194 vers = []
6194 6195 isinternals = []
6195 6196 for name, module in extensions.extensions():
6196 6197 names.append(name)
6197 6198 vers.append(extensions.moduleversion(module) or None)
6198 6199 isinternals.append(extensions.ismoduleinternal(module))
6199 6200 fn = fm.nested("extensions", tmpl='{name}\n')
6200 6201 if names:
6201 6202 namefmt = " %%-%ds " % max(len(n) for n in names)
6202 6203 places = [_("external"), _("internal")]
6203 6204 for n, v, p in zip(names, vers, isinternals):
6204 6205 fn.startitem()
6205 6206 fn.condwrite(ui.verbose, "name", namefmt, n)
6206 6207 if ui.verbose:
6207 6208 fn.plain("%s " % places[p])
6208 6209 fn.data(bundled=p)
6209 6210 fn.condwrite(ui.verbose and v, "ver", "%s", v)
6210 6211 if ui.verbose:
6211 6212 fn.plain("\n")
6212 6213 fn.end()
6213 6214 fm.end()
6214 6215
6215 6216 def loadcmdtable(ui, name, cmdtable):
6216 6217 """Load command functions from specified cmdtable
6217 6218 """
6218 6219 cmdtable = cmdtable.copy()
6219 6220 for cmd in list(cmdtable):
6220 6221 if not cmd.startswith('^'):
6221 6222 continue
6222 6223 ui.deprecwarn("old-style command registration '%s' in extension '%s'"
6223 6224 % (cmd, name), '4.8')
6224 6225 entry = cmdtable.pop(cmd)
6225 6226 entry[0].helpbasic = True
6226 6227 cmdtable[cmd[1:]] = entry
6227 6228
6228 6229 overrides = [cmd for cmd in cmdtable if cmd in table]
6229 6230 if overrides:
6230 6231 ui.warn(_("extension '%s' overrides commands: %s\n")
6231 6232 % (name, " ".join(overrides)))
6232 6233 table.update(cmdtable)
@@ -1,1840 +1,1840 b''
1 1 # subrepo.py - sub-repository classes and factory
2 2 #
3 3 # Copyright 2009-2010 Matt Mackall <mpm@selenic.com>
4 4 #
5 5 # This software may be used and distributed according to the terms of the
6 6 # GNU General Public License version 2 or any later version.
7 7
8 8 from __future__ import absolute_import
9 9
10 10 import copy
11 11 import errno
12 12 import hashlib
13 13 import os
14 14 import re
15 15 import stat
16 16 import subprocess
17 17 import sys
18 18 import tarfile
19 19 import xml.dom.minidom
20 20
21 21 from .i18n import _
22 22 from . import (
23 23 cmdutil,
24 24 encoding,
25 25 error,
26 26 exchange,
27 27 logcmdutil,
28 28 match as matchmod,
29 29 node,
30 30 pathutil,
31 31 phases,
32 32 pycompat,
33 33 scmutil,
34 34 subrepoutil,
35 35 util,
36 36 vfs as vfsmod,
37 37 )
38 38 from .utils import (
39 39 dateutil,
40 40 procutil,
41 41 stringutil,
42 42 )
43 43
44 44 hg = None
45 45 reporelpath = subrepoutil.reporelpath
46 46 subrelpath = subrepoutil.subrelpath
47 47 _abssource = subrepoutil._abssource
48 48 propertycache = util.propertycache
49 49
50 50 def _expandedabspath(path):
51 51 '''
52 52 get a path or url and if it is a path expand it and return an absolute path
53 53 '''
54 54 expandedpath = util.urllocalpath(util.expandpath(path))
55 55 u = util.url(expandedpath)
56 56 if not u.scheme:
57 57 path = util.normpath(os.path.abspath(u.path))
58 58 return path
59 59
60 60 def _getstorehashcachename(remotepath):
61 61 '''get a unique filename for the store hash cache of a remote repository'''
62 62 return node.hex(hashlib.sha1(_expandedabspath(remotepath)).digest())[0:12]
63 63
64 64 class SubrepoAbort(error.Abort):
65 65 """Exception class used to avoid handling a subrepo error more than once"""
66 66 def __init__(self, *args, **kw):
67 67 self.subrepo = kw.pop(r'subrepo', None)
68 68 self.cause = kw.pop(r'cause', None)
69 69 error.Abort.__init__(self, *args, **kw)
70 70
71 71 def annotatesubrepoerror(func):
72 72 def decoratedmethod(self, *args, **kargs):
73 73 try:
74 74 res = func(self, *args, **kargs)
75 75 except SubrepoAbort as ex:
76 76 # This exception has already been handled
77 77 raise ex
78 78 except error.Abort as ex:
79 79 subrepo = subrelpath(self)
80 80 errormsg = (stringutil.forcebytestr(ex) + ' '
81 81 + _('(in subrepository "%s")') % subrepo)
82 82 # avoid handling this exception by raising a SubrepoAbort exception
83 83 raise SubrepoAbort(errormsg, hint=ex.hint, subrepo=subrepo,
84 84 cause=sys.exc_info())
85 85 return res
86 86 return decoratedmethod
87 87
88 88 def _updateprompt(ui, sub, dirty, local, remote):
89 89 if dirty:
90 90 msg = (_(' subrepository sources for %s differ\n'
91 91 'use (l)ocal source (%s) or (r)emote source (%s)?'
92 92 '$$ &Local $$ &Remote')
93 93 % (subrelpath(sub), local, remote))
94 94 else:
95 95 msg = (_(' subrepository sources for %s differ (in checked out '
96 96 'version)\n'
97 97 'use (l)ocal source (%s) or (r)emote source (%s)?'
98 98 '$$ &Local $$ &Remote')
99 99 % (subrelpath(sub), local, remote))
100 100 return ui.promptchoice(msg, 0)
101 101
102 102 def _sanitize(ui, vfs, ignore):
103 103 for dirname, dirs, names in vfs.walk():
104 104 for i, d in enumerate(dirs):
105 105 if d.lower() == ignore:
106 106 del dirs[i]
107 107 break
108 108 if vfs.basename(dirname).lower() != '.hg':
109 109 continue
110 110 for f in names:
111 111 if f.lower() == 'hgrc':
112 112 ui.warn(_("warning: removing potentially hostile 'hgrc' "
113 113 "in '%s'\n") % vfs.join(dirname))
114 114 vfs.unlink(vfs.reljoin(dirname, f))
115 115
116 116 def _auditsubrepopath(repo, path):
117 117 # sanity check for potentially unsafe paths such as '~' and '$FOO'
118 118 if path.startswith('~') or '$' in path or util.expandpath(path) != path:
119 119 raise error.Abort(_('subrepo path contains illegal component: %s')
120 120 % path)
121 121 # auditor doesn't check if the path itself is a symlink
122 122 pathutil.pathauditor(repo.root)(path)
123 123 if repo.wvfs.islink(path):
124 124 raise error.Abort(_("subrepo '%s' traverses symbolic link") % path)
125 125
126 126 SUBREPO_ALLOWED_DEFAULTS = {
127 127 'hg': True,
128 128 'git': False,
129 129 'svn': False,
130 130 }
131 131
132 132 def _checktype(ui, kind):
133 133 # subrepos.allowed is a master kill switch. If disabled, subrepos are
134 134 # disabled period.
135 135 if not ui.configbool('subrepos', 'allowed', True):
136 136 raise error.Abort(_('subrepos not enabled'),
137 137 hint=_("see 'hg help config.subrepos' for details"))
138 138
139 139 default = SUBREPO_ALLOWED_DEFAULTS.get(kind, False)
140 140 if not ui.configbool('subrepos', '%s:allowed' % kind, default):
141 141 raise error.Abort(_('%s subrepos not allowed') % kind,
142 142 hint=_("see 'hg help config.subrepos' for details"))
143 143
144 144 if kind not in types:
145 145 raise error.Abort(_('unknown subrepo type %s') % kind)
146 146
147 147 def subrepo(ctx, path, allowwdir=False, allowcreate=True):
148 148 """return instance of the right subrepo class for subrepo in path"""
149 149 # subrepo inherently violates our import layering rules
150 150 # because it wants to make repo objects from deep inside the stack
151 151 # so we manually delay the circular imports to not break
152 152 # scripts that don't use our demand-loading
153 153 global hg
154 154 from . import hg as h
155 155 hg = h
156 156
157 157 repo = ctx.repo()
158 158 _auditsubrepopath(repo, path)
159 159 state = ctx.substate[path]
160 160 _checktype(repo.ui, state[2])
161 161 if allowwdir:
162 162 state = (state[0], ctx.subrev(path), state[2])
163 163 return types[state[2]](ctx, path, state[:2], allowcreate)
164 164
165 165 def nullsubrepo(ctx, path, pctx):
166 166 """return an empty subrepo in pctx for the extant subrepo in ctx"""
167 167 # subrepo inherently violates our import layering rules
168 168 # because it wants to make repo objects from deep inside the stack
169 169 # so we manually delay the circular imports to not break
170 170 # scripts that don't use our demand-loading
171 171 global hg
172 172 from . import hg as h
173 173 hg = h
174 174
175 175 repo = ctx.repo()
176 176 _auditsubrepopath(repo, path)
177 177 state = ctx.substate[path]
178 178 _checktype(repo.ui, state[2])
179 179 subrev = ''
180 180 if state[2] == 'hg':
181 181 subrev = "0" * 40
182 182 return types[state[2]](pctx, path, (state[0], subrev), True)
183 183
184 184 # subrepo classes need to implement the following abstract class:
185 185
186 186 class abstractsubrepo(object):
187 187
188 188 def __init__(self, ctx, path):
189 189 """Initialize abstractsubrepo part
190 190
191 191 ``ctx`` is the context referring this subrepository in the
192 192 parent repository.
193 193
194 194 ``path`` is the path to this subrepository as seen from
195 195 innermost repository.
196 196 """
197 197 self.ui = ctx.repo().ui
198 198 self._ctx = ctx
199 199 self._path = path
200 200
201 201 def addwebdirpath(self, serverpath, webconf):
202 202 """Add the hgwebdir entries for this subrepo, and any of its subrepos.
203 203
204 204 ``serverpath`` is the path component of the URL for this repo.
205 205
206 206 ``webconf`` is the dictionary of hgwebdir entries.
207 207 """
208 208 pass
209 209
210 210 def storeclean(self, path):
211 211 """
212 212 returns true if the repository has not changed since it was last
213 213 cloned from or pushed to a given repository.
214 214 """
215 215 return False
216 216
217 217 def dirty(self, ignoreupdate=False, missing=False):
218 218 """returns true if the dirstate of the subrepo is dirty or does not
219 219 match current stored state. If ignoreupdate is true, only check
220 220 whether the subrepo has uncommitted changes in its dirstate. If missing
221 221 is true, check for deleted files.
222 222 """
223 223 raise NotImplementedError
224 224
225 225 def dirtyreason(self, ignoreupdate=False, missing=False):
226 226 """return reason string if it is ``dirty()``
227 227
228 228 Returned string should have enough information for the message
229 229 of exception.
230 230
231 231 This returns None, otherwise.
232 232 """
233 233 if self.dirty(ignoreupdate=ignoreupdate, missing=missing):
234 234 return _('uncommitted changes in subrepository "%s"'
235 235 ) % subrelpath(self)
236 236
237 237 def bailifchanged(self, ignoreupdate=False, hint=None):
238 238 """raise Abort if subrepository is ``dirty()``
239 239 """
240 240 dirtyreason = self.dirtyreason(ignoreupdate=ignoreupdate,
241 241 missing=True)
242 242 if dirtyreason:
243 243 raise error.Abort(dirtyreason, hint=hint)
244 244
245 245 def basestate(self):
246 246 """current working directory base state, disregarding .hgsubstate
247 247 state and working directory modifications"""
248 248 raise NotImplementedError
249 249
250 250 def checknested(self, path):
251 251 """check if path is a subrepository within this repository"""
252 252 return False
253 253
254 254 def commit(self, text, user, date):
255 255 """commit the current changes to the subrepo with the given
256 256 log message. Use given user and date if possible. Return the
257 257 new state of the subrepo.
258 258 """
259 259 raise NotImplementedError
260 260
261 261 def phase(self, state):
262 262 """returns phase of specified state in the subrepository.
263 263 """
264 264 return phases.public
265 265
266 266 def remove(self):
267 267 """remove the subrepo
268 268
269 269 (should verify the dirstate is not dirty first)
270 270 """
271 271 raise NotImplementedError
272 272
273 273 def get(self, state, overwrite=False):
274 274 """run whatever commands are needed to put the subrepo into
275 275 this state
276 276 """
277 277 raise NotImplementedError
278 278
279 279 def merge(self, state):
280 280 """merge currently-saved state with the new state."""
281 281 raise NotImplementedError
282 282
283 283 def push(self, opts):
284 284 """perform whatever action is analogous to 'hg push'
285 285
286 286 This may be a no-op on some systems.
287 287 """
288 288 raise NotImplementedError
289 289
290 290 def add(self, ui, match, prefix, uipathfn, explicitonly, **opts):
291 291 return []
292 292
293 293 def addremove(self, matcher, prefix, uipathfn, opts):
294 294 self.ui.warn("%s: %s" % (prefix, _("addremove is not supported")))
295 295 return 1
296 296
297 297 def cat(self, match, fm, fntemplate, prefix, **opts):
298 298 return 1
299 299
300 300 def status(self, rev2, **opts):
301 301 return scmutil.status([], [], [], [], [], [], [])
302 302
303 303 def diff(self, ui, diffopts, node2, match, prefix, **opts):
304 304 pass
305 305
306 306 def outgoing(self, ui, dest, opts):
307 307 return 1
308 308
309 309 def incoming(self, ui, source, opts):
310 310 return 1
311 311
312 312 def files(self):
313 313 """return filename iterator"""
314 314 raise NotImplementedError
315 315
316 316 def filedata(self, name, decode):
317 317 """return file data, optionally passed through repo decoders"""
318 318 raise NotImplementedError
319 319
320 320 def fileflags(self, name):
321 321 """return file flags"""
322 322 return ''
323 323
324 324 def matchfileset(self, expr, badfn=None):
325 325 """Resolve the fileset expression for this repo"""
326 326 return matchmod.nevermatcher(self.wvfs.base, '', badfn=badfn)
327 327
328 328 def printfiles(self, ui, m, fm, fmt, subrepos):
329 329 """handle the files command for this subrepo"""
330 330 return 1
331 331
332 332 def archive(self, archiver, prefix, match=None, decode=True):
333 333 if match is not None:
334 334 files = [f for f in self.files() if match(f)]
335 335 else:
336 336 files = self.files()
337 337 total = len(files)
338 338 relpath = subrelpath(self)
339 339 progress = self.ui.makeprogress(_('archiving (%s)') % relpath,
340 340 unit=_('files'), total=total)
341 341 progress.update(0)
342 342 for name in files:
343 343 flags = self.fileflags(name)
344 344 mode = 'x' in flags and 0o755 or 0o644
345 345 symlink = 'l' in flags
346 346 archiver.addfile(prefix + name, mode, symlink,
347 347 self.filedata(name, decode))
348 348 progress.increment()
349 349 progress.complete()
350 350 return total
351 351
352 352 def walk(self, match):
353 353 '''
354 354 walk recursively through the directory tree, finding all files
355 355 matched by the match function
356 356 '''
357 357
358 def forget(self, match, prefix, dryrun, interactive):
358 def forget(self, match, prefix, uipathfn, dryrun, interactive):
359 359 return ([], [])
360 360
361 361 def removefiles(self, matcher, prefix, uipathfn, after, force, subrepos,
362 362 dryrun, warnings):
363 363 """remove the matched files from the subrepository and the filesystem,
364 364 possibly by force and/or after the file has been removed from the
365 365 filesystem. Return 0 on success, 1 on any warning.
366 366 """
367 367 warnings.append(_("warning: removefiles not implemented (%s)")
368 368 % self._path)
369 369 return 1
370 370
371 371 def revert(self, substate, *pats, **opts):
372 372 self.ui.warn(_('%s: reverting %s subrepos is unsupported\n') \
373 373 % (substate[0], substate[2]))
374 374 return []
375 375
376 376 def shortid(self, revid):
377 377 return revid
378 378
379 379 def unshare(self):
380 380 '''
381 381 convert this repository from shared to normal storage.
382 382 '''
383 383
384 384 def verify(self):
385 385 '''verify the integrity of the repository. Return 0 on success or
386 386 warning, 1 on any error.
387 387 '''
388 388 return 0
389 389
390 390 @propertycache
391 391 def wvfs(self):
392 392 """return vfs to access the working directory of this subrepository
393 393 """
394 394 return vfsmod.vfs(self._ctx.repo().wvfs.join(self._path))
395 395
396 396 @propertycache
397 397 def _relpath(self):
398 398 """return path to this subrepository as seen from outermost repository
399 399 """
400 400 return self.wvfs.reljoin(reporelpath(self._ctx.repo()), self._path)
401 401
402 402 class hgsubrepo(abstractsubrepo):
403 403 def __init__(self, ctx, path, state, allowcreate):
404 404 super(hgsubrepo, self).__init__(ctx, path)
405 405 self._state = state
406 406 r = ctx.repo()
407 407 root = r.wjoin(path)
408 408 create = allowcreate and not r.wvfs.exists('%s/.hg' % path)
409 409 # repository constructor does expand variables in path, which is
410 410 # unsafe since subrepo path might come from untrusted source.
411 411 if os.path.realpath(util.expandpath(root)) != root:
412 412 raise error.Abort(_('subrepo path contains illegal component: %s')
413 413 % path)
414 414 self._repo = hg.repository(r.baseui, root, create=create)
415 415 if self._repo.root != root:
416 416 raise error.ProgrammingError('failed to reject unsafe subrepo '
417 417 'path: %s (expanded to %s)'
418 418 % (root, self._repo.root))
419 419
420 420 # Propagate the parent's --hidden option
421 421 if r is r.unfiltered():
422 422 self._repo = self._repo.unfiltered()
423 423
424 424 self.ui = self._repo.ui
425 425 for s, k in [('ui', 'commitsubrepos')]:
426 426 v = r.ui.config(s, k)
427 427 if v:
428 428 self.ui.setconfig(s, k, v, 'subrepo')
429 429 # internal config: ui._usedassubrepo
430 430 self.ui.setconfig('ui', '_usedassubrepo', 'True', 'subrepo')
431 431 self._initrepo(r, state[0], create)
432 432
433 433 @annotatesubrepoerror
434 434 def addwebdirpath(self, serverpath, webconf):
435 435 cmdutil.addwebdirpath(self._repo, subrelpath(self), webconf)
436 436
437 437 def storeclean(self, path):
438 438 with self._repo.lock():
439 439 return self._storeclean(path)
440 440
441 441 def _storeclean(self, path):
442 442 clean = True
443 443 itercache = self._calcstorehash(path)
444 444 for filehash in self._readstorehashcache(path):
445 445 if filehash != next(itercache, None):
446 446 clean = False
447 447 break
448 448 if clean:
449 449 # if not empty:
450 450 # the cached and current pull states have a different size
451 451 clean = next(itercache, None) is None
452 452 return clean
453 453
454 454 def _calcstorehash(self, remotepath):
455 455 '''calculate a unique "store hash"
456 456
457 457 This method is used to to detect when there are changes that may
458 458 require a push to a given remote path.'''
459 459 # sort the files that will be hashed in increasing (likely) file size
460 460 filelist = ('bookmarks', 'store/phaseroots', 'store/00changelog.i')
461 461 yield '# %s\n' % _expandedabspath(remotepath)
462 462 vfs = self._repo.vfs
463 463 for relname in filelist:
464 464 filehash = node.hex(hashlib.sha1(vfs.tryread(relname)).digest())
465 465 yield '%s = %s\n' % (relname, filehash)
466 466
467 467 @propertycache
468 468 def _cachestorehashvfs(self):
469 469 return vfsmod.vfs(self._repo.vfs.join('cache/storehash'))
470 470
471 471 def _readstorehashcache(self, remotepath):
472 472 '''read the store hash cache for a given remote repository'''
473 473 cachefile = _getstorehashcachename(remotepath)
474 474 return self._cachestorehashvfs.tryreadlines(cachefile, 'r')
475 475
476 476 def _cachestorehash(self, remotepath):
477 477 '''cache the current store hash
478 478
479 479 Each remote repo requires its own store hash cache, because a subrepo
480 480 store may be "clean" versus a given remote repo, but not versus another
481 481 '''
482 482 cachefile = _getstorehashcachename(remotepath)
483 483 with self._repo.lock():
484 484 storehash = list(self._calcstorehash(remotepath))
485 485 vfs = self._cachestorehashvfs
486 486 vfs.writelines(cachefile, storehash, mode='wb', notindexed=True)
487 487
488 488 def _getctx(self):
489 489 '''fetch the context for this subrepo revision, possibly a workingctx
490 490 '''
491 491 if self._ctx.rev() is None:
492 492 return self._repo[None] # workingctx if parent is workingctx
493 493 else:
494 494 rev = self._state[1]
495 495 return self._repo[rev]
496 496
497 497 @annotatesubrepoerror
498 498 def _initrepo(self, parentrepo, source, create):
499 499 self._repo._subparent = parentrepo
500 500 self._repo._subsource = source
501 501
502 502 if create:
503 503 lines = ['[paths]\n']
504 504
505 505 def addpathconfig(key, value):
506 506 if value:
507 507 lines.append('%s = %s\n' % (key, value))
508 508 self.ui.setconfig('paths', key, value, 'subrepo')
509 509
510 510 defpath = _abssource(self._repo, abort=False)
511 511 defpushpath = _abssource(self._repo, True, abort=False)
512 512 addpathconfig('default', defpath)
513 513 if defpath != defpushpath:
514 514 addpathconfig('default-push', defpushpath)
515 515
516 516 self._repo.vfs.write('hgrc', util.tonativeeol(''.join(lines)))
517 517
518 518 @annotatesubrepoerror
519 519 def add(self, ui, match, prefix, uipathfn, explicitonly, **opts):
520 520 return cmdutil.add(ui, self._repo, match, prefix, uipathfn,
521 521 explicitonly, **opts)
522 522
523 523 @annotatesubrepoerror
524 524 def addremove(self, m, prefix, uipathfn, opts):
525 525 # In the same way as sub directories are processed, once in a subrepo,
526 526 # always entry any of its subrepos. Don't corrupt the options that will
527 527 # be used to process sibling subrepos however.
528 528 opts = copy.copy(opts)
529 529 opts['subrepos'] = True
530 530 return scmutil.addremove(self._repo, m, prefix, uipathfn, opts)
531 531
532 532 @annotatesubrepoerror
533 533 def cat(self, match, fm, fntemplate, prefix, **opts):
534 534 rev = self._state[1]
535 535 ctx = self._repo[rev]
536 536 return cmdutil.cat(self.ui, self._repo, ctx, match, fm, fntemplate,
537 537 prefix, **opts)
538 538
539 539 @annotatesubrepoerror
540 540 def status(self, rev2, **opts):
541 541 try:
542 542 rev1 = self._state[1]
543 543 ctx1 = self._repo[rev1]
544 544 ctx2 = self._repo[rev2]
545 545 return self._repo.status(ctx1, ctx2, **opts)
546 546 except error.RepoLookupError as inst:
547 547 self.ui.warn(_('warning: error "%s" in subrepository "%s"\n')
548 548 % (inst, subrelpath(self)))
549 549 return scmutil.status([], [], [], [], [], [], [])
550 550
551 551 @annotatesubrepoerror
552 552 def diff(self, ui, diffopts, node2, match, prefix, **opts):
553 553 try:
554 554 node1 = node.bin(self._state[1])
555 555 # We currently expect node2 to come from substate and be
556 556 # in hex format
557 557 if node2 is not None:
558 558 node2 = node.bin(node2)
559 559 logcmdutil.diffordiffstat(ui, self._repo, diffopts, node1, node2,
560 560 match, prefix=prefix, listsubrepos=True,
561 561 **opts)
562 562 except error.RepoLookupError as inst:
563 563 self.ui.warn(_('warning: error "%s" in subrepository "%s"\n')
564 564 % (inst, subrelpath(self)))
565 565
566 566 @annotatesubrepoerror
567 567 def archive(self, archiver, prefix, match=None, decode=True):
568 568 self._get(self._state + ('hg',))
569 569 files = self.files()
570 570 if match:
571 571 files = [f for f in files if match(f)]
572 572 rev = self._state[1]
573 573 ctx = self._repo[rev]
574 574 scmutil.prefetchfiles(self._repo, [ctx.rev()],
575 575 scmutil.matchfiles(self._repo, files))
576 576 total = abstractsubrepo.archive(self, archiver, prefix, match)
577 577 for subpath in ctx.substate:
578 578 s = subrepo(ctx, subpath, True)
579 579 submatch = matchmod.subdirmatcher(subpath, match)
580 580 subprefix = prefix + subpath + '/'
581 581 total += s.archive(archiver, subprefix, submatch,
582 582 decode)
583 583 return total
584 584
585 585 @annotatesubrepoerror
586 586 def dirty(self, ignoreupdate=False, missing=False):
587 587 r = self._state[1]
588 588 if r == '' and not ignoreupdate: # no state recorded
589 589 return True
590 590 w = self._repo[None]
591 591 if r != w.p1().hex() and not ignoreupdate:
592 592 # different version checked out
593 593 return True
594 594 return w.dirty(missing=missing) # working directory changed
595 595
596 596 def basestate(self):
597 597 return self._repo['.'].hex()
598 598
599 599 def checknested(self, path):
600 600 return self._repo._checknested(self._repo.wjoin(path))
601 601
602 602 @annotatesubrepoerror
603 603 def commit(self, text, user, date):
604 604 # don't bother committing in the subrepo if it's only been
605 605 # updated
606 606 if not self.dirty(True):
607 607 return self._repo['.'].hex()
608 608 self.ui.debug("committing subrepo %s\n" % subrelpath(self))
609 609 n = self._repo.commit(text, user, date)
610 610 if not n:
611 611 return self._repo['.'].hex() # different version checked out
612 612 return node.hex(n)
613 613
614 614 @annotatesubrepoerror
615 615 def phase(self, state):
616 616 return self._repo[state or '.'].phase()
617 617
618 618 @annotatesubrepoerror
619 619 def remove(self):
620 620 # we can't fully delete the repository as it may contain
621 621 # local-only history
622 622 self.ui.note(_('removing subrepo %s\n') % subrelpath(self))
623 623 hg.clean(self._repo, node.nullid, False)
624 624
625 625 def _get(self, state):
626 626 source, revision, kind = state
627 627 parentrepo = self._repo._subparent
628 628
629 629 if revision in self._repo.unfiltered():
630 630 # Allow shared subrepos tracked at null to setup the sharedpath
631 631 if len(self._repo) != 0 or not parentrepo.shared():
632 632 return True
633 633 self._repo._subsource = source
634 634 srcurl = _abssource(self._repo)
635 635
636 636 # Defer creating the peer until after the status message is logged, in
637 637 # case there are network problems.
638 638 getpeer = lambda: hg.peer(self._repo, {}, srcurl)
639 639
640 640 if len(self._repo) == 0:
641 641 # use self._repo.vfs instead of self.wvfs to remove .hg only
642 642 self._repo.vfs.rmtree()
643 643
644 644 # A remote subrepo could be shared if there is a local copy
645 645 # relative to the parent's share source. But clone pooling doesn't
646 646 # assemble the repos in a tree, so that can't be consistently done.
647 647 # A simpler option is for the user to configure clone pooling, and
648 648 # work with that.
649 649 if parentrepo.shared() and hg.islocal(srcurl):
650 650 self.ui.status(_('sharing subrepo %s from %s\n')
651 651 % (subrelpath(self), srcurl))
652 652 shared = hg.share(self._repo._subparent.baseui,
653 653 getpeer(), self._repo.root,
654 654 update=False, bookmarks=False)
655 655 self._repo = shared.local()
656 656 else:
657 657 # TODO: find a common place for this and this code in the
658 658 # share.py wrap of the clone command.
659 659 if parentrepo.shared():
660 660 pool = self.ui.config('share', 'pool')
661 661 if pool:
662 662 pool = util.expandpath(pool)
663 663
664 664 shareopts = {
665 665 'pool': pool,
666 666 'mode': self.ui.config('share', 'poolnaming'),
667 667 }
668 668 else:
669 669 shareopts = {}
670 670
671 671 self.ui.status(_('cloning subrepo %s from %s\n')
672 672 % (subrelpath(self), util.hidepassword(srcurl)))
673 673 other, cloned = hg.clone(self._repo._subparent.baseui, {},
674 674 getpeer(), self._repo.root,
675 675 update=False, shareopts=shareopts)
676 676 self._repo = cloned.local()
677 677 self._initrepo(parentrepo, source, create=True)
678 678 self._cachestorehash(srcurl)
679 679 else:
680 680 self.ui.status(_('pulling subrepo %s from %s\n')
681 681 % (subrelpath(self), util.hidepassword(srcurl)))
682 682 cleansub = self.storeclean(srcurl)
683 683 exchange.pull(self._repo, getpeer())
684 684 if cleansub:
685 685 # keep the repo clean after pull
686 686 self._cachestorehash(srcurl)
687 687 return False
688 688
689 689 @annotatesubrepoerror
690 690 def get(self, state, overwrite=False):
691 691 inrepo = self._get(state)
692 692 source, revision, kind = state
693 693 repo = self._repo
694 694 repo.ui.debug("getting subrepo %s\n" % self._path)
695 695 if inrepo:
696 696 urepo = repo.unfiltered()
697 697 ctx = urepo[revision]
698 698 if ctx.hidden():
699 699 urepo.ui.warn(
700 700 _('revision %s in subrepository "%s" is hidden\n') \
701 701 % (revision[0:12], self._path))
702 702 repo = urepo
703 703 hg.updaterepo(repo, revision, overwrite)
704 704
705 705 @annotatesubrepoerror
706 706 def merge(self, state):
707 707 self._get(state)
708 708 cur = self._repo['.']
709 709 dst = self._repo[state[1]]
710 710 anc = dst.ancestor(cur)
711 711
712 712 def mergefunc():
713 713 if anc == cur and dst.branch() == cur.branch():
714 714 self.ui.debug('updating subrepository "%s"\n'
715 715 % subrelpath(self))
716 716 hg.update(self._repo, state[1])
717 717 elif anc == dst:
718 718 self.ui.debug('skipping subrepository "%s"\n'
719 719 % subrelpath(self))
720 720 else:
721 721 self.ui.debug('merging subrepository "%s"\n' % subrelpath(self))
722 722 hg.merge(self._repo, state[1], remind=False)
723 723
724 724 wctx = self._repo[None]
725 725 if self.dirty():
726 726 if anc != dst:
727 727 if _updateprompt(self.ui, self, wctx.dirty(), cur, dst):
728 728 mergefunc()
729 729 else:
730 730 mergefunc()
731 731 else:
732 732 mergefunc()
733 733
734 734 @annotatesubrepoerror
735 735 def push(self, opts):
736 736 force = opts.get('force')
737 737 newbranch = opts.get('new_branch')
738 738 ssh = opts.get('ssh')
739 739
740 740 # push subrepos depth-first for coherent ordering
741 741 c = self._repo['.']
742 742 subs = c.substate # only repos that are committed
743 743 for s in sorted(subs):
744 744 if c.sub(s).push(opts) == 0:
745 745 return False
746 746
747 747 dsturl = _abssource(self._repo, True)
748 748 if not force:
749 749 if self.storeclean(dsturl):
750 750 self.ui.status(
751 751 _('no changes made to subrepo %s since last push to %s\n')
752 752 % (subrelpath(self), util.hidepassword(dsturl)))
753 753 return None
754 754 self.ui.status(_('pushing subrepo %s to %s\n') %
755 755 (subrelpath(self), util.hidepassword(dsturl)))
756 756 other = hg.peer(self._repo, {'ssh': ssh}, dsturl)
757 757 res = exchange.push(self._repo, other, force, newbranch=newbranch)
758 758
759 759 # the repo is now clean
760 760 self._cachestorehash(dsturl)
761 761 return res.cgresult
762 762
763 763 @annotatesubrepoerror
764 764 def outgoing(self, ui, dest, opts):
765 765 if 'rev' in opts or 'branch' in opts:
766 766 opts = copy.copy(opts)
767 767 opts.pop('rev', None)
768 768 opts.pop('branch', None)
769 769 return hg.outgoing(ui, self._repo, _abssource(self._repo, True), opts)
770 770
771 771 @annotatesubrepoerror
772 772 def incoming(self, ui, source, opts):
773 773 if 'rev' in opts or 'branch' in opts:
774 774 opts = copy.copy(opts)
775 775 opts.pop('rev', None)
776 776 opts.pop('branch', None)
777 777 return hg.incoming(ui, self._repo, _abssource(self._repo, False), opts)
778 778
779 779 @annotatesubrepoerror
780 780 def files(self):
781 781 rev = self._state[1]
782 782 ctx = self._repo[rev]
783 783 return ctx.manifest().keys()
784 784
785 785 def filedata(self, name, decode):
786 786 rev = self._state[1]
787 787 data = self._repo[rev][name].data()
788 788 if decode:
789 789 data = self._repo.wwritedata(name, data)
790 790 return data
791 791
792 792 def fileflags(self, name):
793 793 rev = self._state[1]
794 794 ctx = self._repo[rev]
795 795 return ctx.flags(name)
796 796
797 797 @annotatesubrepoerror
798 798 def printfiles(self, ui, m, fm, fmt, subrepos):
799 799 # If the parent context is a workingctx, use the workingctx here for
800 800 # consistency.
801 801 if self._ctx.rev() is None:
802 802 ctx = self._repo[None]
803 803 else:
804 804 rev = self._state[1]
805 805 ctx = self._repo[rev]
806 806 return cmdutil.files(ui, ctx, m, fm, fmt, subrepos)
807 807
808 808 @annotatesubrepoerror
809 809 def matchfileset(self, expr, badfn=None):
810 810 repo = self._repo
811 811 if self._ctx.rev() is None:
812 812 ctx = repo[None]
813 813 else:
814 814 rev = self._state[1]
815 815 ctx = repo[rev]
816 816
817 817 matchers = [ctx.matchfileset(expr, badfn=badfn)]
818 818
819 819 for subpath in ctx.substate:
820 820 sub = ctx.sub(subpath)
821 821
822 822 try:
823 823 sm = sub.matchfileset(expr, badfn=badfn)
824 824 pm = matchmod.prefixdirmatcher(repo.root, repo.getcwd(),
825 825 subpath, sm, badfn=badfn)
826 826 matchers.append(pm)
827 827 except error.LookupError:
828 828 self.ui.status(_("skipping missing subrepository: %s\n")
829 829 % self.wvfs.reljoin(reporelpath(self), subpath))
830 830 if len(matchers) == 1:
831 831 return matchers[0]
832 832 return matchmod.unionmatcher(matchers)
833 833
834 834 def walk(self, match):
835 835 ctx = self._repo[None]
836 836 return ctx.walk(match)
837 837
838 838 @annotatesubrepoerror
839 def forget(self, match, prefix, dryrun, interactive):
840 return cmdutil.forget(self.ui, self._repo, match, prefix,
839 def forget(self, match, prefix, uipathfn, dryrun, interactive):
840 return cmdutil.forget(self.ui, self._repo, match, prefix, uipathfn,
841 841 True, dryrun=dryrun, interactive=interactive)
842 842
843 843 @annotatesubrepoerror
844 844 def removefiles(self, matcher, prefix, uipathfn, after, force, subrepos,
845 845 dryrun, warnings):
846 846 return cmdutil.remove(self.ui, self._repo, matcher, prefix, uipathfn,
847 847 after, force, subrepos, dryrun)
848 848
849 849 @annotatesubrepoerror
850 850 def revert(self, substate, *pats, **opts):
851 851 # reverting a subrepo is a 2 step process:
852 852 # 1. if the no_backup is not set, revert all modified
853 853 # files inside the subrepo
854 854 # 2. update the subrepo to the revision specified in
855 855 # the corresponding substate dictionary
856 856 self.ui.status(_('reverting subrepo %s\n') % substate[0])
857 857 if not opts.get(r'no_backup'):
858 858 # Revert all files on the subrepo, creating backups
859 859 # Note that this will not recursively revert subrepos
860 860 # We could do it if there was a set:subrepos() predicate
861 861 opts = opts.copy()
862 862 opts[r'date'] = None
863 863 opts[r'rev'] = substate[1]
864 864
865 865 self.filerevert(*pats, **opts)
866 866
867 867 # Update the repo to the revision specified in the given substate
868 868 if not opts.get(r'dry_run'):
869 869 self.get(substate, overwrite=True)
870 870
871 871 def filerevert(self, *pats, **opts):
872 872 ctx = self._repo[opts[r'rev']]
873 873 parents = self._repo.dirstate.parents()
874 874 if opts.get(r'all'):
875 875 pats = ['set:modified()']
876 876 else:
877 877 pats = []
878 878 cmdutil.revert(self.ui, self._repo, ctx, parents, *pats, **opts)
879 879
880 880 def shortid(self, revid):
881 881 return revid[:12]
882 882
883 883 @annotatesubrepoerror
884 884 def unshare(self):
885 885 # subrepo inherently violates our import layering rules
886 886 # because it wants to make repo objects from deep inside the stack
887 887 # so we manually delay the circular imports to not break
888 888 # scripts that don't use our demand-loading
889 889 global hg
890 890 from . import hg as h
891 891 hg = h
892 892
893 893 # Nothing prevents a user from sharing in a repo, and then making that a
894 894 # subrepo. Alternately, the previous unshare attempt may have failed
895 895 # part way through. So recurse whether or not this layer is shared.
896 896 if self._repo.shared():
897 897 self.ui.status(_("unsharing subrepo '%s'\n") % self._relpath)
898 898
899 899 hg.unshare(self.ui, self._repo)
900 900
901 901 def verify(self):
902 902 try:
903 903 rev = self._state[1]
904 904 ctx = self._repo.unfiltered()[rev]
905 905 if ctx.hidden():
906 906 # Since hidden revisions aren't pushed/pulled, it seems worth an
907 907 # explicit warning.
908 908 ui = self._repo.ui
909 909 ui.warn(_("subrepo '%s' is hidden in revision %s\n") %
910 910 (self._relpath, node.short(self._ctx.node())))
911 911 return 0
912 912 except error.RepoLookupError:
913 913 # A missing subrepo revision may be a case of needing to pull it, so
914 914 # don't treat this as an error.
915 915 self._repo.ui.warn(_("subrepo '%s' not found in revision %s\n") %
916 916 (self._relpath, node.short(self._ctx.node())))
917 917 return 0
918 918
919 919 @propertycache
920 920 def wvfs(self):
921 921 """return own wvfs for efficiency and consistency
922 922 """
923 923 return self._repo.wvfs
924 924
925 925 @propertycache
926 926 def _relpath(self):
927 927 """return path to this subrepository as seen from outermost repository
928 928 """
929 929 # Keep consistent dir separators by avoiding vfs.join(self._path)
930 930 return reporelpath(self._repo)
931 931
932 932 class svnsubrepo(abstractsubrepo):
933 933 def __init__(self, ctx, path, state, allowcreate):
934 934 super(svnsubrepo, self).__init__(ctx, path)
935 935 self._state = state
936 936 self._exe = procutil.findexe('svn')
937 937 if not self._exe:
938 938 raise error.Abort(_("'svn' executable not found for subrepo '%s'")
939 939 % self._path)
940 940
941 941 def _svncommand(self, commands, filename='', failok=False):
942 942 cmd = [self._exe]
943 943 extrakw = {}
944 944 if not self.ui.interactive():
945 945 # Making stdin be a pipe should prevent svn from behaving
946 946 # interactively even if we can't pass --non-interactive.
947 947 extrakw[r'stdin'] = subprocess.PIPE
948 948 # Starting in svn 1.5 --non-interactive is a global flag
949 949 # instead of being per-command, but we need to support 1.4 so
950 950 # we have to be intelligent about what commands take
951 951 # --non-interactive.
952 952 if commands[0] in ('update', 'checkout', 'commit'):
953 953 cmd.append('--non-interactive')
954 954 cmd.extend(commands)
955 955 if filename is not None:
956 956 path = self.wvfs.reljoin(self._ctx.repo().origroot,
957 957 self._path, filename)
958 958 cmd.append(path)
959 959 env = dict(encoding.environ)
960 960 # Avoid localized output, preserve current locale for everything else.
961 961 lc_all = env.get('LC_ALL')
962 962 if lc_all:
963 963 env['LANG'] = lc_all
964 964 del env['LC_ALL']
965 965 env['LC_MESSAGES'] = 'C'
966 966 p = subprocess.Popen(pycompat.rapply(procutil.tonativestr, cmd),
967 967 bufsize=-1, close_fds=procutil.closefds,
968 968 stdout=subprocess.PIPE, stderr=subprocess.PIPE,
969 969 env=procutil.tonativeenv(env), **extrakw)
970 970 stdout, stderr = map(util.fromnativeeol, p.communicate())
971 971 stderr = stderr.strip()
972 972 if not failok:
973 973 if p.returncode:
974 974 raise error.Abort(stderr or 'exited with code %d'
975 975 % p.returncode)
976 976 if stderr:
977 977 self.ui.warn(stderr + '\n')
978 978 return stdout, stderr
979 979
980 980 @propertycache
981 981 def _svnversion(self):
982 982 output, err = self._svncommand(['--version', '--quiet'], filename=None)
983 983 m = re.search(br'^(\d+)\.(\d+)', output)
984 984 if not m:
985 985 raise error.Abort(_('cannot retrieve svn tool version'))
986 986 return (int(m.group(1)), int(m.group(2)))
987 987
988 988 def _svnmissing(self):
989 989 return not self.wvfs.exists('.svn')
990 990
991 991 def _wcrevs(self):
992 992 # Get the working directory revision as well as the last
993 993 # commit revision so we can compare the subrepo state with
994 994 # both. We used to store the working directory one.
995 995 output, err = self._svncommand(['info', '--xml'])
996 996 doc = xml.dom.minidom.parseString(output)
997 997 entries = doc.getElementsByTagName(r'entry')
998 998 lastrev, rev = '0', '0'
999 999 if entries:
1000 1000 rev = pycompat.bytestr(entries[0].getAttribute(r'revision')) or '0'
1001 1001 commits = entries[0].getElementsByTagName(r'commit')
1002 1002 if commits:
1003 1003 lastrev = pycompat.bytestr(
1004 1004 commits[0].getAttribute(r'revision')) or '0'
1005 1005 return (lastrev, rev)
1006 1006
1007 1007 def _wcrev(self):
1008 1008 return self._wcrevs()[0]
1009 1009
1010 1010 def _wcchanged(self):
1011 1011 """Return (changes, extchanges, missing) where changes is True
1012 1012 if the working directory was changed, extchanges is
1013 1013 True if any of these changes concern an external entry and missing
1014 1014 is True if any change is a missing entry.
1015 1015 """
1016 1016 output, err = self._svncommand(['status', '--xml'])
1017 1017 externals, changes, missing = [], [], []
1018 1018 doc = xml.dom.minidom.parseString(output)
1019 1019 for e in doc.getElementsByTagName(r'entry'):
1020 1020 s = e.getElementsByTagName(r'wc-status')
1021 1021 if not s:
1022 1022 continue
1023 1023 item = s[0].getAttribute(r'item')
1024 1024 props = s[0].getAttribute(r'props')
1025 1025 path = e.getAttribute(r'path').encode('utf8')
1026 1026 if item == r'external':
1027 1027 externals.append(path)
1028 1028 elif item == r'missing':
1029 1029 missing.append(path)
1030 1030 if (item not in (r'', r'normal', r'unversioned', r'external')
1031 1031 or props not in (r'', r'none', r'normal')):
1032 1032 changes.append(path)
1033 1033 for path in changes:
1034 1034 for ext in externals:
1035 1035 if path == ext or path.startswith(ext + pycompat.ossep):
1036 1036 return True, True, bool(missing)
1037 1037 return bool(changes), False, bool(missing)
1038 1038
1039 1039 @annotatesubrepoerror
1040 1040 def dirty(self, ignoreupdate=False, missing=False):
1041 1041 if self._svnmissing():
1042 1042 return self._state[1] != ''
1043 1043 wcchanged = self._wcchanged()
1044 1044 changed = wcchanged[0] or (missing and wcchanged[2])
1045 1045 if not changed:
1046 1046 if self._state[1] in self._wcrevs() or ignoreupdate:
1047 1047 return False
1048 1048 return True
1049 1049
1050 1050 def basestate(self):
1051 1051 lastrev, rev = self._wcrevs()
1052 1052 if lastrev != rev:
1053 1053 # Last committed rev is not the same than rev. We would
1054 1054 # like to take lastrev but we do not know if the subrepo
1055 1055 # URL exists at lastrev. Test it and fallback to rev it
1056 1056 # is not there.
1057 1057 try:
1058 1058 self._svncommand(['list', '%s@%s' % (self._state[0], lastrev)])
1059 1059 return lastrev
1060 1060 except error.Abort:
1061 1061 pass
1062 1062 return rev
1063 1063
1064 1064 @annotatesubrepoerror
1065 1065 def commit(self, text, user, date):
1066 1066 # user and date are out of our hands since svn is centralized
1067 1067 changed, extchanged, missing = self._wcchanged()
1068 1068 if not changed:
1069 1069 return self.basestate()
1070 1070 if extchanged:
1071 1071 # Do not try to commit externals
1072 1072 raise error.Abort(_('cannot commit svn externals'))
1073 1073 if missing:
1074 1074 # svn can commit with missing entries but aborting like hg
1075 1075 # seems a better approach.
1076 1076 raise error.Abort(_('cannot commit missing svn entries'))
1077 1077 commitinfo, err = self._svncommand(['commit', '-m', text])
1078 1078 self.ui.status(commitinfo)
1079 1079 newrev = re.search('Committed revision ([0-9]+).', commitinfo)
1080 1080 if not newrev:
1081 1081 if not commitinfo.strip():
1082 1082 # Sometimes, our definition of "changed" differs from
1083 1083 # svn one. For instance, svn ignores missing files
1084 1084 # when committing. If there are only missing files, no
1085 1085 # commit is made, no output and no error code.
1086 1086 raise error.Abort(_('failed to commit svn changes'))
1087 1087 raise error.Abort(commitinfo.splitlines()[-1])
1088 1088 newrev = newrev.groups()[0]
1089 1089 self.ui.status(self._svncommand(['update', '-r', newrev])[0])
1090 1090 return newrev
1091 1091
1092 1092 @annotatesubrepoerror
1093 1093 def remove(self):
1094 1094 if self.dirty():
1095 1095 self.ui.warn(_('not removing repo %s because '
1096 1096 'it has changes.\n') % self._path)
1097 1097 return
1098 1098 self.ui.note(_('removing subrepo %s\n') % self._path)
1099 1099
1100 1100 self.wvfs.rmtree(forcibly=True)
1101 1101 try:
1102 1102 pwvfs = self._ctx.repo().wvfs
1103 1103 pwvfs.removedirs(pwvfs.dirname(self._path))
1104 1104 except OSError:
1105 1105 pass
1106 1106
1107 1107 @annotatesubrepoerror
1108 1108 def get(self, state, overwrite=False):
1109 1109 if overwrite:
1110 1110 self._svncommand(['revert', '--recursive'])
1111 1111 args = ['checkout']
1112 1112 if self._svnversion >= (1, 5):
1113 1113 args.append('--force')
1114 1114 # The revision must be specified at the end of the URL to properly
1115 1115 # update to a directory which has since been deleted and recreated.
1116 1116 args.append('%s@%s' % (state[0], state[1]))
1117 1117
1118 1118 # SEC: check that the ssh url is safe
1119 1119 util.checksafessh(state[0])
1120 1120
1121 1121 status, err = self._svncommand(args, failok=True)
1122 1122 _sanitize(self.ui, self.wvfs, '.svn')
1123 1123 if not re.search('Checked out revision [0-9]+.', status):
1124 1124 if ('is already a working copy for a different URL' in err
1125 1125 and (self._wcchanged()[:2] == (False, False))):
1126 1126 # obstructed but clean working copy, so just blow it away.
1127 1127 self.remove()
1128 1128 self.get(state, overwrite=False)
1129 1129 return
1130 1130 raise error.Abort((status or err).splitlines()[-1])
1131 1131 self.ui.status(status)
1132 1132
1133 1133 @annotatesubrepoerror
1134 1134 def merge(self, state):
1135 1135 old = self._state[1]
1136 1136 new = state[1]
1137 1137 wcrev = self._wcrev()
1138 1138 if new != wcrev:
1139 1139 dirty = old == wcrev or self._wcchanged()[0]
1140 1140 if _updateprompt(self.ui, self, dirty, wcrev, new):
1141 1141 self.get(state, False)
1142 1142
1143 1143 def push(self, opts):
1144 1144 # push is a no-op for SVN
1145 1145 return True
1146 1146
1147 1147 @annotatesubrepoerror
1148 1148 def files(self):
1149 1149 output = self._svncommand(['list', '--recursive', '--xml'])[0]
1150 1150 doc = xml.dom.minidom.parseString(output)
1151 1151 paths = []
1152 1152 for e in doc.getElementsByTagName(r'entry'):
1153 1153 kind = pycompat.bytestr(e.getAttribute(r'kind'))
1154 1154 if kind != 'file':
1155 1155 continue
1156 1156 name = r''.join(c.data for c
1157 1157 in e.getElementsByTagName(r'name')[0].childNodes
1158 1158 if c.nodeType == c.TEXT_NODE)
1159 1159 paths.append(name.encode('utf8'))
1160 1160 return paths
1161 1161
1162 1162 def filedata(self, name, decode):
1163 1163 return self._svncommand(['cat'], name)[0]
1164 1164
1165 1165
1166 1166 class gitsubrepo(abstractsubrepo):
1167 1167 def __init__(self, ctx, path, state, allowcreate):
1168 1168 super(gitsubrepo, self).__init__(ctx, path)
1169 1169 self._state = state
1170 1170 self._abspath = ctx.repo().wjoin(path)
1171 1171 self._subparent = ctx.repo()
1172 1172 self._ensuregit()
1173 1173
1174 1174 def _ensuregit(self):
1175 1175 try:
1176 1176 self._gitexecutable = 'git'
1177 1177 out, err = self._gitnodir(['--version'])
1178 1178 except OSError as e:
1179 1179 genericerror = _("error executing git for subrepo '%s': %s")
1180 1180 notfoundhint = _("check git is installed and in your PATH")
1181 1181 if e.errno != errno.ENOENT:
1182 1182 raise error.Abort(genericerror % (
1183 1183 self._path, encoding.strtolocal(e.strerror)))
1184 1184 elif pycompat.iswindows:
1185 1185 try:
1186 1186 self._gitexecutable = 'git.cmd'
1187 1187 out, err = self._gitnodir(['--version'])
1188 1188 except OSError as e2:
1189 1189 if e2.errno == errno.ENOENT:
1190 1190 raise error.Abort(_("couldn't find 'git' or 'git.cmd'"
1191 1191 " for subrepo '%s'") % self._path,
1192 1192 hint=notfoundhint)
1193 1193 else:
1194 1194 raise error.Abort(genericerror % (self._path,
1195 1195 encoding.strtolocal(e2.strerror)))
1196 1196 else:
1197 1197 raise error.Abort(_("couldn't find git for subrepo '%s'")
1198 1198 % self._path, hint=notfoundhint)
1199 1199 versionstatus = self._checkversion(out)
1200 1200 if versionstatus == 'unknown':
1201 1201 self.ui.warn(_('cannot retrieve git version\n'))
1202 1202 elif versionstatus == 'abort':
1203 1203 raise error.Abort(_('git subrepo requires at least 1.6.0 or later'))
1204 1204 elif versionstatus == 'warning':
1205 1205 self.ui.warn(_('git subrepo requires at least 1.6.0 or later\n'))
1206 1206
1207 1207 @staticmethod
1208 1208 def _gitversion(out):
1209 1209 m = re.search(br'^git version (\d+)\.(\d+)\.(\d+)', out)
1210 1210 if m:
1211 1211 return (int(m.group(1)), int(m.group(2)), int(m.group(3)))
1212 1212
1213 1213 m = re.search(br'^git version (\d+)\.(\d+)', out)
1214 1214 if m:
1215 1215 return (int(m.group(1)), int(m.group(2)), 0)
1216 1216
1217 1217 return -1
1218 1218
1219 1219 @staticmethod
1220 1220 def _checkversion(out):
1221 1221 '''ensure git version is new enough
1222 1222
1223 1223 >>> _checkversion = gitsubrepo._checkversion
1224 1224 >>> _checkversion(b'git version 1.6.0')
1225 1225 'ok'
1226 1226 >>> _checkversion(b'git version 1.8.5')
1227 1227 'ok'
1228 1228 >>> _checkversion(b'git version 1.4.0')
1229 1229 'abort'
1230 1230 >>> _checkversion(b'git version 1.5.0')
1231 1231 'warning'
1232 1232 >>> _checkversion(b'git version 1.9-rc0')
1233 1233 'ok'
1234 1234 >>> _checkversion(b'git version 1.9.0.265.g81cdec2')
1235 1235 'ok'
1236 1236 >>> _checkversion(b'git version 1.9.0.GIT')
1237 1237 'ok'
1238 1238 >>> _checkversion(b'git version 12345')
1239 1239 'unknown'
1240 1240 >>> _checkversion(b'no')
1241 1241 'unknown'
1242 1242 '''
1243 1243 version = gitsubrepo._gitversion(out)
1244 1244 # git 1.4.0 can't work at all, but 1.5.X can in at least some cases,
1245 1245 # despite the docstring comment. For now, error on 1.4.0, warn on
1246 1246 # 1.5.0 but attempt to continue.
1247 1247 if version == -1:
1248 1248 return 'unknown'
1249 1249 if version < (1, 5, 0):
1250 1250 return 'abort'
1251 1251 elif version < (1, 6, 0):
1252 1252 return 'warning'
1253 1253 return 'ok'
1254 1254
1255 1255 def _gitcommand(self, commands, env=None, stream=False):
1256 1256 return self._gitdir(commands, env=env, stream=stream)[0]
1257 1257
1258 1258 def _gitdir(self, commands, env=None, stream=False):
1259 1259 return self._gitnodir(commands, env=env, stream=stream,
1260 1260 cwd=self._abspath)
1261 1261
1262 1262 def _gitnodir(self, commands, env=None, stream=False, cwd=None):
1263 1263 """Calls the git command
1264 1264
1265 1265 The methods tries to call the git command. versions prior to 1.6.0
1266 1266 are not supported and very probably fail.
1267 1267 """
1268 1268 self.ui.debug('%s: git %s\n' % (self._relpath, ' '.join(commands)))
1269 1269 if env is None:
1270 1270 env = encoding.environ.copy()
1271 1271 # disable localization for Git output (issue5176)
1272 1272 env['LC_ALL'] = 'C'
1273 1273 # fix for Git CVE-2015-7545
1274 1274 if 'GIT_ALLOW_PROTOCOL' not in env:
1275 1275 env['GIT_ALLOW_PROTOCOL'] = 'file:git:http:https:ssh'
1276 1276 # unless ui.quiet is set, print git's stderr,
1277 1277 # which is mostly progress and useful info
1278 1278 errpipe = None
1279 1279 if self.ui.quiet:
1280 1280 errpipe = open(os.devnull, 'w')
1281 1281 if self.ui._colormode and len(commands) and commands[0] == "diff":
1282 1282 # insert the argument in the front,
1283 1283 # the end of git diff arguments is used for paths
1284 1284 commands.insert(1, '--color')
1285 1285 p = subprocess.Popen(pycompat.rapply(procutil.tonativestr,
1286 1286 [self._gitexecutable] + commands),
1287 1287 bufsize=-1,
1288 1288 cwd=pycompat.rapply(procutil.tonativestr, cwd),
1289 1289 env=procutil.tonativeenv(env),
1290 1290 close_fds=procutil.closefds,
1291 1291 stdout=subprocess.PIPE, stderr=errpipe)
1292 1292 if stream:
1293 1293 return p.stdout, None
1294 1294
1295 1295 retdata = p.stdout.read().strip()
1296 1296 # wait for the child to exit to avoid race condition.
1297 1297 p.wait()
1298 1298
1299 1299 if p.returncode != 0 and p.returncode != 1:
1300 1300 # there are certain error codes that are ok
1301 1301 command = commands[0]
1302 1302 if command in ('cat-file', 'symbolic-ref'):
1303 1303 return retdata, p.returncode
1304 1304 # for all others, abort
1305 1305 raise error.Abort(_('git %s error %d in %s') %
1306 1306 (command, p.returncode, self._relpath))
1307 1307
1308 1308 return retdata, p.returncode
1309 1309
1310 1310 def _gitmissing(self):
1311 1311 return not self.wvfs.exists('.git')
1312 1312
1313 1313 def _gitstate(self):
1314 1314 return self._gitcommand(['rev-parse', 'HEAD'])
1315 1315
1316 1316 def _gitcurrentbranch(self):
1317 1317 current, err = self._gitdir(['symbolic-ref', 'HEAD', '--quiet'])
1318 1318 if err:
1319 1319 current = None
1320 1320 return current
1321 1321
1322 1322 def _gitremote(self, remote):
1323 1323 out = self._gitcommand(['remote', 'show', '-n', remote])
1324 1324 line = out.split('\n')[1]
1325 1325 i = line.index('URL: ') + len('URL: ')
1326 1326 return line[i:]
1327 1327
1328 1328 def _githavelocally(self, revision):
1329 1329 out, code = self._gitdir(['cat-file', '-e', revision])
1330 1330 return code == 0
1331 1331
1332 1332 def _gitisancestor(self, r1, r2):
1333 1333 base = self._gitcommand(['merge-base', r1, r2])
1334 1334 return base == r1
1335 1335
1336 1336 def _gitisbare(self):
1337 1337 return self._gitcommand(['config', '--bool', 'core.bare']) == 'true'
1338 1338
1339 1339 def _gitupdatestat(self):
1340 1340 """This must be run before git diff-index.
1341 1341 diff-index only looks at changes to file stat;
1342 1342 this command looks at file contents and updates the stat."""
1343 1343 self._gitcommand(['update-index', '-q', '--refresh'])
1344 1344
1345 1345 def _gitbranchmap(self):
1346 1346 '''returns 2 things:
1347 1347 a map from git branch to revision
1348 1348 a map from revision to branches'''
1349 1349 branch2rev = {}
1350 1350 rev2branch = {}
1351 1351
1352 1352 out = self._gitcommand(['for-each-ref', '--format',
1353 1353 '%(objectname) %(refname)'])
1354 1354 for line in out.split('\n'):
1355 1355 revision, ref = line.split(' ')
1356 1356 if (not ref.startswith('refs/heads/') and
1357 1357 not ref.startswith('refs/remotes/')):
1358 1358 continue
1359 1359 if ref.startswith('refs/remotes/') and ref.endswith('/HEAD'):
1360 1360 continue # ignore remote/HEAD redirects
1361 1361 branch2rev[ref] = revision
1362 1362 rev2branch.setdefault(revision, []).append(ref)
1363 1363 return branch2rev, rev2branch
1364 1364
1365 1365 def _gittracking(self, branches):
1366 1366 'return map of remote branch to local tracking branch'
1367 1367 # assumes no more than one local tracking branch for each remote
1368 1368 tracking = {}
1369 1369 for b in branches:
1370 1370 if b.startswith('refs/remotes/'):
1371 1371 continue
1372 1372 bname = b.split('/', 2)[2]
1373 1373 remote = self._gitcommand(['config', 'branch.%s.remote' % bname])
1374 1374 if remote:
1375 1375 ref = self._gitcommand(['config', 'branch.%s.merge' % bname])
1376 1376 tracking['refs/remotes/%s/%s' %
1377 1377 (remote, ref.split('/', 2)[2])] = b
1378 1378 return tracking
1379 1379
1380 1380 def _abssource(self, source):
1381 1381 if '://' not in source:
1382 1382 # recognize the scp syntax as an absolute source
1383 1383 colon = source.find(':')
1384 1384 if colon != -1 and '/' not in source[:colon]:
1385 1385 return source
1386 1386 self._subsource = source
1387 1387 return _abssource(self)
1388 1388
1389 1389 def _fetch(self, source, revision):
1390 1390 if self._gitmissing():
1391 1391 # SEC: check for safe ssh url
1392 1392 util.checksafessh(source)
1393 1393
1394 1394 source = self._abssource(source)
1395 1395 self.ui.status(_('cloning subrepo %s from %s\n') %
1396 1396 (self._relpath, source))
1397 1397 self._gitnodir(['clone', source, self._abspath])
1398 1398 if self._githavelocally(revision):
1399 1399 return
1400 1400 self.ui.status(_('pulling subrepo %s from %s\n') %
1401 1401 (self._relpath, self._gitremote('origin')))
1402 1402 # try only origin: the originally cloned repo
1403 1403 self._gitcommand(['fetch'])
1404 1404 if not self._githavelocally(revision):
1405 1405 raise error.Abort(_('revision %s does not exist in subrepository '
1406 1406 '"%s"\n') % (revision, self._relpath))
1407 1407
1408 1408 @annotatesubrepoerror
1409 1409 def dirty(self, ignoreupdate=False, missing=False):
1410 1410 if self._gitmissing():
1411 1411 return self._state[1] != ''
1412 1412 if self._gitisbare():
1413 1413 return True
1414 1414 if not ignoreupdate and self._state[1] != self._gitstate():
1415 1415 # different version checked out
1416 1416 return True
1417 1417 # check for staged changes or modified files; ignore untracked files
1418 1418 self._gitupdatestat()
1419 1419 out, code = self._gitdir(['diff-index', '--quiet', 'HEAD'])
1420 1420 return code == 1
1421 1421
1422 1422 def basestate(self):
1423 1423 return self._gitstate()
1424 1424
1425 1425 @annotatesubrepoerror
1426 1426 def get(self, state, overwrite=False):
1427 1427 source, revision, kind = state
1428 1428 if not revision:
1429 1429 self.remove()
1430 1430 return
1431 1431 self._fetch(source, revision)
1432 1432 # if the repo was set to be bare, unbare it
1433 1433 if self._gitisbare():
1434 1434 self._gitcommand(['config', 'core.bare', 'false'])
1435 1435 if self._gitstate() == revision:
1436 1436 self._gitcommand(['reset', '--hard', 'HEAD'])
1437 1437 return
1438 1438 elif self._gitstate() == revision:
1439 1439 if overwrite:
1440 1440 # first reset the index to unmark new files for commit, because
1441 1441 # reset --hard will otherwise throw away files added for commit,
1442 1442 # not just unmark them.
1443 1443 self._gitcommand(['reset', 'HEAD'])
1444 1444 self._gitcommand(['reset', '--hard', 'HEAD'])
1445 1445 return
1446 1446 branch2rev, rev2branch = self._gitbranchmap()
1447 1447
1448 1448 def checkout(args):
1449 1449 cmd = ['checkout']
1450 1450 if overwrite:
1451 1451 # first reset the index to unmark new files for commit, because
1452 1452 # the -f option will otherwise throw away files added for
1453 1453 # commit, not just unmark them.
1454 1454 self._gitcommand(['reset', 'HEAD'])
1455 1455 cmd.append('-f')
1456 1456 self._gitcommand(cmd + args)
1457 1457 _sanitize(self.ui, self.wvfs, '.git')
1458 1458
1459 1459 def rawcheckout():
1460 1460 # no branch to checkout, check it out with no branch
1461 1461 self.ui.warn(_('checking out detached HEAD in '
1462 1462 'subrepository "%s"\n') % self._relpath)
1463 1463 self.ui.warn(_('check out a git branch if you intend '
1464 1464 'to make changes\n'))
1465 1465 checkout(['-q', revision])
1466 1466
1467 1467 if revision not in rev2branch:
1468 1468 rawcheckout()
1469 1469 return
1470 1470 branches = rev2branch[revision]
1471 1471 firstlocalbranch = None
1472 1472 for b in branches:
1473 1473 if b == 'refs/heads/master':
1474 1474 # master trumps all other branches
1475 1475 checkout(['refs/heads/master'])
1476 1476 return
1477 1477 if not firstlocalbranch and not b.startswith('refs/remotes/'):
1478 1478 firstlocalbranch = b
1479 1479 if firstlocalbranch:
1480 1480 checkout([firstlocalbranch])
1481 1481 return
1482 1482
1483 1483 tracking = self._gittracking(branch2rev.keys())
1484 1484 # choose a remote branch already tracked if possible
1485 1485 remote = branches[0]
1486 1486 if remote not in tracking:
1487 1487 for b in branches:
1488 1488 if b in tracking:
1489 1489 remote = b
1490 1490 break
1491 1491
1492 1492 if remote not in tracking:
1493 1493 # create a new local tracking branch
1494 1494 local = remote.split('/', 3)[3]
1495 1495 checkout(['-b', local, remote])
1496 1496 elif self._gitisancestor(branch2rev[tracking[remote]], remote):
1497 1497 # When updating to a tracked remote branch,
1498 1498 # if the local tracking branch is downstream of it,
1499 1499 # a normal `git pull` would have performed a "fast-forward merge"
1500 1500 # which is equivalent to updating the local branch to the remote.
1501 1501 # Since we are only looking at branching at update, we need to
1502 1502 # detect this situation and perform this action lazily.
1503 1503 if tracking[remote] != self._gitcurrentbranch():
1504 1504 checkout([tracking[remote]])
1505 1505 self._gitcommand(['merge', '--ff', remote])
1506 1506 _sanitize(self.ui, self.wvfs, '.git')
1507 1507 else:
1508 1508 # a real merge would be required, just checkout the revision
1509 1509 rawcheckout()
1510 1510
1511 1511 @annotatesubrepoerror
1512 1512 def commit(self, text, user, date):
1513 1513 if self._gitmissing():
1514 1514 raise error.Abort(_("subrepo %s is missing") % self._relpath)
1515 1515 cmd = ['commit', '-a', '-m', text]
1516 1516 env = encoding.environ.copy()
1517 1517 if user:
1518 1518 cmd += ['--author', user]
1519 1519 if date:
1520 1520 # git's date parser silently ignores when seconds < 1e9
1521 1521 # convert to ISO8601
1522 1522 env['GIT_AUTHOR_DATE'] = dateutil.datestr(date,
1523 1523 '%Y-%m-%dT%H:%M:%S %1%2')
1524 1524 self._gitcommand(cmd, env=env)
1525 1525 # make sure commit works otherwise HEAD might not exist under certain
1526 1526 # circumstances
1527 1527 return self._gitstate()
1528 1528
1529 1529 @annotatesubrepoerror
1530 1530 def merge(self, state):
1531 1531 source, revision, kind = state
1532 1532 self._fetch(source, revision)
1533 1533 base = self._gitcommand(['merge-base', revision, self._state[1]])
1534 1534 self._gitupdatestat()
1535 1535 out, code = self._gitdir(['diff-index', '--quiet', 'HEAD'])
1536 1536
1537 1537 def mergefunc():
1538 1538 if base == revision:
1539 1539 self.get(state) # fast forward merge
1540 1540 elif base != self._state[1]:
1541 1541 self._gitcommand(['merge', '--no-commit', revision])
1542 1542 _sanitize(self.ui, self.wvfs, '.git')
1543 1543
1544 1544 if self.dirty():
1545 1545 if self._gitstate() != revision:
1546 1546 dirty = self._gitstate() == self._state[1] or code != 0
1547 1547 if _updateprompt(self.ui, self, dirty,
1548 1548 self._state[1][:7], revision[:7]):
1549 1549 mergefunc()
1550 1550 else:
1551 1551 mergefunc()
1552 1552
1553 1553 @annotatesubrepoerror
1554 1554 def push(self, opts):
1555 1555 force = opts.get('force')
1556 1556
1557 1557 if not self._state[1]:
1558 1558 return True
1559 1559 if self._gitmissing():
1560 1560 raise error.Abort(_("subrepo %s is missing") % self._relpath)
1561 1561 # if a branch in origin contains the revision, nothing to do
1562 1562 branch2rev, rev2branch = self._gitbranchmap()
1563 1563 if self._state[1] in rev2branch:
1564 1564 for b in rev2branch[self._state[1]]:
1565 1565 if b.startswith('refs/remotes/origin/'):
1566 1566 return True
1567 1567 for b, revision in branch2rev.iteritems():
1568 1568 if b.startswith('refs/remotes/origin/'):
1569 1569 if self._gitisancestor(self._state[1], revision):
1570 1570 return True
1571 1571 # otherwise, try to push the currently checked out branch
1572 1572 cmd = ['push']
1573 1573 if force:
1574 1574 cmd.append('--force')
1575 1575
1576 1576 current = self._gitcurrentbranch()
1577 1577 if current:
1578 1578 # determine if the current branch is even useful
1579 1579 if not self._gitisancestor(self._state[1], current):
1580 1580 self.ui.warn(_('unrelated git branch checked out '
1581 1581 'in subrepository "%s"\n') % self._relpath)
1582 1582 return False
1583 1583 self.ui.status(_('pushing branch %s of subrepository "%s"\n') %
1584 1584 (current.split('/', 2)[2], self._relpath))
1585 1585 ret = self._gitdir(cmd + ['origin', current])
1586 1586 return ret[1] == 0
1587 1587 else:
1588 1588 self.ui.warn(_('no branch checked out in subrepository "%s"\n'
1589 1589 'cannot push revision %s\n') %
1590 1590 (self._relpath, self._state[1]))
1591 1591 return False
1592 1592
1593 1593 @annotatesubrepoerror
1594 1594 def add(self, ui, match, prefix, uipathfn, explicitonly, **opts):
1595 1595 if self._gitmissing():
1596 1596 return []
1597 1597
1598 1598 s = self.status(None, unknown=True, clean=True)
1599 1599
1600 1600 tracked = set()
1601 1601 # dirstates 'amn' warn, 'r' is added again
1602 1602 for l in (s.modified, s.added, s.deleted, s.clean):
1603 1603 tracked.update(l)
1604 1604
1605 1605 # Unknown files not of interest will be rejected by the matcher
1606 1606 files = s.unknown
1607 1607 files.extend(match.files())
1608 1608
1609 1609 rejected = []
1610 1610
1611 1611 files = [f for f in sorted(set(files)) if match(f)]
1612 1612 for f in files:
1613 1613 exact = match.exact(f)
1614 1614 command = ["add"]
1615 1615 if exact:
1616 1616 command.append("-f") #should be added, even if ignored
1617 1617 if ui.verbose or not exact:
1618 1618 ui.status(_('adding %s\n') % uipathfn(f))
1619 1619
1620 1620 if f in tracked: # hg prints 'adding' even if already tracked
1621 1621 if exact:
1622 1622 rejected.append(f)
1623 1623 continue
1624 1624 if not opts.get(r'dry_run'):
1625 1625 self._gitcommand(command + [f])
1626 1626
1627 1627 for f in rejected:
1628 1628 ui.warn(_("%s already tracked!\n") % uipathfn(f))
1629 1629
1630 1630 return rejected
1631 1631
1632 1632 @annotatesubrepoerror
1633 1633 def remove(self):
1634 1634 if self._gitmissing():
1635 1635 return
1636 1636 if self.dirty():
1637 1637 self.ui.warn(_('not removing repo %s because '
1638 1638 'it has changes.\n') % self._relpath)
1639 1639 return
1640 1640 # we can't fully delete the repository as it may contain
1641 1641 # local-only history
1642 1642 self.ui.note(_('removing subrepo %s\n') % self._relpath)
1643 1643 self._gitcommand(['config', 'core.bare', 'true'])
1644 1644 for f, kind in self.wvfs.readdir():
1645 1645 if f == '.git':
1646 1646 continue
1647 1647 if kind == stat.S_IFDIR:
1648 1648 self.wvfs.rmtree(f)
1649 1649 else:
1650 1650 self.wvfs.unlink(f)
1651 1651
1652 1652 def archive(self, archiver, prefix, match=None, decode=True):
1653 1653 total = 0
1654 1654 source, revision = self._state
1655 1655 if not revision:
1656 1656 return total
1657 1657 self._fetch(source, revision)
1658 1658
1659 1659 # Parse git's native archive command.
1660 1660 # This should be much faster than manually traversing the trees
1661 1661 # and objects with many subprocess calls.
1662 1662 tarstream = self._gitcommand(['archive', revision], stream=True)
1663 1663 tar = tarfile.open(fileobj=tarstream, mode=r'r|')
1664 1664 relpath = subrelpath(self)
1665 1665 progress = self.ui.makeprogress(_('archiving (%s)') % relpath,
1666 1666 unit=_('files'))
1667 1667 progress.update(0)
1668 1668 for info in tar:
1669 1669 if info.isdir():
1670 1670 continue
1671 1671 bname = pycompat.fsencode(info.name)
1672 1672 if match and not match(bname):
1673 1673 continue
1674 1674 if info.issym():
1675 1675 data = info.linkname
1676 1676 else:
1677 1677 data = tar.extractfile(info).read()
1678 1678 archiver.addfile(prefix + bname, info.mode, info.issym(), data)
1679 1679 total += 1
1680 1680 progress.increment()
1681 1681 progress.complete()
1682 1682 return total
1683 1683
1684 1684
1685 1685 @annotatesubrepoerror
1686 1686 def cat(self, match, fm, fntemplate, prefix, **opts):
1687 1687 rev = self._state[1]
1688 1688 if match.anypats():
1689 1689 return 1 #No support for include/exclude yet
1690 1690
1691 1691 if not match.files():
1692 1692 return 1
1693 1693
1694 1694 # TODO: add support for non-plain formatter (see cmdutil.cat())
1695 1695 for f in match.files():
1696 1696 output = self._gitcommand(["show", "%s:%s" % (rev, f)])
1697 1697 fp = cmdutil.makefileobj(self._ctx, fntemplate,
1698 1698 pathname=self.wvfs.reljoin(prefix, f))
1699 1699 fp.write(output)
1700 1700 fp.close()
1701 1701 return 0
1702 1702
1703 1703
1704 1704 @annotatesubrepoerror
1705 1705 def status(self, rev2, **opts):
1706 1706 rev1 = self._state[1]
1707 1707 if self._gitmissing() or not rev1:
1708 1708 # if the repo is missing, return no results
1709 1709 return scmutil.status([], [], [], [], [], [], [])
1710 1710 modified, added, removed = [], [], []
1711 1711 self._gitupdatestat()
1712 1712 if rev2:
1713 1713 command = ['diff-tree', '--no-renames', '-r', rev1, rev2]
1714 1714 else:
1715 1715 command = ['diff-index', '--no-renames', rev1]
1716 1716 out = self._gitcommand(command)
1717 1717 for line in out.split('\n'):
1718 1718 tab = line.find('\t')
1719 1719 if tab == -1:
1720 1720 continue
1721 1721 status, f = line[tab - 1:tab], line[tab + 1:]
1722 1722 if status == 'M':
1723 1723 modified.append(f)
1724 1724 elif status == 'A':
1725 1725 added.append(f)
1726 1726 elif status == 'D':
1727 1727 removed.append(f)
1728 1728
1729 1729 deleted, unknown, ignored, clean = [], [], [], []
1730 1730
1731 1731 command = ['status', '--porcelain', '-z']
1732 1732 if opts.get(r'unknown'):
1733 1733 command += ['--untracked-files=all']
1734 1734 if opts.get(r'ignored'):
1735 1735 command += ['--ignored']
1736 1736 out = self._gitcommand(command)
1737 1737
1738 1738 changedfiles = set()
1739 1739 changedfiles.update(modified)
1740 1740 changedfiles.update(added)
1741 1741 changedfiles.update(removed)
1742 1742 for line in out.split('\0'):
1743 1743 if not line:
1744 1744 continue
1745 1745 st = line[0:2]
1746 1746 #moves and copies show 2 files on one line
1747 1747 if line.find('\0') >= 0:
1748 1748 filename1, filename2 = line[3:].split('\0')
1749 1749 else:
1750 1750 filename1 = line[3:]
1751 1751 filename2 = None
1752 1752
1753 1753 changedfiles.add(filename1)
1754 1754 if filename2:
1755 1755 changedfiles.add(filename2)
1756 1756
1757 1757 if st == '??':
1758 1758 unknown.append(filename1)
1759 1759 elif st == '!!':
1760 1760 ignored.append(filename1)
1761 1761
1762 1762 if opts.get(r'clean'):
1763 1763 out = self._gitcommand(['ls-files'])
1764 1764 for f in out.split('\n'):
1765 1765 if not f in changedfiles:
1766 1766 clean.append(f)
1767 1767
1768 1768 return scmutil.status(modified, added, removed, deleted,
1769 1769 unknown, ignored, clean)
1770 1770
1771 1771 @annotatesubrepoerror
1772 1772 def diff(self, ui, diffopts, node2, match, prefix, **opts):
1773 1773 node1 = self._state[1]
1774 1774 cmd = ['diff', '--no-renames']
1775 1775 if opts[r'stat']:
1776 1776 cmd.append('--stat')
1777 1777 else:
1778 1778 # for Git, this also implies '-p'
1779 1779 cmd.append('-U%d' % diffopts.context)
1780 1780
1781 1781 if diffopts.noprefix:
1782 1782 cmd.extend(['--src-prefix=%s/' % prefix,
1783 1783 '--dst-prefix=%s/' % prefix])
1784 1784 else:
1785 1785 cmd.extend(['--src-prefix=a/%s/' % prefix,
1786 1786 '--dst-prefix=b/%s/' % prefix])
1787 1787
1788 1788 if diffopts.ignorews:
1789 1789 cmd.append('--ignore-all-space')
1790 1790 if diffopts.ignorewsamount:
1791 1791 cmd.append('--ignore-space-change')
1792 1792 if self._gitversion(self._gitcommand(['--version'])) >= (1, 8, 4) \
1793 1793 and diffopts.ignoreblanklines:
1794 1794 cmd.append('--ignore-blank-lines')
1795 1795
1796 1796 cmd.append(node1)
1797 1797 if node2:
1798 1798 cmd.append(node2)
1799 1799
1800 1800 output = ""
1801 1801 if match.always():
1802 1802 output += self._gitcommand(cmd) + '\n'
1803 1803 else:
1804 1804 st = self.status(node2)[:3]
1805 1805 files = [f for sublist in st for f in sublist]
1806 1806 for f in files:
1807 1807 if match(f):
1808 1808 output += self._gitcommand(cmd + ['--', f]) + '\n'
1809 1809
1810 1810 if output.strip():
1811 1811 ui.write(output)
1812 1812
1813 1813 @annotatesubrepoerror
1814 1814 def revert(self, substate, *pats, **opts):
1815 1815 self.ui.status(_('reverting subrepo %s\n') % substate[0])
1816 1816 if not opts.get(r'no_backup'):
1817 1817 status = self.status(None)
1818 1818 names = status.modified
1819 1819 for name in names:
1820 1820 # backuppath() expects a path relative to the parent repo (the
1821 1821 # repo that ui.origbackuppath is relative to)
1822 1822 parentname = os.path.join(self._path, name)
1823 1823 bakname = scmutil.backuppath(self.ui, self._subparent,
1824 1824 parentname)
1825 1825 self.ui.note(_('saving current version of %s as %s\n') %
1826 1826 (name, os.path.relpath(bakname)))
1827 1827 util.rename(self.wvfs.join(name), bakname)
1828 1828
1829 1829 if not opts.get(r'dry_run'):
1830 1830 self.get(substate, overwrite=True)
1831 1831 return []
1832 1832
1833 1833 def shortid(self, revid):
1834 1834 return revid[:7]
1835 1835
1836 1836 types = {
1837 1837 'hg': hgsubrepo,
1838 1838 'svn': svnsubrepo,
1839 1839 'git': gitsubrepo,
1840 1840 }
General Comments 0
You need to be logged in to leave comments. Login now