##// END OF EJS Templates
merge: use collections.defaultdict() for mergeresult.commitinfo...
Pulkit Goyal -
r45943:f970cca3 default
parent child Browse files
Show More
@@ -1,2263 +1,2263 b''
1 1 # merge.py - directory-level update/merge handling for Mercurial
2 2 #
3 3 # Copyright 2006, 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 collections
11 11 import errno
12 12 import stat
13 13 import struct
14 14
15 15 from .i18n import _
16 16 from .node import (
17 17 addednodeid,
18 18 modifiednodeid,
19 19 nullid,
20 20 nullrev,
21 21 )
22 22 from .thirdparty import attr
23 23 from . import (
24 24 copies,
25 25 encoding,
26 26 error,
27 27 filemerge,
28 28 match as matchmod,
29 29 mergestate as mergestatemod,
30 30 obsutil,
31 31 pathutil,
32 32 pycompat,
33 33 scmutil,
34 34 subrepoutil,
35 35 util,
36 36 worker,
37 37 )
38 38
39 39 _pack = struct.pack
40 40 _unpack = struct.unpack
41 41
42 42
43 43 def _getcheckunknownconfig(repo, section, name):
44 44 config = repo.ui.config(section, name)
45 45 valid = [b'abort', b'ignore', b'warn']
46 46 if config not in valid:
47 47 validstr = b', '.join([b"'" + v + b"'" for v in valid])
48 48 raise error.ConfigError(
49 49 _(b"%s.%s not valid ('%s' is none of %s)")
50 50 % (section, name, config, validstr)
51 51 )
52 52 return config
53 53
54 54
55 55 def _checkunknownfile(repo, wctx, mctx, f, f2=None):
56 56 if wctx.isinmemory():
57 57 # Nothing to do in IMM because nothing in the "working copy" can be an
58 58 # unknown file.
59 59 #
60 60 # Note that we should bail out here, not in ``_checkunknownfiles()``,
61 61 # because that function does other useful work.
62 62 return False
63 63
64 64 if f2 is None:
65 65 f2 = f
66 66 return (
67 67 repo.wvfs.audit.check(f)
68 68 and repo.wvfs.isfileorlink(f)
69 69 and repo.dirstate.normalize(f) not in repo.dirstate
70 70 and mctx[f2].cmp(wctx[f])
71 71 )
72 72
73 73
74 74 class _unknowndirschecker(object):
75 75 """
76 76 Look for any unknown files or directories that may have a path conflict
77 77 with a file. If any path prefix of the file exists as a file or link,
78 78 then it conflicts. If the file itself is a directory that contains any
79 79 file that is not tracked, then it conflicts.
80 80
81 81 Returns the shortest path at which a conflict occurs, or None if there is
82 82 no conflict.
83 83 """
84 84
85 85 def __init__(self):
86 86 # A set of paths known to be good. This prevents repeated checking of
87 87 # dirs. It will be updated with any new dirs that are checked and found
88 88 # to be safe.
89 89 self._unknowndircache = set()
90 90
91 91 # A set of paths that are known to be absent. This prevents repeated
92 92 # checking of subdirectories that are known not to exist. It will be
93 93 # updated with any new dirs that are checked and found to be absent.
94 94 self._missingdircache = set()
95 95
96 96 def __call__(self, repo, wctx, f):
97 97 if wctx.isinmemory():
98 98 # Nothing to do in IMM for the same reason as ``_checkunknownfile``.
99 99 return False
100 100
101 101 # Check for path prefixes that exist as unknown files.
102 102 for p in reversed(list(pathutil.finddirs(f))):
103 103 if p in self._missingdircache:
104 104 return
105 105 if p in self._unknowndircache:
106 106 continue
107 107 if repo.wvfs.audit.check(p):
108 108 if (
109 109 repo.wvfs.isfileorlink(p)
110 110 and repo.dirstate.normalize(p) not in repo.dirstate
111 111 ):
112 112 return p
113 113 if not repo.wvfs.lexists(p):
114 114 self._missingdircache.add(p)
115 115 return
116 116 self._unknowndircache.add(p)
117 117
118 118 # Check if the file conflicts with a directory containing unknown files.
119 119 if repo.wvfs.audit.check(f) and repo.wvfs.isdir(f):
120 120 # Does the directory contain any files that are not in the dirstate?
121 121 for p, dirs, files in repo.wvfs.walk(f):
122 122 for fn in files:
123 123 relf = util.pconvert(repo.wvfs.reljoin(p, fn))
124 124 relf = repo.dirstate.normalize(relf, isknown=True)
125 125 if relf not in repo.dirstate:
126 126 return f
127 127 return None
128 128
129 129
130 130 def _checkunknownfiles(repo, wctx, mctx, force, mresult, mergeforce):
131 131 """
132 132 Considers any actions that care about the presence of conflicting unknown
133 133 files. For some actions, the result is to abort; for others, it is to
134 134 choose a different action.
135 135 """
136 136 fileconflicts = set()
137 137 pathconflicts = set()
138 138 warnconflicts = set()
139 139 abortconflicts = set()
140 140 unknownconfig = _getcheckunknownconfig(repo, b'merge', b'checkunknown')
141 141 ignoredconfig = _getcheckunknownconfig(repo, b'merge', b'checkignored')
142 142 pathconfig = repo.ui.configbool(
143 143 b'experimental', b'merge.checkpathconflicts'
144 144 )
145 145 if not force:
146 146
147 147 def collectconflicts(conflicts, config):
148 148 if config == b'abort':
149 149 abortconflicts.update(conflicts)
150 150 elif config == b'warn':
151 151 warnconflicts.update(conflicts)
152 152
153 153 checkunknowndirs = _unknowndirschecker()
154 154 for f in mresult.files(
155 155 (
156 156 mergestatemod.ACTION_CREATED,
157 157 mergestatemod.ACTION_DELETED_CHANGED,
158 158 )
159 159 ):
160 160 if _checkunknownfile(repo, wctx, mctx, f):
161 161 fileconflicts.add(f)
162 162 elif pathconfig and f not in wctx:
163 163 path = checkunknowndirs(repo, wctx, f)
164 164 if path is not None:
165 165 pathconflicts.add(path)
166 166 for f, args, msg in mresult.getactions(
167 167 [mergestatemod.ACTION_LOCAL_DIR_RENAME_GET]
168 168 ):
169 169 if _checkunknownfile(repo, wctx, mctx, f, args[0]):
170 170 fileconflicts.add(f)
171 171
172 172 allconflicts = fileconflicts | pathconflicts
173 173 ignoredconflicts = {c for c in allconflicts if repo.dirstate._ignore(c)}
174 174 unknownconflicts = allconflicts - ignoredconflicts
175 175 collectconflicts(ignoredconflicts, ignoredconfig)
176 176 collectconflicts(unknownconflicts, unknownconfig)
177 177 else:
178 178 for f, args, msg in list(
179 179 mresult.getactions([mergestatemod.ACTION_CREATED_MERGE])
180 180 ):
181 181 fl2, anc = args
182 182 different = _checkunknownfile(repo, wctx, mctx, f)
183 183 if repo.dirstate._ignore(f):
184 184 config = ignoredconfig
185 185 else:
186 186 config = unknownconfig
187 187
188 188 # The behavior when force is True is described by this table:
189 189 # config different mergeforce | action backup
190 190 # * n * | get n
191 191 # * y y | merge -
192 192 # abort y n | merge - (1)
193 193 # warn y n | warn + get y
194 194 # ignore y n | get y
195 195 #
196 196 # (1) this is probably the wrong behavior here -- we should
197 197 # probably abort, but some actions like rebases currently
198 198 # don't like an abort happening in the middle of
199 199 # merge.update.
200 200 if not different:
201 201 mresult.addfile(
202 202 f,
203 203 mergestatemod.ACTION_GET,
204 204 (fl2, False),
205 205 b'remote created',
206 206 )
207 207 elif mergeforce or config == b'abort':
208 208 mresult.addfile(
209 209 f,
210 210 mergestatemod.ACTION_MERGE,
211 211 (f, f, None, False, anc),
212 212 b'remote differs from untracked local',
213 213 )
214 214 elif config == b'abort':
215 215 abortconflicts.add(f)
216 216 else:
217 217 if config == b'warn':
218 218 warnconflicts.add(f)
219 219 mresult.addfile(
220 220 f, mergestatemod.ACTION_GET, (fl2, True), b'remote created',
221 221 )
222 222
223 223 for f in sorted(abortconflicts):
224 224 warn = repo.ui.warn
225 225 if f in pathconflicts:
226 226 if repo.wvfs.isfileorlink(f):
227 227 warn(_(b"%s: untracked file conflicts with directory\n") % f)
228 228 else:
229 229 warn(_(b"%s: untracked directory conflicts with file\n") % f)
230 230 else:
231 231 warn(_(b"%s: untracked file differs\n") % f)
232 232 if abortconflicts:
233 233 raise error.Abort(
234 234 _(
235 235 b"untracked files in working directory "
236 236 b"differ from files in requested revision"
237 237 )
238 238 )
239 239
240 240 for f in sorted(warnconflicts):
241 241 if repo.wvfs.isfileorlink(f):
242 242 repo.ui.warn(_(b"%s: replacing untracked file\n") % f)
243 243 else:
244 244 repo.ui.warn(_(b"%s: replacing untracked files in directory\n") % f)
245 245
246 246 for f, args, msg in list(
247 247 mresult.getactions([mergestatemod.ACTION_CREATED])
248 248 ):
249 249 backup = (
250 250 f in fileconflicts
251 251 or f in pathconflicts
252 252 or any(p in pathconflicts for p in pathutil.finddirs(f))
253 253 )
254 254 (flags,) = args
255 255 mresult.addfile(f, mergestatemod.ACTION_GET, (flags, backup), msg)
256 256
257 257
258 258 def _forgetremoved(wctx, mctx, branchmerge, mresult):
259 259 """
260 260 Forget removed files
261 261
262 262 If we're jumping between revisions (as opposed to merging), and if
263 263 neither the working directory nor the target rev has the file,
264 264 then we need to remove it from the dirstate, to prevent the
265 265 dirstate from listing the file when it is no longer in the
266 266 manifest.
267 267
268 268 If we're merging, and the other revision has removed a file
269 269 that is not present in the working directory, we need to mark it
270 270 as removed.
271 271 """
272 272
273 273 m = mergestatemod.ACTION_FORGET
274 274 if branchmerge:
275 275 m = mergestatemod.ACTION_REMOVE
276 276 for f in wctx.deleted():
277 277 if f not in mctx:
278 278 mresult.addfile(f, m, None, b"forget deleted")
279 279
280 280 if not branchmerge:
281 281 for f in wctx.removed():
282 282 if f not in mctx:
283 283 mresult.addfile(
284 284 f, mergestatemod.ACTION_FORGET, None, b"forget removed",
285 285 )
286 286
287 287
288 288 def _checkcollision(repo, wmf, mresult):
289 289 """
290 290 Check for case-folding collisions.
291 291 """
292 292 # If the repo is narrowed, filter out files outside the narrowspec.
293 293 narrowmatch = repo.narrowmatch()
294 294 if not narrowmatch.always():
295 295 pmmf = set(wmf.walk(narrowmatch))
296 296 if mresult:
297 297 for f in list(mresult.files()):
298 298 if not narrowmatch(f):
299 299 mresult.removefile(f)
300 300 else:
301 301 # build provisional merged manifest up
302 302 pmmf = set(wmf)
303 303
304 304 if mresult:
305 305 # KEEP and EXEC are no-op
306 306 for f in mresult.files(
307 307 (
308 308 mergestatemod.ACTION_ADD,
309 309 mergestatemod.ACTION_ADD_MODIFIED,
310 310 mergestatemod.ACTION_FORGET,
311 311 mergestatemod.ACTION_GET,
312 312 mergestatemod.ACTION_CHANGED_DELETED,
313 313 mergestatemod.ACTION_DELETED_CHANGED,
314 314 )
315 315 ):
316 316 pmmf.add(f)
317 317 for f in mresult.files((mergestatemod.ACTION_REMOVE,)):
318 318 pmmf.discard(f)
319 319 for f, args, msg in mresult.getactions(
320 320 [mergestatemod.ACTION_DIR_RENAME_MOVE_LOCAL]
321 321 ):
322 322 f2, flags = args
323 323 pmmf.discard(f2)
324 324 pmmf.add(f)
325 325 for f in mresult.files((mergestatemod.ACTION_LOCAL_DIR_RENAME_GET,)):
326 326 pmmf.add(f)
327 327 for f, args, msg in mresult.getactions([mergestatemod.ACTION_MERGE]):
328 328 f1, f2, fa, move, anc = args
329 329 if move:
330 330 pmmf.discard(f1)
331 331 pmmf.add(f)
332 332
333 333 # check case-folding collision in provisional merged manifest
334 334 foldmap = {}
335 335 for f in pmmf:
336 336 fold = util.normcase(f)
337 337 if fold in foldmap:
338 338 raise error.Abort(
339 339 _(b"case-folding collision between %s and %s")
340 340 % (f, foldmap[fold])
341 341 )
342 342 foldmap[fold] = f
343 343
344 344 # check case-folding of directories
345 345 foldprefix = unfoldprefix = lastfull = b''
346 346 for fold, f in sorted(foldmap.items()):
347 347 if fold.startswith(foldprefix) and not f.startswith(unfoldprefix):
348 348 # the folded prefix matches but actual casing is different
349 349 raise error.Abort(
350 350 _(b"case-folding collision between %s and directory of %s")
351 351 % (lastfull, f)
352 352 )
353 353 foldprefix = fold + b'/'
354 354 unfoldprefix = f + b'/'
355 355 lastfull = f
356 356
357 357
358 358 def driverpreprocess(repo, ms, wctx, labels=None):
359 359 """run the preprocess step of the merge driver, if any
360 360
361 361 This is currently not implemented -- it's an extension point."""
362 362 return True
363 363
364 364
365 365 def driverconclude(repo, ms, wctx, labels=None):
366 366 """run the conclude step of the merge driver, if any
367 367
368 368 This is currently not implemented -- it's an extension point."""
369 369 return True
370 370
371 371
372 372 def _filesindirs(repo, manifest, dirs):
373 373 """
374 374 Generator that yields pairs of all the files in the manifest that are found
375 375 inside the directories listed in dirs, and which directory they are found
376 376 in.
377 377 """
378 378 for f in manifest:
379 379 for p in pathutil.finddirs(f):
380 380 if p in dirs:
381 381 yield f, p
382 382 break
383 383
384 384
385 385 def checkpathconflicts(repo, wctx, mctx, mresult):
386 386 """
387 387 Check if any actions introduce path conflicts in the repository, updating
388 388 actions to record or handle the path conflict accordingly.
389 389 """
390 390 mf = wctx.manifest()
391 391
392 392 # The set of local files that conflict with a remote directory.
393 393 localconflicts = set()
394 394
395 395 # The set of directories that conflict with a remote file, and so may cause
396 396 # conflicts if they still contain any files after the merge.
397 397 remoteconflicts = set()
398 398
399 399 # The set of directories that appear as both a file and a directory in the
400 400 # remote manifest. These indicate an invalid remote manifest, which
401 401 # can't be updated to cleanly.
402 402 invalidconflicts = set()
403 403
404 404 # The set of directories that contain files that are being created.
405 405 createdfiledirs = set()
406 406
407 407 # The set of files deleted by all the actions.
408 408 deletedfiles = set()
409 409
410 410 for f in mresult.files(
411 411 (
412 412 mergestatemod.ACTION_CREATED,
413 413 mergestatemod.ACTION_DELETED_CHANGED,
414 414 mergestatemod.ACTION_MERGE,
415 415 mergestatemod.ACTION_CREATED_MERGE,
416 416 )
417 417 ):
418 418 # This action may create a new local file.
419 419 createdfiledirs.update(pathutil.finddirs(f))
420 420 if mf.hasdir(f):
421 421 # The file aliases a local directory. This might be ok if all
422 422 # the files in the local directory are being deleted. This
423 423 # will be checked once we know what all the deleted files are.
424 424 remoteconflicts.add(f)
425 425 # Track the names of all deleted files.
426 426 for f in mresult.files((mergestatemod.ACTION_REMOVE,)):
427 427 deletedfiles.add(f)
428 428 for (f, args, msg) in mresult.getactions((mergestatemod.ACTION_MERGE,)):
429 429 f1, f2, fa, move, anc = args
430 430 if move:
431 431 deletedfiles.add(f1)
432 432 for (f, args, msg) in mresult.getactions(
433 433 (mergestatemod.ACTION_DIR_RENAME_MOVE_LOCAL,)
434 434 ):
435 435 f2, flags = args
436 436 deletedfiles.add(f2)
437 437
438 438 # Check all directories that contain created files for path conflicts.
439 439 for p in createdfiledirs:
440 440 if p in mf:
441 441 if p in mctx:
442 442 # A file is in a directory which aliases both a local
443 443 # and a remote file. This is an internal inconsistency
444 444 # within the remote manifest.
445 445 invalidconflicts.add(p)
446 446 else:
447 447 # A file is in a directory which aliases a local file.
448 448 # We will need to rename the local file.
449 449 localconflicts.add(p)
450 450 pd = mresult.getfile(p)
451 451 if pd and pd[0] in (
452 452 mergestatemod.ACTION_CREATED,
453 453 mergestatemod.ACTION_DELETED_CHANGED,
454 454 mergestatemod.ACTION_MERGE,
455 455 mergestatemod.ACTION_CREATED_MERGE,
456 456 ):
457 457 # The file is in a directory which aliases a remote file.
458 458 # This is an internal inconsistency within the remote
459 459 # manifest.
460 460 invalidconflicts.add(p)
461 461
462 462 # Rename all local conflicting files that have not been deleted.
463 463 for p in localconflicts:
464 464 if p not in deletedfiles:
465 465 ctxname = bytes(wctx).rstrip(b'+')
466 466 pnew = util.safename(p, ctxname, wctx, set(mresult.files()))
467 467 porig = wctx[p].copysource() or p
468 468 mresult.addfile(
469 469 pnew,
470 470 mergestatemod.ACTION_PATH_CONFLICT_RESOLVE,
471 471 (p, porig),
472 472 b'local path conflict',
473 473 )
474 474 mresult.addfile(
475 475 p,
476 476 mergestatemod.ACTION_PATH_CONFLICT,
477 477 (pnew, b'l'),
478 478 b'path conflict',
479 479 )
480 480
481 481 if remoteconflicts:
482 482 # Check if all files in the conflicting directories have been removed.
483 483 ctxname = bytes(mctx).rstrip(b'+')
484 484 for f, p in _filesindirs(repo, mf, remoteconflicts):
485 485 if f not in deletedfiles:
486 486 m, args, msg = mresult.getfile(p)
487 487 pnew = util.safename(p, ctxname, wctx, set(mresult.files()))
488 488 if m in (
489 489 mergestatemod.ACTION_DELETED_CHANGED,
490 490 mergestatemod.ACTION_MERGE,
491 491 ):
492 492 # Action was merge, just update target.
493 493 mresult.addfile(pnew, m, args, msg)
494 494 else:
495 495 # Action was create, change to renamed get action.
496 496 fl = args[0]
497 497 mresult.addfile(
498 498 pnew,
499 499 mergestatemod.ACTION_LOCAL_DIR_RENAME_GET,
500 500 (p, fl),
501 501 b'remote path conflict',
502 502 )
503 503 mresult.addfile(
504 504 p,
505 505 mergestatemod.ACTION_PATH_CONFLICT,
506 506 (pnew, mergestatemod.ACTION_REMOVE),
507 507 b'path conflict',
508 508 )
509 509 remoteconflicts.remove(p)
510 510 break
511 511
512 512 if invalidconflicts:
513 513 for p in invalidconflicts:
514 514 repo.ui.warn(_(b"%s: is both a file and a directory\n") % p)
515 515 raise error.Abort(_(b"destination manifest contains path conflicts"))
516 516
517 517
518 518 def _filternarrowactions(narrowmatch, branchmerge, mresult):
519 519 """
520 520 Filters out actions that can ignored because the repo is narrowed.
521 521
522 522 Raise an exception if the merge cannot be completed because the repo is
523 523 narrowed.
524 524 """
525 525 # TODO: handle with nonconflicttypes
526 526 nooptypes = {mergestatemod.ACTION_KEEP}
527 527 nonconflicttypes = {
528 528 mergestatemod.ACTION_ADD,
529 529 mergestatemod.ACTION_ADD_MODIFIED,
530 530 mergestatemod.ACTION_CREATED,
531 531 mergestatemod.ACTION_CREATED_MERGE,
532 532 mergestatemod.ACTION_FORGET,
533 533 mergestatemod.ACTION_GET,
534 534 mergestatemod.ACTION_REMOVE,
535 535 mergestatemod.ACTION_EXEC,
536 536 }
537 537 # We mutate the items in the dict during iteration, so iterate
538 538 # over a copy.
539 539 for f, action in mresult.filemap():
540 540 if narrowmatch(f):
541 541 pass
542 542 elif not branchmerge:
543 543 mresult.removefile(f) # just updating, ignore changes outside clone
544 544 elif action[0] in nooptypes:
545 545 mresult.removefile(f) # merge does not affect file
546 546 elif action[0] in nonconflicttypes:
547 547 raise error.Abort(
548 548 _(
549 549 b'merge affects file \'%s\' outside narrow, '
550 550 b'which is not yet supported'
551 551 )
552 552 % f,
553 553 hint=_(b'merging in the other direction may work'),
554 554 )
555 555 else:
556 556 raise error.Abort(
557 557 _(b'conflict in file \'%s\' is outside narrow clone') % f
558 558 )
559 559
560 560
561 561 class mergeresult(object):
562 562 ''''An object representing result of merging manifests.
563 563
564 564 It has information about what actions need to be performed on dirstate
565 565 mapping of divergent renames and other such cases. '''
566 566
567 567 def __init__(self):
568 568 """
569 569 filemapping: dict of filename as keys and action related info as values
570 570 diverge: mapping of source name -> list of dest name for
571 571 divergent renames
572 572 renamedelete: mapping of source name -> list of destinations for files
573 573 deleted on one side and renamed on other.
574 574 commitinfo: dict containing data which should be used on commit
575 575 contains a filename -> info mapping
576 576 actionmapping: dict of action names as keys and values are dict of
577 577 filename as key and related data as values
578 578 """
579 579 self._filemapping = {}
580 580 self._diverge = {}
581 581 self._renamedelete = {}
582 self._commitinfo = {}
582 self._commitinfo = collections.defaultdict(dict)
583 583 self._actionmapping = collections.defaultdict(dict)
584 584
585 585 def updatevalues(self, diverge, renamedelete, commitinfo):
586 586 self._diverge = diverge
587 587 self._renamedelete = renamedelete
588 588 self._commitinfo = commitinfo
589 589
590 590 def addfile(self, filename, action, data, message):
591 591 """ adds a new file to the mergeresult object
592 592
593 593 filename: file which we are adding
594 594 action: one of mergestatemod.ACTION_*
595 595 data: a tuple of information like fctx and ctx related to this merge
596 596 message: a message about the merge
597 597 """
598 598 # if the file already existed, we need to delete it's old
599 599 # entry form _actionmapping too
600 600 if filename in self._filemapping:
601 601 a, d, m = self._filemapping[filename]
602 602 del self._actionmapping[a][filename]
603 603
604 604 self._filemapping[filename] = (action, data, message)
605 605 self._actionmapping[action][filename] = (data, message)
606 606
607 607 def getfile(self, filename, default_return=None):
608 608 """ returns (action, args, msg) about this file
609 609
610 610 returns default_return if the file is not present """
611 611 if filename in self._filemapping:
612 612 return self._filemapping[filename]
613 613 return default_return
614 614
615 615 def files(self, actions=None):
616 616 """ returns files on which provided action needs to perfromed
617 617
618 618 If actions is None, all files are returned
619 619 """
620 620 # TODO: think whether we should return renamedelete and
621 621 # diverge filenames also
622 622 if actions is None:
623 623 for f in self._filemapping:
624 624 yield f
625 625
626 626 else:
627 627 for a in actions:
628 628 for f in self._actionmapping[a]:
629 629 yield f
630 630
631 631 def removefile(self, filename):
632 632 """ removes a file from the mergeresult object as the file might
633 633 not merging anymore """
634 634 action, data, message = self._filemapping[filename]
635 635 del self._filemapping[filename]
636 636 del self._actionmapping[action][filename]
637 637
638 638 def getactions(self, actions, sort=False):
639 639 """ get list of files which are marked with these actions
640 640 if sort is true, files for each action is sorted and then added
641 641
642 642 Returns a list of tuple of form (filename, data, message)
643 643 """
644 644 for a in actions:
645 645 if sort:
646 646 for f in sorted(self._actionmapping[a]):
647 647 args, msg = self._actionmapping[a][f]
648 648 yield f, args, msg
649 649 else:
650 650 for f, (args, msg) in pycompat.iteritems(
651 651 self._actionmapping[a]
652 652 ):
653 653 yield f, args, msg
654 654
655 655 def len(self, actions=None):
656 656 """ returns number of files which needs actions
657 657
658 658 if actions is passed, total of number of files in that action
659 659 only is returned """
660 660
661 661 if actions is None:
662 662 return len(self._filemapping)
663 663
664 664 return sum(len(self._actionmapping[a]) for a in actions)
665 665
666 666 def filemap(self, sort=False):
667 667 if sorted:
668 668 for key, val in sorted(pycompat.iteritems(self._filemapping)):
669 669 yield key, val
670 670 else:
671 671 for key, val in pycompat.iteritems(self._filemapping):
672 672 yield key, val
673 673
674 674 @property
675 675 def diverge(self):
676 676 return self._diverge
677 677
678 678 @property
679 679 def renamedelete(self):
680 680 return self._renamedelete
681 681
682 682 @property
683 683 def commitinfo(self):
684 684 return self._commitinfo
685 685
686 686 @property
687 687 def actionsdict(self):
688 688 """ returns a dictionary of actions to be perfomed with action as key
689 689 and a list of files and related arguments as values """
690 690 res = collections.defaultdict(list)
691 691 for a, d in pycompat.iteritems(self._actionmapping):
692 692 for f, (args, msg) in pycompat.iteritems(d):
693 693 res[a].append((f, args, msg))
694 694 return res
695 695
696 696 def setactions(self, actions):
697 697 self._filemapping = actions
698 698 self._actionmapping = collections.defaultdict(dict)
699 699 for f, (act, data, msg) in pycompat.iteritems(self._filemapping):
700 700 self._actionmapping[act][f] = data, msg
701 701
702 702 def hasconflicts(self):
703 703 """ tells whether this merge resulted in some actions which can
704 704 result in conflicts or not """
705 705 for a in self._actionmapping.keys():
706 706 if (
707 707 a
708 708 not in (
709 709 mergestatemod.ACTION_GET,
710 710 mergestatemod.ACTION_KEEP,
711 711 mergestatemod.ACTION_EXEC,
712 712 mergestatemod.ACTION_REMOVE,
713 713 mergestatemod.ACTION_PATH_CONFLICT_RESOLVE,
714 714 )
715 715 and self._actionmapping[a]
716 716 ):
717 717 return True
718 718
719 719 return False
720 720
721 721
722 722 def manifestmerge(
723 723 repo,
724 724 wctx,
725 725 p2,
726 726 pa,
727 727 branchmerge,
728 728 force,
729 729 matcher,
730 730 acceptremote,
731 731 followcopies,
732 732 forcefulldiff=False,
733 733 ):
734 734 """
735 735 Merge wctx and p2 with ancestor pa and generate merge action list
736 736
737 737 branchmerge and force are as passed in to update
738 738 matcher = matcher to filter file lists
739 739 acceptremote = accept the incoming changes without prompting
740 740
741 741 Returns an object of mergeresult class
742 742 """
743 743 mresult = mergeresult()
744 744 if matcher is not None and matcher.always():
745 745 matcher = None
746 746
747 747 # manifests fetched in order are going to be faster, so prime the caches
748 748 [
749 749 x.manifest()
750 750 for x in sorted(wctx.parents() + [p2, pa], key=scmutil.intrev)
751 751 ]
752 752
753 753 branch_copies1 = copies.branch_copies()
754 754 branch_copies2 = copies.branch_copies()
755 755 diverge = {}
756 756 # information from merge which is needed at commit time
757 757 # for example choosing filelog of which parent to commit
758 758 # TODO: use specific constants in future for this mapping
759 commitinfo = {}
759 commitinfo = collections.defaultdict(dict)
760 760 if followcopies:
761 761 branch_copies1, branch_copies2, diverge = copies.mergecopies(
762 762 repo, wctx, p2, pa
763 763 )
764 764
765 765 boolbm = pycompat.bytestr(bool(branchmerge))
766 766 boolf = pycompat.bytestr(bool(force))
767 767 boolm = pycompat.bytestr(bool(matcher))
768 768 repo.ui.note(_(b"resolving manifests\n"))
769 769 repo.ui.debug(
770 770 b" branchmerge: %s, force: %s, partial: %s\n" % (boolbm, boolf, boolm)
771 771 )
772 772 repo.ui.debug(b" ancestor: %s, local: %s, remote: %s\n" % (pa, wctx, p2))
773 773
774 774 m1, m2, ma = wctx.manifest(), p2.manifest(), pa.manifest()
775 775 copied1 = set(branch_copies1.copy.values())
776 776 copied1.update(branch_copies1.movewithdir.values())
777 777 copied2 = set(branch_copies2.copy.values())
778 778 copied2.update(branch_copies2.movewithdir.values())
779 779
780 780 if b'.hgsubstate' in m1 and wctx.rev() is None:
781 781 # Check whether sub state is modified, and overwrite the manifest
782 782 # to flag the change. If wctx is a committed revision, we shouldn't
783 783 # care for the dirty state of the working directory.
784 784 if any(wctx.sub(s).dirty() for s in wctx.substate):
785 785 m1[b'.hgsubstate'] = modifiednodeid
786 786
787 787 # Don't use m2-vs-ma optimization if:
788 788 # - ma is the same as m1 or m2, which we're just going to diff again later
789 789 # - The caller specifically asks for a full diff, which is useful during bid
790 790 # merge.
791 791 if pa not in ([wctx, p2] + wctx.parents()) and not forcefulldiff:
792 792 # Identify which files are relevant to the merge, so we can limit the
793 793 # total m1-vs-m2 diff to just those files. This has significant
794 794 # performance benefits in large repositories.
795 795 relevantfiles = set(ma.diff(m2).keys())
796 796
797 797 # For copied and moved files, we need to add the source file too.
798 798 for copykey, copyvalue in pycompat.iteritems(branch_copies1.copy):
799 799 if copyvalue in relevantfiles:
800 800 relevantfiles.add(copykey)
801 801 for movedirkey in branch_copies1.movewithdir:
802 802 relevantfiles.add(movedirkey)
803 803 filesmatcher = scmutil.matchfiles(repo, relevantfiles)
804 804 matcher = matchmod.intersectmatchers(matcher, filesmatcher)
805 805
806 806 diff = m1.diff(m2, match=matcher)
807 807
808 808 for f, ((n1, fl1), (n2, fl2)) in pycompat.iteritems(diff):
809 809 if n1 and n2: # file exists on both local and remote side
810 810 if f not in ma:
811 811 # TODO: what if they're renamed from different sources?
812 812 fa = branch_copies1.copy.get(
813 813 f, None
814 814 ) or branch_copies2.copy.get(f, None)
815 815 args, msg = None, None
816 816 if fa is not None:
817 817 args = (f, f, fa, False, pa.node())
818 818 msg = b'both renamed from %s' % fa
819 819 else:
820 820 args = (f, f, None, False, pa.node())
821 821 msg = b'both created'
822 822 mresult.addfile(f, mergestatemod.ACTION_MERGE, args, msg)
823 823 else:
824 824 a = ma[f]
825 825 fla = ma.flags(f)
826 826 nol = b'l' not in fl1 + fl2 + fla
827 827 if n2 == a and fl2 == fla:
828 828 mresult.addfile(
829 829 f, mergestatemod.ACTION_KEEP, (), b'remote unchanged',
830 830 )
831 831 elif n1 == a and fl1 == fla: # local unchanged - use remote
832 832 if n1 == n2: # optimization: keep local content
833 833 mresult.addfile(
834 834 f,
835 835 mergestatemod.ACTION_EXEC,
836 836 (fl2,),
837 837 b'update permissions',
838 838 )
839 839 else:
840 840 mresult.addfile(
841 841 f,
842 842 mergestatemod.ACTION_GET,
843 843 (fl2, False),
844 844 b'remote is newer',
845 845 )
846 846 if branchmerge:
847 commitinfo[f] = b'other'
847 commitinfo[f][b'filenode-source'] = b'other'
848 848 elif nol and n2 == a: # remote only changed 'x'
849 849 mresult.addfile(
850 850 f,
851 851 mergestatemod.ACTION_EXEC,
852 852 (fl2,),
853 853 b'update permissions',
854 854 )
855 855 elif nol and n1 == a: # local only changed 'x'
856 856 mresult.addfile(
857 857 f,
858 858 mergestatemod.ACTION_GET,
859 859 (fl1, False),
860 860 b'remote is newer',
861 861 )
862 862 if branchmerge:
863 commitinfo[f] = b'other'
863 commitinfo[f][b'filenode-source'] = b'other'
864 864 else: # both changed something
865 865 mresult.addfile(
866 866 f,
867 867 mergestatemod.ACTION_MERGE,
868 868 (f, f, f, False, pa.node()),
869 869 b'versions differ',
870 870 )
871 871 elif n1: # file exists only on local side
872 872 if f in copied2:
873 873 pass # we'll deal with it on m2 side
874 874 elif (
875 875 f in branch_copies1.movewithdir
876 876 ): # directory rename, move local
877 877 f2 = branch_copies1.movewithdir[f]
878 878 if f2 in m2:
879 879 mresult.addfile(
880 880 f2,
881 881 mergestatemod.ACTION_MERGE,
882 882 (f, f2, None, True, pa.node()),
883 883 b'remote directory rename, both created',
884 884 )
885 885 else:
886 886 mresult.addfile(
887 887 f2,
888 888 mergestatemod.ACTION_DIR_RENAME_MOVE_LOCAL,
889 889 (f, fl1),
890 890 b'remote directory rename - move from %s' % f,
891 891 )
892 892 elif f in branch_copies1.copy:
893 893 f2 = branch_copies1.copy[f]
894 894 mresult.addfile(
895 895 f,
896 896 mergestatemod.ACTION_MERGE,
897 897 (f, f2, f2, False, pa.node()),
898 898 b'local copied/moved from %s' % f2,
899 899 )
900 900 elif f in ma: # clean, a different, no remote
901 901 if n1 != ma[f]:
902 902 if acceptremote:
903 903 mresult.addfile(
904 904 f,
905 905 mergestatemod.ACTION_REMOVE,
906 906 None,
907 907 b'remote delete',
908 908 )
909 909 else:
910 910 mresult.addfile(
911 911 f,
912 912 mergestatemod.ACTION_CHANGED_DELETED,
913 913 (f, None, f, False, pa.node()),
914 914 b'prompt changed/deleted',
915 915 )
916 916 elif n1 == addednodeid:
917 917 # This file was locally added. We should forget it instead of
918 918 # deleting it.
919 919 mresult.addfile(
920 920 f, mergestatemod.ACTION_FORGET, None, b'remote deleted',
921 921 )
922 922 else:
923 923 mresult.addfile(
924 924 f, mergestatemod.ACTION_REMOVE, None, b'other deleted',
925 925 )
926 926 elif n2: # file exists only on remote side
927 927 if f in copied1:
928 928 pass # we'll deal with it on m1 side
929 929 elif f in branch_copies2.movewithdir:
930 930 f2 = branch_copies2.movewithdir[f]
931 931 if f2 in m1:
932 932 mresult.addfile(
933 933 f2,
934 934 mergestatemod.ACTION_MERGE,
935 935 (f2, f, None, False, pa.node()),
936 936 b'local directory rename, both created',
937 937 )
938 938 else:
939 939 mresult.addfile(
940 940 f2,
941 941 mergestatemod.ACTION_LOCAL_DIR_RENAME_GET,
942 942 (f, fl2),
943 943 b'local directory rename - get from %s' % f,
944 944 )
945 945 elif f in branch_copies2.copy:
946 946 f2 = branch_copies2.copy[f]
947 947 msg, args = None, None
948 948 if f2 in m2:
949 949 args = (f2, f, f2, False, pa.node())
950 950 msg = b'remote copied from %s' % f2
951 951 else:
952 952 args = (f2, f, f2, True, pa.node())
953 953 msg = b'remote moved from %s' % f2
954 954 mresult.addfile(f, mergestatemod.ACTION_MERGE, args, msg)
955 955 elif f not in ma:
956 956 # local unknown, remote created: the logic is described by the
957 957 # following table:
958 958 #
959 959 # force branchmerge different | action
960 960 # n * * | create
961 961 # y n * | create
962 962 # y y n | create
963 963 # y y y | merge
964 964 #
965 965 # Checking whether the files are different is expensive, so we
966 966 # don't do that when we can avoid it.
967 967 if not force:
968 968 mresult.addfile(
969 969 f,
970 970 mergestatemod.ACTION_CREATED,
971 971 (fl2,),
972 972 b'remote created',
973 973 )
974 974 elif not branchmerge:
975 975 mresult.addfile(
976 976 f,
977 977 mergestatemod.ACTION_CREATED,
978 978 (fl2,),
979 979 b'remote created',
980 980 )
981 981 else:
982 982 mresult.addfile(
983 983 f,
984 984 mergestatemod.ACTION_CREATED_MERGE,
985 985 (fl2, pa.node()),
986 986 b'remote created, get or merge',
987 987 )
988 988 elif n2 != ma[f]:
989 989 df = None
990 990 for d in branch_copies1.dirmove:
991 991 if f.startswith(d):
992 992 # new file added in a directory that was moved
993 993 df = branch_copies1.dirmove[d] + f[len(d) :]
994 994 break
995 995 if df is not None and df in m1:
996 996 mresult.addfile(
997 997 df,
998 998 mergestatemod.ACTION_MERGE,
999 999 (df, f, f, False, pa.node()),
1000 1000 b'local directory rename - respect move '
1001 1001 b'from %s' % f,
1002 1002 )
1003 1003 elif acceptremote:
1004 1004 mresult.addfile(
1005 1005 f,
1006 1006 mergestatemod.ACTION_CREATED,
1007 1007 (fl2,),
1008 1008 b'remote recreating',
1009 1009 )
1010 1010 else:
1011 1011 mresult.addfile(
1012 1012 f,
1013 1013 mergestatemod.ACTION_DELETED_CHANGED,
1014 1014 (None, f, f, False, pa.node()),
1015 1015 b'prompt deleted/changed',
1016 1016 )
1017 1017
1018 1018 if repo.ui.configbool(b'experimental', b'merge.checkpathconflicts'):
1019 1019 # If we are merging, look for path conflicts.
1020 1020 checkpathconflicts(repo, wctx, p2, mresult)
1021 1021
1022 1022 narrowmatch = repo.narrowmatch()
1023 1023 if not narrowmatch.always():
1024 1024 # Updates "actions" in place
1025 1025 _filternarrowactions(narrowmatch, branchmerge, mresult)
1026 1026
1027 1027 renamedelete = branch_copies1.renamedelete
1028 1028 renamedelete.update(branch_copies2.renamedelete)
1029 1029
1030 1030 mresult.updatevalues(diverge, renamedelete, commitinfo)
1031 1031 return mresult
1032 1032
1033 1033
1034 1034 def _resolvetrivial(repo, wctx, mctx, ancestor, mresult):
1035 1035 """Resolves false conflicts where the nodeid changed but the content
1036 1036 remained the same."""
1037 1037 # We force a copy of actions.items() because we're going to mutate
1038 1038 # actions as we resolve trivial conflicts.
1039 1039 for f in list(mresult.files((mergestatemod.ACTION_CHANGED_DELETED,))):
1040 1040 if f in ancestor and not wctx[f].cmp(ancestor[f]):
1041 1041 # local did change but ended up with same content
1042 1042 mresult.addfile(
1043 1043 f, mergestatemod.ACTION_REMOVE, None, b'prompt same'
1044 1044 )
1045 1045
1046 1046 for f in list(mresult.files((mergestatemod.ACTION_DELETED_CHANGED,))):
1047 1047 if f in ancestor and not mctx[f].cmp(ancestor[f]):
1048 1048 # remote did change but ended up with same content
1049 1049 mresult.removefile(f) # don't get = keep local deleted
1050 1050
1051 1051
1052 1052 def calculateupdates(
1053 1053 repo,
1054 1054 wctx,
1055 1055 mctx,
1056 1056 ancestors,
1057 1057 branchmerge,
1058 1058 force,
1059 1059 acceptremote,
1060 1060 followcopies,
1061 1061 matcher=None,
1062 1062 mergeforce=False,
1063 1063 ):
1064 1064 """
1065 1065 Calculate the actions needed to merge mctx into wctx using ancestors
1066 1066
1067 1067 Uses manifestmerge() to merge manifest and get list of actions required to
1068 1068 perform for merging two manifests. If there are multiple ancestors, uses bid
1069 1069 merge if enabled.
1070 1070
1071 1071 Also filters out actions which are unrequired if repository is sparse.
1072 1072
1073 1073 Returns mergeresult object same as manifestmerge().
1074 1074 """
1075 1075 # Avoid cycle.
1076 1076 from . import sparse
1077 1077
1078 1078 mresult = None
1079 1079 if len(ancestors) == 1: # default
1080 1080 mresult = manifestmerge(
1081 1081 repo,
1082 1082 wctx,
1083 1083 mctx,
1084 1084 ancestors[0],
1085 1085 branchmerge,
1086 1086 force,
1087 1087 matcher,
1088 1088 acceptremote,
1089 1089 followcopies,
1090 1090 )
1091 1091 _checkunknownfiles(repo, wctx, mctx, force, mresult, mergeforce)
1092 1092
1093 1093 else: # only when merge.preferancestor=* - the default
1094 1094 repo.ui.note(
1095 1095 _(b"note: merging %s and %s using bids from ancestors %s\n")
1096 1096 % (
1097 1097 wctx,
1098 1098 mctx,
1099 1099 _(b' and ').join(pycompat.bytestr(anc) for anc in ancestors),
1100 1100 )
1101 1101 )
1102 1102
1103 1103 # mapping filename to bids (action method to list af actions)
1104 1104 # {FILENAME1 : BID1, FILENAME2 : BID2}
1105 1105 # BID is another dictionary which contains
1106 1106 # mapping of following form:
1107 1107 # {ACTION_X : [info, ..], ACTION_Y : [info, ..]}
1108 1108 fbids = {}
1109 1109 diverge, renamedelete = None, None
1110 1110 for ancestor in ancestors:
1111 1111 repo.ui.note(_(b'\ncalculating bids for ancestor %s\n') % ancestor)
1112 1112 mresult1 = manifestmerge(
1113 1113 repo,
1114 1114 wctx,
1115 1115 mctx,
1116 1116 ancestor,
1117 1117 branchmerge,
1118 1118 force,
1119 1119 matcher,
1120 1120 acceptremote,
1121 1121 followcopies,
1122 1122 forcefulldiff=True,
1123 1123 )
1124 1124 _checkunknownfiles(repo, wctx, mctx, force, mresult1, mergeforce)
1125 1125
1126 1126 # Track the shortest set of warning on the theory that bid
1127 1127 # merge will correctly incorporate more information
1128 1128 if diverge is None or len(mresult1.diverge) < len(diverge):
1129 1129 diverge = mresult1.diverge
1130 1130 if renamedelete is None or len(renamedelete) < len(
1131 1131 mresult1.renamedelete
1132 1132 ):
1133 1133 renamedelete = mresult1.renamedelete
1134 1134
1135 1135 for f, a in mresult1.filemap(sort=True):
1136 1136 m, args, msg = a
1137 1137 repo.ui.debug(b' %s: %s -> %s\n' % (f, msg, m))
1138 1138 if f in fbids:
1139 1139 d = fbids[f]
1140 1140 if m in d:
1141 1141 d[m].append(a)
1142 1142 else:
1143 1143 d[m] = [a]
1144 1144 else:
1145 1145 fbids[f] = {m: [a]}
1146 1146
1147 1147 # Call for bids
1148 1148 # Pick the best bid for each file
1149 1149 repo.ui.note(_(b'\nauction for merging merge bids\n'))
1150 1150 mresult = mergeresult()
1151 1151 for f, bids in sorted(fbids.items()):
1152 1152 # bids is a mapping from action method to list af actions
1153 1153 # Consensus?
1154 1154 if len(bids) == 1: # all bids are the same kind of method
1155 1155 m, l = list(bids.items())[0]
1156 1156 if all(a == l[0] for a in l[1:]): # len(bids) is > 1
1157 1157 repo.ui.note(_(b" %s: consensus for %s\n") % (f, m))
1158 1158 mresult.addfile(f, *l[0])
1159 1159 continue
1160 1160 # If keep is an option, just do it.
1161 1161 if mergestatemod.ACTION_KEEP in bids:
1162 1162 repo.ui.note(_(b" %s: picking 'keep' action\n") % f)
1163 1163 mresult.addfile(f, *bids[mergestatemod.ACTION_KEEP][0])
1164 1164 continue
1165 1165 # If there are gets and they all agree [how could they not?], do it.
1166 1166 if mergestatemod.ACTION_GET in bids:
1167 1167 ga0 = bids[mergestatemod.ACTION_GET][0]
1168 1168 if all(a == ga0 for a in bids[mergestatemod.ACTION_GET][1:]):
1169 1169 repo.ui.note(_(b" %s: picking 'get' action\n") % f)
1170 1170 mresult.addfile(f, *ga0)
1171 1171 continue
1172 1172 # TODO: Consider other simple actions such as mode changes
1173 1173 # Handle inefficient democrazy.
1174 1174 repo.ui.note(_(b' %s: multiple bids for merge action:\n') % f)
1175 1175 for m, l in sorted(bids.items()):
1176 1176 for _f, args, msg in l:
1177 1177 repo.ui.note(b' %s -> %s\n' % (msg, m))
1178 1178 # Pick random action. TODO: Instead, prompt user when resolving
1179 1179 m, l = list(bids.items())[0]
1180 1180 repo.ui.warn(
1181 1181 _(b' %s: ambiguous merge - picked %s action\n') % (f, m)
1182 1182 )
1183 1183 mresult.addfile(f, *l[0])
1184 1184 continue
1185 1185 repo.ui.note(_(b'end of auction\n\n'))
1186 1186 # TODO: think about commitinfo when bid merge is used
1187 1187 mresult.updatevalues(diverge, renamedelete, {})
1188 1188
1189 1189 if wctx.rev() is None:
1190 1190 _forgetremoved(wctx, mctx, branchmerge, mresult)
1191 1191
1192 1192 sparse.filterupdatesactions(repo, wctx, mctx, branchmerge, mresult)
1193 1193 _resolvetrivial(repo, wctx, mctx, ancestors[0], mresult)
1194 1194
1195 1195 return mresult
1196 1196
1197 1197
1198 1198 def _getcwd():
1199 1199 try:
1200 1200 return encoding.getcwd()
1201 1201 except OSError as err:
1202 1202 if err.errno == errno.ENOENT:
1203 1203 return None
1204 1204 raise
1205 1205
1206 1206
1207 1207 def batchremove(repo, wctx, actions):
1208 1208 """apply removes to the working directory
1209 1209
1210 1210 yields tuples for progress updates
1211 1211 """
1212 1212 verbose = repo.ui.verbose
1213 1213 cwd = _getcwd()
1214 1214 i = 0
1215 1215 for f, args, msg in actions:
1216 1216 repo.ui.debug(b" %s: %s -> r\n" % (f, msg))
1217 1217 if verbose:
1218 1218 repo.ui.note(_(b"removing %s\n") % f)
1219 1219 wctx[f].audit()
1220 1220 try:
1221 1221 wctx[f].remove(ignoremissing=True)
1222 1222 except OSError as inst:
1223 1223 repo.ui.warn(
1224 1224 _(b"update failed to remove %s: %s!\n") % (f, inst.strerror)
1225 1225 )
1226 1226 if i == 100:
1227 1227 yield i, f
1228 1228 i = 0
1229 1229 i += 1
1230 1230 if i > 0:
1231 1231 yield i, f
1232 1232
1233 1233 if cwd and not _getcwd():
1234 1234 # cwd was removed in the course of removing files; print a helpful
1235 1235 # warning.
1236 1236 repo.ui.warn(
1237 1237 _(
1238 1238 b"current directory was removed\n"
1239 1239 b"(consider changing to repo root: %s)\n"
1240 1240 )
1241 1241 % repo.root
1242 1242 )
1243 1243
1244 1244
1245 1245 def batchget(repo, mctx, wctx, wantfiledata, actions):
1246 1246 """apply gets to the working directory
1247 1247
1248 1248 mctx is the context to get from
1249 1249
1250 1250 Yields arbitrarily many (False, tuple) for progress updates, followed by
1251 1251 exactly one (True, filedata). When wantfiledata is false, filedata is an
1252 1252 empty dict. When wantfiledata is true, filedata[f] is a triple (mode, size,
1253 1253 mtime) of the file f written for each action.
1254 1254 """
1255 1255 filedata = {}
1256 1256 verbose = repo.ui.verbose
1257 1257 fctx = mctx.filectx
1258 1258 ui = repo.ui
1259 1259 i = 0
1260 1260 with repo.wvfs.backgroundclosing(ui, expectedcount=len(actions)):
1261 1261 for f, (flags, backup), msg in actions:
1262 1262 repo.ui.debug(b" %s: %s -> g\n" % (f, msg))
1263 1263 if verbose:
1264 1264 repo.ui.note(_(b"getting %s\n") % f)
1265 1265
1266 1266 if backup:
1267 1267 # If a file or directory exists with the same name, back that
1268 1268 # up. Otherwise, look to see if there is a file that conflicts
1269 1269 # with a directory this file is in, and if so, back that up.
1270 1270 conflicting = f
1271 1271 if not repo.wvfs.lexists(f):
1272 1272 for p in pathutil.finddirs(f):
1273 1273 if repo.wvfs.isfileorlink(p):
1274 1274 conflicting = p
1275 1275 break
1276 1276 if repo.wvfs.lexists(conflicting):
1277 1277 orig = scmutil.backuppath(ui, repo, conflicting)
1278 1278 util.rename(repo.wjoin(conflicting), orig)
1279 1279 wfctx = wctx[f]
1280 1280 wfctx.clearunknown()
1281 1281 atomictemp = ui.configbool(b"experimental", b"update.atomic-file")
1282 1282 size = wfctx.write(
1283 1283 fctx(f).data(),
1284 1284 flags,
1285 1285 backgroundclose=True,
1286 1286 atomictemp=atomictemp,
1287 1287 )
1288 1288 if wantfiledata:
1289 1289 s = wfctx.lstat()
1290 1290 mode = s.st_mode
1291 1291 mtime = s[stat.ST_MTIME]
1292 1292 filedata[f] = (mode, size, mtime) # for dirstate.normal
1293 1293 if i == 100:
1294 1294 yield False, (i, f)
1295 1295 i = 0
1296 1296 i += 1
1297 1297 if i > 0:
1298 1298 yield False, (i, f)
1299 1299 yield True, filedata
1300 1300
1301 1301
1302 1302 def _prefetchfiles(repo, ctx, mresult):
1303 1303 """Invoke ``scmutil.prefetchfiles()`` for the files relevant to the dict
1304 1304 of merge actions. ``ctx`` is the context being merged in."""
1305 1305
1306 1306 # Skipping 'a', 'am', 'f', 'r', 'dm', 'e', 'k', 'p' and 'pr', because they
1307 1307 # don't touch the context to be merged in. 'cd' is skipped, because
1308 1308 # changed/deleted never resolves to something from the remote side.
1309 1309 files = mresult.files(
1310 1310 [
1311 1311 mergestatemod.ACTION_GET,
1312 1312 mergestatemod.ACTION_DELETED_CHANGED,
1313 1313 mergestatemod.ACTION_LOCAL_DIR_RENAME_GET,
1314 1314 mergestatemod.ACTION_MERGE,
1315 1315 ]
1316 1316 )
1317 1317
1318 1318 prefetch = scmutil.prefetchfiles
1319 1319 matchfiles = scmutil.matchfiles
1320 1320 prefetch(
1321 1321 repo, [(ctx.rev(), matchfiles(repo, files),)],
1322 1322 )
1323 1323
1324 1324
1325 1325 @attr.s(frozen=True)
1326 1326 class updateresult(object):
1327 1327 updatedcount = attr.ib()
1328 1328 mergedcount = attr.ib()
1329 1329 removedcount = attr.ib()
1330 1330 unresolvedcount = attr.ib()
1331 1331
1332 1332 def isempty(self):
1333 1333 return not (
1334 1334 self.updatedcount
1335 1335 or self.mergedcount
1336 1336 or self.removedcount
1337 1337 or self.unresolvedcount
1338 1338 )
1339 1339
1340 1340
1341 1341 def applyupdates(
1342 1342 repo, mresult, wctx, mctx, overwrite, wantfiledata, labels=None,
1343 1343 ):
1344 1344 """apply the merge action list to the working directory
1345 1345
1346 1346 mresult is a mergeresult object representing result of the merge
1347 1347 wctx is the working copy context
1348 1348 mctx is the context to be merged into the working copy
1349 1349
1350 1350 Return a tuple of (counts, filedata), where counts is a tuple
1351 1351 (updated, merged, removed, unresolved) that describes how many
1352 1352 files were affected by the update, and filedata is as described in
1353 1353 batchget.
1354 1354 """
1355 1355
1356 1356 _prefetchfiles(repo, mctx, mresult)
1357 1357
1358 1358 updated, merged, removed = 0, 0, 0
1359 1359 ms = mergestatemod.mergestate.clean(
1360 1360 repo, wctx.p1().node(), mctx.node(), labels
1361 1361 )
1362 1362
1363 1363 for f, op in pycompat.iteritems(mresult.commitinfo):
1364 1364 # the other side of filenode was choosen while merging, store this in
1365 1365 # mergestate so that it can be reused on commit
1366 if op == b'other':
1366 if op[b'filenode-source'] == b'other':
1367 1367 ms.addmergedother(f)
1368 1368
1369 1369 moves = []
1370 1370
1371 1371 # 'cd' and 'dc' actions are treated like other merge conflicts
1372 1372 mergeactions = list(
1373 1373 mresult.getactions(
1374 1374 [
1375 1375 mergestatemod.ACTION_CHANGED_DELETED,
1376 1376 mergestatemod.ACTION_DELETED_CHANGED,
1377 1377 mergestatemod.ACTION_MERGE,
1378 1378 ],
1379 1379 sort=True,
1380 1380 )
1381 1381 )
1382 1382 for f, args, msg in mergeactions:
1383 1383 f1, f2, fa, move, anc = args
1384 1384 if f == b'.hgsubstate': # merged internally
1385 1385 continue
1386 1386 if f1 is None:
1387 1387 fcl = filemerge.absentfilectx(wctx, fa)
1388 1388 else:
1389 1389 repo.ui.debug(b" preserving %s for resolve of %s\n" % (f1, f))
1390 1390 fcl = wctx[f1]
1391 1391 if f2 is None:
1392 1392 fco = filemerge.absentfilectx(mctx, fa)
1393 1393 else:
1394 1394 fco = mctx[f2]
1395 1395 actx = repo[anc]
1396 1396 if fa in actx:
1397 1397 fca = actx[fa]
1398 1398 else:
1399 1399 # TODO: move to absentfilectx
1400 1400 fca = repo.filectx(f1, fileid=nullrev)
1401 1401 ms.add(fcl, fco, fca, f)
1402 1402 if f1 != f and move:
1403 1403 moves.append(f1)
1404 1404
1405 1405 # remove renamed files after safely stored
1406 1406 for f in moves:
1407 1407 if wctx[f].lexists():
1408 1408 repo.ui.debug(b"removing %s\n" % f)
1409 1409 wctx[f].audit()
1410 1410 wctx[f].remove()
1411 1411
1412 1412 numupdates = mresult.len() - mresult.len((mergestatemod.ACTION_KEEP,))
1413 1413 progress = repo.ui.makeprogress(
1414 1414 _(b'updating'), unit=_(b'files'), total=numupdates
1415 1415 )
1416 1416
1417 1417 if b'.hgsubstate' in mresult._actionmapping[mergestatemod.ACTION_REMOVE]:
1418 1418 subrepoutil.submerge(repo, wctx, mctx, wctx, overwrite, labels)
1419 1419
1420 1420 # record path conflicts
1421 1421 for f, args, msg in mresult.getactions(
1422 1422 [mergestatemod.ACTION_PATH_CONFLICT], sort=True
1423 1423 ):
1424 1424 f1, fo = args
1425 1425 s = repo.ui.status
1426 1426 s(
1427 1427 _(
1428 1428 b"%s: path conflict - a file or link has the same name as a "
1429 1429 b"directory\n"
1430 1430 )
1431 1431 % f
1432 1432 )
1433 1433 if fo == b'l':
1434 1434 s(_(b"the local file has been renamed to %s\n") % f1)
1435 1435 else:
1436 1436 s(_(b"the remote file has been renamed to %s\n") % f1)
1437 1437 s(_(b"resolve manually then use 'hg resolve --mark %s'\n") % f)
1438 1438 ms.addpathconflict(f, f1, fo)
1439 1439 progress.increment(item=f)
1440 1440
1441 1441 # When merging in-memory, we can't support worker processes, so set the
1442 1442 # per-item cost at 0 in that case.
1443 1443 cost = 0 if wctx.isinmemory() else 0.001
1444 1444
1445 1445 # remove in parallel (must come before resolving path conflicts and getting)
1446 1446 prog = worker.worker(
1447 1447 repo.ui,
1448 1448 cost,
1449 1449 batchremove,
1450 1450 (repo, wctx),
1451 1451 list(mresult.getactions([mergestatemod.ACTION_REMOVE], sort=True)),
1452 1452 )
1453 1453 for i, item in prog:
1454 1454 progress.increment(step=i, item=item)
1455 1455 removed = mresult.len((mergestatemod.ACTION_REMOVE,))
1456 1456
1457 1457 # resolve path conflicts (must come before getting)
1458 1458 for f, args, msg in mresult.getactions(
1459 1459 [mergestatemod.ACTION_PATH_CONFLICT_RESOLVE], sort=True
1460 1460 ):
1461 1461 repo.ui.debug(b" %s: %s -> pr\n" % (f, msg))
1462 1462 (f0, origf0) = args
1463 1463 if wctx[f0].lexists():
1464 1464 repo.ui.note(_(b"moving %s to %s\n") % (f0, f))
1465 1465 wctx[f].audit()
1466 1466 wctx[f].write(wctx.filectx(f0).data(), wctx.filectx(f0).flags())
1467 1467 wctx[f0].remove()
1468 1468 progress.increment(item=f)
1469 1469
1470 1470 # get in parallel.
1471 1471 threadsafe = repo.ui.configbool(
1472 1472 b'experimental', b'worker.wdir-get-thread-safe'
1473 1473 )
1474 1474 prog = worker.worker(
1475 1475 repo.ui,
1476 1476 cost,
1477 1477 batchget,
1478 1478 (repo, mctx, wctx, wantfiledata),
1479 1479 list(mresult.getactions([mergestatemod.ACTION_GET], sort=True)),
1480 1480 threadsafe=threadsafe,
1481 1481 hasretval=True,
1482 1482 )
1483 1483 getfiledata = {}
1484 1484 for final, res in prog:
1485 1485 if final:
1486 1486 getfiledata = res
1487 1487 else:
1488 1488 i, item = res
1489 1489 progress.increment(step=i, item=item)
1490 1490
1491 1491 if b'.hgsubstate' in mresult._actionmapping[mergestatemod.ACTION_GET]:
1492 1492 subrepoutil.submerge(repo, wctx, mctx, wctx, overwrite, labels)
1493 1493
1494 1494 # forget (manifest only, just log it) (must come first)
1495 1495 for f, args, msg in mresult.getactions(
1496 1496 (mergestatemod.ACTION_FORGET,), sort=True
1497 1497 ):
1498 1498 repo.ui.debug(b" %s: %s -> f\n" % (f, msg))
1499 1499 progress.increment(item=f)
1500 1500
1501 1501 # re-add (manifest only, just log it)
1502 1502 for f, args, msg in mresult.getactions(
1503 1503 (mergestatemod.ACTION_ADD,), sort=True
1504 1504 ):
1505 1505 repo.ui.debug(b" %s: %s -> a\n" % (f, msg))
1506 1506 progress.increment(item=f)
1507 1507
1508 1508 # re-add/mark as modified (manifest only, just log it)
1509 1509 for f, args, msg in mresult.getactions(
1510 1510 (mergestatemod.ACTION_ADD_MODIFIED,), sort=True
1511 1511 ):
1512 1512 repo.ui.debug(b" %s: %s -> am\n" % (f, msg))
1513 1513 progress.increment(item=f)
1514 1514
1515 1515 # keep (noop, just log it)
1516 1516 for f, args, msg in mresult.getactions(
1517 1517 (mergestatemod.ACTION_KEEP,), sort=True
1518 1518 ):
1519 1519 repo.ui.debug(b" %s: %s -> k\n" % (f, msg))
1520 1520 # no progress
1521 1521
1522 1522 # directory rename, move local
1523 1523 for f, args, msg in mresult.getactions(
1524 1524 (mergestatemod.ACTION_DIR_RENAME_MOVE_LOCAL,), sort=True
1525 1525 ):
1526 1526 repo.ui.debug(b" %s: %s -> dm\n" % (f, msg))
1527 1527 progress.increment(item=f)
1528 1528 f0, flags = args
1529 1529 repo.ui.note(_(b"moving %s to %s\n") % (f0, f))
1530 1530 wctx[f].audit()
1531 1531 wctx[f].write(wctx.filectx(f0).data(), flags)
1532 1532 wctx[f0].remove()
1533 1533
1534 1534 # local directory rename, get
1535 1535 for f, args, msg in mresult.getactions(
1536 1536 (mergestatemod.ACTION_LOCAL_DIR_RENAME_GET,), sort=True
1537 1537 ):
1538 1538 repo.ui.debug(b" %s: %s -> dg\n" % (f, msg))
1539 1539 progress.increment(item=f)
1540 1540 f0, flags = args
1541 1541 repo.ui.note(_(b"getting %s to %s\n") % (f0, f))
1542 1542 wctx[f].write(mctx.filectx(f0).data(), flags)
1543 1543
1544 1544 # exec
1545 1545 for f, args, msg in mresult.getactions(
1546 1546 (mergestatemod.ACTION_EXEC,), sort=True
1547 1547 ):
1548 1548 repo.ui.debug(b" %s: %s -> e\n" % (f, msg))
1549 1549 progress.increment(item=f)
1550 1550 (flags,) = args
1551 1551 wctx[f].audit()
1552 1552 wctx[f].setflags(b'l' in flags, b'x' in flags)
1553 1553
1554 1554 # these actions updates the file
1555 1555 updated = mresult.len(
1556 1556 (
1557 1557 mergestatemod.ACTION_GET,
1558 1558 mergestatemod.ACTION_EXEC,
1559 1559 mergestatemod.ACTION_LOCAL_DIR_RENAME_GET,
1560 1560 mergestatemod.ACTION_DIR_RENAME_MOVE_LOCAL,
1561 1561 )
1562 1562 )
1563 1563 # the ordering is important here -- ms.mergedriver will raise if the merge
1564 1564 # driver has changed, and we want to be able to bypass it when overwrite is
1565 1565 # True
1566 1566 usemergedriver = not overwrite and mergeactions and ms.mergedriver
1567 1567
1568 1568 if usemergedriver:
1569 1569 if wctx.isinmemory():
1570 1570 raise error.InMemoryMergeConflictsError(
1571 1571 b"in-memory merge does not support mergedriver"
1572 1572 )
1573 1573 ms.commit()
1574 1574 proceed = driverpreprocess(repo, ms, wctx, labels=labels)
1575 1575 # the driver might leave some files unresolved
1576 1576 unresolvedf = set(ms.unresolved())
1577 1577 if not proceed:
1578 1578 # XXX setting unresolved to at least 1 is a hack to make sure we
1579 1579 # error out
1580 1580 return updateresult(
1581 1581 updated, merged, removed, max(len(unresolvedf), 1)
1582 1582 )
1583 1583 newactions = []
1584 1584 for f, args, msg in mergeactions:
1585 1585 if f in unresolvedf:
1586 1586 newactions.append((f, args, msg))
1587 1587 mergeactions = newactions
1588 1588
1589 1589 try:
1590 1590 # premerge
1591 1591 tocomplete = []
1592 1592 for f, args, msg in mergeactions:
1593 1593 repo.ui.debug(b" %s: %s -> m (premerge)\n" % (f, msg))
1594 1594 progress.increment(item=f)
1595 1595 if f == b'.hgsubstate': # subrepo states need updating
1596 1596 subrepoutil.submerge(
1597 1597 repo, wctx, mctx, wctx.ancestor(mctx), overwrite, labels
1598 1598 )
1599 1599 continue
1600 1600 wctx[f].audit()
1601 1601 complete, r = ms.preresolve(f, wctx)
1602 1602 if not complete:
1603 1603 numupdates += 1
1604 1604 tocomplete.append((f, args, msg))
1605 1605
1606 1606 # merge
1607 1607 for f, args, msg in tocomplete:
1608 1608 repo.ui.debug(b" %s: %s -> m (merge)\n" % (f, msg))
1609 1609 progress.increment(item=f, total=numupdates)
1610 1610 ms.resolve(f, wctx)
1611 1611
1612 1612 finally:
1613 1613 ms.commit()
1614 1614
1615 1615 unresolved = ms.unresolvedcount()
1616 1616
1617 1617 if (
1618 1618 usemergedriver
1619 1619 and not unresolved
1620 1620 and ms.mdstate() != mergestatemod.MERGE_DRIVER_STATE_SUCCESS
1621 1621 ):
1622 1622 if not driverconclude(repo, ms, wctx, labels=labels):
1623 1623 # XXX setting unresolved to at least 1 is a hack to make sure we
1624 1624 # error out
1625 1625 unresolved = max(unresolved, 1)
1626 1626
1627 1627 ms.commit()
1628 1628
1629 1629 msupdated, msmerged, msremoved = ms.counts()
1630 1630 updated += msupdated
1631 1631 merged += msmerged
1632 1632 removed += msremoved
1633 1633
1634 1634 extraactions = ms.actions()
1635 1635 if extraactions:
1636 1636 mfiles = {
1637 1637 a[0] for a in mresult.getactions((mergestatemod.ACTION_MERGE,))
1638 1638 }
1639 1639 for k, acts in pycompat.iteritems(extraactions):
1640 1640 for a in acts:
1641 1641 mresult.addfile(a[0], k, *a[1:])
1642 1642 if k == mergestatemod.ACTION_GET and wantfiledata:
1643 1643 # no filedata until mergestate is updated to provide it
1644 1644 for a in acts:
1645 1645 getfiledata[a[0]] = None
1646 1646 # Remove these files from actions[ACTION_MERGE] as well. This is
1647 1647 # important because in recordupdates, files in actions[ACTION_MERGE]
1648 1648 # are processed after files in other actions, and the merge driver
1649 1649 # might add files to those actions via extraactions above. This can
1650 1650 # lead to a file being recorded twice, with poor results. This is
1651 1651 # especially problematic for actions[ACTION_REMOVE] (currently only
1652 1652 # possible with the merge driver in the initial merge process;
1653 1653 # interrupted merges don't go through this flow).
1654 1654 #
1655 1655 # The real fix here is to have indexes by both file and action so
1656 1656 # that when the action for a file is changed it is automatically
1657 1657 # reflected in the other action lists. But that involves a more
1658 1658 # complex data structure, so this will do for now.
1659 1659 #
1660 1660 # We don't need to do the same operation for 'dc' and 'cd' because
1661 1661 # those lists aren't consulted again.
1662 1662 mfiles.difference_update(a[0] for a in acts)
1663 1663
1664 1664 for a in list(mresult.getactions((mergestatemod.ACTION_MERGE,))):
1665 1665 if a[0] not in mfiles:
1666 1666 mresult.removefile(a[0])
1667 1667
1668 1668 progress.complete()
1669 1669 assert len(getfiledata) == (
1670 1670 mresult.len((mergestatemod.ACTION_GET,)) if wantfiledata else 0
1671 1671 )
1672 1672 return updateresult(updated, merged, removed, unresolved), getfiledata
1673 1673
1674 1674
1675 1675 def _advertisefsmonitor(repo, num_gets, p1node):
1676 1676 # Advertise fsmonitor when its presence could be useful.
1677 1677 #
1678 1678 # We only advertise when performing an update from an empty working
1679 1679 # directory. This typically only occurs during initial clone.
1680 1680 #
1681 1681 # We give users a mechanism to disable the warning in case it is
1682 1682 # annoying.
1683 1683 #
1684 1684 # We only allow on Linux and MacOS because that's where fsmonitor is
1685 1685 # considered stable.
1686 1686 fsmonitorwarning = repo.ui.configbool(b'fsmonitor', b'warn_when_unused')
1687 1687 fsmonitorthreshold = repo.ui.configint(
1688 1688 b'fsmonitor', b'warn_update_file_count'
1689 1689 )
1690 1690 try:
1691 1691 # avoid cycle: extensions -> cmdutil -> merge
1692 1692 from . import extensions
1693 1693
1694 1694 extensions.find(b'fsmonitor')
1695 1695 fsmonitorenabled = repo.ui.config(b'fsmonitor', b'mode') != b'off'
1696 1696 # We intentionally don't look at whether fsmonitor has disabled
1697 1697 # itself because a) fsmonitor may have already printed a warning
1698 1698 # b) we only care about the config state here.
1699 1699 except KeyError:
1700 1700 fsmonitorenabled = False
1701 1701
1702 1702 if (
1703 1703 fsmonitorwarning
1704 1704 and not fsmonitorenabled
1705 1705 and p1node == nullid
1706 1706 and num_gets >= fsmonitorthreshold
1707 1707 and pycompat.sysplatform.startswith((b'linux', b'darwin'))
1708 1708 ):
1709 1709 repo.ui.warn(
1710 1710 _(
1711 1711 b'(warning: large working directory being used without '
1712 1712 b'fsmonitor enabled; enable fsmonitor to improve performance; '
1713 1713 b'see "hg help -e fsmonitor")\n'
1714 1714 )
1715 1715 )
1716 1716
1717 1717
1718 1718 UPDATECHECK_ABORT = b'abort' # handled at higher layers
1719 1719 UPDATECHECK_NONE = b'none'
1720 1720 UPDATECHECK_LINEAR = b'linear'
1721 1721 UPDATECHECK_NO_CONFLICT = b'noconflict'
1722 1722
1723 1723
1724 1724 def update(
1725 1725 repo,
1726 1726 node,
1727 1727 branchmerge,
1728 1728 force,
1729 1729 ancestor=None,
1730 1730 mergeancestor=False,
1731 1731 labels=None,
1732 1732 matcher=None,
1733 1733 mergeforce=False,
1734 1734 updatedirstate=True,
1735 1735 updatecheck=None,
1736 1736 wc=None,
1737 1737 ):
1738 1738 """
1739 1739 Perform a merge between the working directory and the given node
1740 1740
1741 1741 node = the node to update to
1742 1742 branchmerge = whether to merge between branches
1743 1743 force = whether to force branch merging or file overwriting
1744 1744 matcher = a matcher to filter file lists (dirstate not updated)
1745 1745 mergeancestor = whether it is merging with an ancestor. If true,
1746 1746 we should accept the incoming changes for any prompts that occur.
1747 1747 If false, merging with an ancestor (fast-forward) is only allowed
1748 1748 between different named branches. This flag is used by rebase extension
1749 1749 as a temporary fix and should be avoided in general.
1750 1750 labels = labels to use for base, local and other
1751 1751 mergeforce = whether the merge was run with 'merge --force' (deprecated): if
1752 1752 this is True, then 'force' should be True as well.
1753 1753
1754 1754 The table below shows all the behaviors of the update command given the
1755 1755 -c/--check and -C/--clean or no options, whether the working directory is
1756 1756 dirty, whether a revision is specified, and the relationship of the parent
1757 1757 rev to the target rev (linear or not). Match from top first. The -n
1758 1758 option doesn't exist on the command line, but represents the
1759 1759 experimental.updatecheck=noconflict option.
1760 1760
1761 1761 This logic is tested by test-update-branches.t.
1762 1762
1763 1763 -c -C -n -m dirty rev linear | result
1764 1764 y y * * * * * | (1)
1765 1765 y * y * * * * | (1)
1766 1766 y * * y * * * | (1)
1767 1767 * y y * * * * | (1)
1768 1768 * y * y * * * | (1)
1769 1769 * * y y * * * | (1)
1770 1770 * * * * * n n | x
1771 1771 * * * * n * * | ok
1772 1772 n n n n y * y | merge
1773 1773 n n n n y y n | (2)
1774 1774 n n n y y * * | merge
1775 1775 n n y n y * * | merge if no conflict
1776 1776 n y n n y * * | discard
1777 1777 y n n n y * * | (3)
1778 1778
1779 1779 x = can't happen
1780 1780 * = don't-care
1781 1781 1 = incompatible options (checked in commands.py)
1782 1782 2 = abort: uncommitted changes (commit or update --clean to discard changes)
1783 1783 3 = abort: uncommitted changes (checked in commands.py)
1784 1784
1785 1785 The merge is performed inside ``wc``, a workingctx-like objects. It defaults
1786 1786 to repo[None] if None is passed.
1787 1787
1788 1788 Return the same tuple as applyupdates().
1789 1789 """
1790 1790 # Avoid cycle.
1791 1791 from . import sparse
1792 1792
1793 1793 # This function used to find the default destination if node was None, but
1794 1794 # that's now in destutil.py.
1795 1795 assert node is not None
1796 1796 if not branchmerge and not force:
1797 1797 # TODO: remove the default once all callers that pass branchmerge=False
1798 1798 # and force=False pass a value for updatecheck. We may want to allow
1799 1799 # updatecheck='abort' to better suppport some of these callers.
1800 1800 if updatecheck is None:
1801 1801 updatecheck = UPDATECHECK_LINEAR
1802 1802 if updatecheck not in (
1803 1803 UPDATECHECK_NONE,
1804 1804 UPDATECHECK_LINEAR,
1805 1805 UPDATECHECK_NO_CONFLICT,
1806 1806 ):
1807 1807 raise ValueError(
1808 1808 r'Invalid updatecheck %r (can accept %r)'
1809 1809 % (
1810 1810 updatecheck,
1811 1811 (
1812 1812 UPDATECHECK_NONE,
1813 1813 UPDATECHECK_LINEAR,
1814 1814 UPDATECHECK_NO_CONFLICT,
1815 1815 ),
1816 1816 )
1817 1817 )
1818 1818 if wc is not None and wc.isinmemory():
1819 1819 maybe_wlock = util.nullcontextmanager()
1820 1820 else:
1821 1821 maybe_wlock = repo.wlock()
1822 1822 with maybe_wlock:
1823 1823 if wc is None:
1824 1824 wc = repo[None]
1825 1825 pl = wc.parents()
1826 1826 p1 = pl[0]
1827 1827 p2 = repo[node]
1828 1828 if ancestor is not None:
1829 1829 pas = [repo[ancestor]]
1830 1830 else:
1831 1831 if repo.ui.configlist(b'merge', b'preferancestor') == [b'*']:
1832 1832 cahs = repo.changelog.commonancestorsheads(p1.node(), p2.node())
1833 1833 pas = [repo[anc] for anc in (sorted(cahs) or [nullid])]
1834 1834 else:
1835 1835 pas = [p1.ancestor(p2, warn=branchmerge)]
1836 1836
1837 1837 fp1, fp2, xp1, xp2 = p1.node(), p2.node(), bytes(p1), bytes(p2)
1838 1838
1839 1839 overwrite = force and not branchmerge
1840 1840 ### check phase
1841 1841 if not overwrite:
1842 1842 if len(pl) > 1:
1843 1843 raise error.Abort(_(b"outstanding uncommitted merge"))
1844 1844 ms = mergestatemod.mergestate.read(repo)
1845 1845 if list(ms.unresolved()):
1846 1846 raise error.Abort(
1847 1847 _(b"outstanding merge conflicts"),
1848 1848 hint=_(b"use 'hg resolve' to resolve"),
1849 1849 )
1850 1850 if branchmerge:
1851 1851 if pas == [p2]:
1852 1852 raise error.Abort(
1853 1853 _(
1854 1854 b"merging with a working directory ancestor"
1855 1855 b" has no effect"
1856 1856 )
1857 1857 )
1858 1858 elif pas == [p1]:
1859 1859 if not mergeancestor and wc.branch() == p2.branch():
1860 1860 raise error.Abort(
1861 1861 _(b"nothing to merge"),
1862 1862 hint=_(b"use 'hg update' or check 'hg heads'"),
1863 1863 )
1864 1864 if not force and (wc.files() or wc.deleted()):
1865 1865 raise error.Abort(
1866 1866 _(b"uncommitted changes"),
1867 1867 hint=_(b"use 'hg status' to list changes"),
1868 1868 )
1869 1869 if not wc.isinmemory():
1870 1870 for s in sorted(wc.substate):
1871 1871 wc.sub(s).bailifchanged()
1872 1872
1873 1873 elif not overwrite:
1874 1874 if p1 == p2: # no-op update
1875 1875 # call the hooks and exit early
1876 1876 repo.hook(b'preupdate', throw=True, parent1=xp2, parent2=b'')
1877 1877 repo.hook(b'update', parent1=xp2, parent2=b'', error=0)
1878 1878 return updateresult(0, 0, 0, 0)
1879 1879
1880 1880 if updatecheck == UPDATECHECK_LINEAR and pas not in (
1881 1881 [p1],
1882 1882 [p2],
1883 1883 ): # nonlinear
1884 1884 dirty = wc.dirty(missing=True)
1885 1885 if dirty:
1886 1886 # Branching is a bit strange to ensure we do the minimal
1887 1887 # amount of call to obsutil.foreground.
1888 1888 foreground = obsutil.foreground(repo, [p1.node()])
1889 1889 # note: the <node> variable contains a random identifier
1890 1890 if repo[node].node() in foreground:
1891 1891 pass # allow updating to successors
1892 1892 else:
1893 1893 msg = _(b"uncommitted changes")
1894 1894 hint = _(b"commit or update --clean to discard changes")
1895 1895 raise error.UpdateAbort(msg, hint=hint)
1896 1896 else:
1897 1897 # Allow jumping branches if clean and specific rev given
1898 1898 pass
1899 1899
1900 1900 if overwrite:
1901 1901 pas = [wc]
1902 1902 elif not branchmerge:
1903 1903 pas = [p1]
1904 1904
1905 1905 # deprecated config: merge.followcopies
1906 1906 followcopies = repo.ui.configbool(b'merge', b'followcopies')
1907 1907 if overwrite:
1908 1908 followcopies = False
1909 1909 elif not pas[0]:
1910 1910 followcopies = False
1911 1911 if not branchmerge and not wc.dirty(missing=True):
1912 1912 followcopies = False
1913 1913
1914 1914 ### calculate phase
1915 1915 mresult = calculateupdates(
1916 1916 repo,
1917 1917 wc,
1918 1918 p2,
1919 1919 pas,
1920 1920 branchmerge,
1921 1921 force,
1922 1922 mergeancestor,
1923 1923 followcopies,
1924 1924 matcher=matcher,
1925 1925 mergeforce=mergeforce,
1926 1926 )
1927 1927
1928 1928 if updatecheck == UPDATECHECK_NO_CONFLICT:
1929 1929 if mresult.hasconflicts():
1930 1930 msg = _(b"conflicting changes")
1931 1931 hint = _(b"commit or update --clean to discard changes")
1932 1932 raise error.Abort(msg, hint=hint)
1933 1933
1934 1934 # Prompt and create actions. Most of this is in the resolve phase
1935 1935 # already, but we can't handle .hgsubstate in filemerge or
1936 1936 # subrepoutil.submerge yet so we have to keep prompting for it.
1937 1937 vals = mresult.getfile(b'.hgsubstate')
1938 1938 if vals:
1939 1939 f = b'.hgsubstate'
1940 1940 m, args, msg = vals
1941 1941 prompts = filemerge.partextras(labels)
1942 1942 prompts[b'f'] = f
1943 1943 if m == mergestatemod.ACTION_CHANGED_DELETED:
1944 1944 if repo.ui.promptchoice(
1945 1945 _(
1946 1946 b"local%(l)s changed %(f)s which other%(o)s deleted\n"
1947 1947 b"use (c)hanged version or (d)elete?"
1948 1948 b"$$ &Changed $$ &Delete"
1949 1949 )
1950 1950 % prompts,
1951 1951 0,
1952 1952 ):
1953 1953 mresult.addfile(
1954 1954 f, mergestatemod.ACTION_REMOVE, None, b'prompt delete',
1955 1955 )
1956 1956 elif f in p1:
1957 1957 mresult.addfile(
1958 1958 f,
1959 1959 mergestatemod.ACTION_ADD_MODIFIED,
1960 1960 None,
1961 1961 b'prompt keep',
1962 1962 )
1963 1963 else:
1964 1964 mresult.addfile(
1965 1965 f, mergestatemod.ACTION_ADD, None, b'prompt keep',
1966 1966 )
1967 1967 elif m == mergestatemod.ACTION_DELETED_CHANGED:
1968 1968 f1, f2, fa, move, anc = args
1969 1969 flags = p2[f2].flags()
1970 1970 if (
1971 1971 repo.ui.promptchoice(
1972 1972 _(
1973 1973 b"other%(o)s changed %(f)s which local%(l)s deleted\n"
1974 1974 b"use (c)hanged version or leave (d)eleted?"
1975 1975 b"$$ &Changed $$ &Deleted"
1976 1976 )
1977 1977 % prompts,
1978 1978 0,
1979 1979 )
1980 1980 == 0
1981 1981 ):
1982 1982 mresult.addfile(
1983 1983 f,
1984 1984 mergestatemod.ACTION_GET,
1985 1985 (flags, False),
1986 1986 b'prompt recreating',
1987 1987 )
1988 1988 else:
1989 1989 mresult.removefile(f)
1990 1990
1991 1991 if not util.fscasesensitive(repo.path):
1992 1992 # check collision between files only in p2 for clean update
1993 1993 if not branchmerge and (
1994 1994 force or not wc.dirty(missing=True, branch=False)
1995 1995 ):
1996 1996 _checkcollision(repo, p2.manifest(), None)
1997 1997 else:
1998 1998 _checkcollision(repo, wc.manifest(), mresult)
1999 1999
2000 2000 # divergent renames
2001 2001 for f, fl in sorted(pycompat.iteritems(mresult.diverge)):
2002 2002 repo.ui.warn(
2003 2003 _(
2004 2004 b"note: possible conflict - %s was renamed "
2005 2005 b"multiple times to:\n"
2006 2006 )
2007 2007 % f
2008 2008 )
2009 2009 for nf in sorted(fl):
2010 2010 repo.ui.warn(b" %s\n" % nf)
2011 2011
2012 2012 # rename and delete
2013 2013 for f, fl in sorted(pycompat.iteritems(mresult.renamedelete)):
2014 2014 repo.ui.warn(
2015 2015 _(
2016 2016 b"note: possible conflict - %s was deleted "
2017 2017 b"and renamed to:\n"
2018 2018 )
2019 2019 % f
2020 2020 )
2021 2021 for nf in sorted(fl):
2022 2022 repo.ui.warn(b" %s\n" % nf)
2023 2023
2024 2024 ### apply phase
2025 2025 if not branchmerge: # just jump to the new rev
2026 2026 fp1, fp2, xp1, xp2 = fp2, nullid, xp2, b''
2027 2027 # If we're doing a partial update, we need to skip updating
2028 2028 # the dirstate.
2029 2029 always = matcher is None or matcher.always()
2030 2030 updatedirstate = updatedirstate and always and not wc.isinmemory()
2031 2031 if updatedirstate:
2032 2032 repo.hook(b'preupdate', throw=True, parent1=xp1, parent2=xp2)
2033 2033 # note that we're in the middle of an update
2034 2034 repo.vfs.write(b'updatestate', p2.hex())
2035 2035
2036 2036 _advertisefsmonitor(
2037 2037 repo, mresult.len((mergestatemod.ACTION_GET,)), p1.node()
2038 2038 )
2039 2039
2040 2040 wantfiledata = updatedirstate and not branchmerge
2041 2041 stats, getfiledata = applyupdates(
2042 2042 repo, mresult, wc, p2, overwrite, wantfiledata, labels=labels,
2043 2043 )
2044 2044
2045 2045 if updatedirstate:
2046 2046 with repo.dirstate.parentchange():
2047 2047 repo.setparents(fp1, fp2)
2048 2048 mergestatemod.recordupdates(
2049 2049 repo, mresult.actionsdict, branchmerge, getfiledata
2050 2050 )
2051 2051 # update completed, clear state
2052 2052 util.unlink(repo.vfs.join(b'updatestate'))
2053 2053
2054 2054 if not branchmerge:
2055 2055 repo.dirstate.setbranch(p2.branch())
2056 2056
2057 2057 # If we're updating to a location, clean up any stale temporary includes
2058 2058 # (ex: this happens during hg rebase --abort).
2059 2059 if not branchmerge:
2060 2060 sparse.prunetemporaryincludes(repo)
2061 2061
2062 2062 if updatedirstate:
2063 2063 repo.hook(
2064 2064 b'update', parent1=xp1, parent2=xp2, error=stats.unresolvedcount
2065 2065 )
2066 2066 return stats
2067 2067
2068 2068
2069 2069 def merge(ctx, labels=None, force=False, wc=None):
2070 2070 """Merge another topological branch into the working copy.
2071 2071
2072 2072 force = whether the merge was run with 'merge --force' (deprecated)
2073 2073 """
2074 2074
2075 2075 return update(
2076 2076 ctx.repo(),
2077 2077 ctx.rev(),
2078 2078 labels=labels,
2079 2079 branchmerge=True,
2080 2080 force=force,
2081 2081 mergeforce=force,
2082 2082 wc=wc,
2083 2083 )
2084 2084
2085 2085
2086 2086 def clean_update(ctx, wc=None):
2087 2087 """Do a clean update to the given commit.
2088 2088
2089 2089 This involves updating to the commit and discarding any changes in the
2090 2090 working copy.
2091 2091 """
2092 2092 return update(ctx.repo(), ctx.rev(), branchmerge=False, force=True, wc=wc)
2093 2093
2094 2094
2095 2095 def revert_to(ctx, matcher=None, wc=None):
2096 2096 """Revert the working copy to the given commit.
2097 2097
2098 2098 The working copy will keep its current parent(s) but its content will
2099 2099 be the same as in the given commit.
2100 2100 """
2101 2101
2102 2102 return update(
2103 2103 ctx.repo(),
2104 2104 ctx.rev(),
2105 2105 branchmerge=False,
2106 2106 force=True,
2107 2107 updatedirstate=False,
2108 2108 matcher=matcher,
2109 2109 wc=wc,
2110 2110 )
2111 2111
2112 2112
2113 2113 def graft(
2114 2114 repo,
2115 2115 ctx,
2116 2116 base=None,
2117 2117 labels=None,
2118 2118 keepparent=False,
2119 2119 keepconflictparent=False,
2120 2120 wctx=None,
2121 2121 ):
2122 2122 """Do a graft-like merge.
2123 2123
2124 2124 This is a merge where the merge ancestor is chosen such that one
2125 2125 or more changesets are grafted onto the current changeset. In
2126 2126 addition to the merge, this fixes up the dirstate to include only
2127 2127 a single parent (if keepparent is False) and tries to duplicate any
2128 2128 renames/copies appropriately.
2129 2129
2130 2130 ctx - changeset to rebase
2131 2131 base - merge base, or ctx.p1() if not specified
2132 2132 labels - merge labels eg ['local', 'graft']
2133 2133 keepparent - keep second parent if any
2134 2134 keepconflictparent - if unresolved, keep parent used for the merge
2135 2135
2136 2136 """
2137 2137 # If we're grafting a descendant onto an ancestor, be sure to pass
2138 2138 # mergeancestor=True to update. This does two things: 1) allows the merge if
2139 2139 # the destination is the same as the parent of the ctx (so we can use graft
2140 2140 # to copy commits), and 2) informs update that the incoming changes are
2141 2141 # newer than the destination so it doesn't prompt about "remote changed foo
2142 2142 # which local deleted".
2143 2143 # We also pass mergeancestor=True when base is the same revision as p1. 2)
2144 2144 # doesn't matter as there can't possibly be conflicts, but 1) is necessary.
2145 2145 wctx = wctx or repo[None]
2146 2146 pctx = wctx.p1()
2147 2147 base = base or ctx.p1()
2148 2148 mergeancestor = (
2149 2149 repo.changelog.isancestor(pctx.node(), ctx.node())
2150 2150 or pctx.rev() == base.rev()
2151 2151 )
2152 2152
2153 2153 stats = update(
2154 2154 repo,
2155 2155 ctx.node(),
2156 2156 True,
2157 2157 True,
2158 2158 base.node(),
2159 2159 mergeancestor=mergeancestor,
2160 2160 labels=labels,
2161 2161 wc=wctx,
2162 2162 )
2163 2163
2164 2164 if keepconflictparent and stats.unresolvedcount:
2165 2165 pother = ctx.node()
2166 2166 else:
2167 2167 pother = nullid
2168 2168 parents = ctx.parents()
2169 2169 if keepparent and len(parents) == 2 and base in parents:
2170 2170 parents.remove(base)
2171 2171 pother = parents[0].node()
2172 2172 # Never set both parents equal to each other
2173 2173 if pother == pctx.node():
2174 2174 pother = nullid
2175 2175
2176 2176 if wctx.isinmemory():
2177 2177 wctx.setparents(pctx.node(), pother)
2178 2178 # fix up dirstate for copies and renames
2179 2179 copies.graftcopies(wctx, ctx, base)
2180 2180 else:
2181 2181 with repo.dirstate.parentchange():
2182 2182 repo.setparents(pctx.node(), pother)
2183 2183 repo.dirstate.write(repo.currenttransaction())
2184 2184 # fix up dirstate for copies and renames
2185 2185 copies.graftcopies(wctx, ctx, base)
2186 2186 return stats
2187 2187
2188 2188
2189 2189 def purge(
2190 2190 repo,
2191 2191 matcher,
2192 2192 unknown=True,
2193 2193 ignored=False,
2194 2194 removeemptydirs=True,
2195 2195 removefiles=True,
2196 2196 abortonerror=False,
2197 2197 noop=False,
2198 2198 ):
2199 2199 """Purge the working directory of untracked files.
2200 2200
2201 2201 ``matcher`` is a matcher configured to scan the working directory -
2202 2202 potentially a subset.
2203 2203
2204 2204 ``unknown`` controls whether unknown files should be purged.
2205 2205
2206 2206 ``ignored`` controls whether ignored files should be purged.
2207 2207
2208 2208 ``removeemptydirs`` controls whether empty directories should be removed.
2209 2209
2210 2210 ``removefiles`` controls whether files are removed.
2211 2211
2212 2212 ``abortonerror`` causes an exception to be raised if an error occurs
2213 2213 deleting a file or directory.
2214 2214
2215 2215 ``noop`` controls whether to actually remove files. If not defined, actions
2216 2216 will be taken.
2217 2217
2218 2218 Returns an iterable of relative paths in the working directory that were
2219 2219 or would be removed.
2220 2220 """
2221 2221
2222 2222 def remove(removefn, path):
2223 2223 try:
2224 2224 removefn(path)
2225 2225 except OSError:
2226 2226 m = _(b'%s cannot be removed') % path
2227 2227 if abortonerror:
2228 2228 raise error.Abort(m)
2229 2229 else:
2230 2230 repo.ui.warn(_(b'warning: %s\n') % m)
2231 2231
2232 2232 # There's no API to copy a matcher. So mutate the passed matcher and
2233 2233 # restore it when we're done.
2234 2234 oldtraversedir = matcher.traversedir
2235 2235
2236 2236 res = []
2237 2237
2238 2238 try:
2239 2239 if removeemptydirs:
2240 2240 directories = []
2241 2241 matcher.traversedir = directories.append
2242 2242
2243 2243 status = repo.status(match=matcher, ignored=ignored, unknown=unknown)
2244 2244
2245 2245 if removefiles:
2246 2246 for f in sorted(status.unknown + status.ignored):
2247 2247 if not noop:
2248 2248 repo.ui.note(_(b'removing file %s\n') % f)
2249 2249 remove(repo.wvfs.unlink, f)
2250 2250 res.append(f)
2251 2251
2252 2252 if removeemptydirs:
2253 2253 for f in sorted(directories, reverse=True):
2254 2254 if matcher(f) and not repo.wvfs.listdir(f):
2255 2255 if not noop:
2256 2256 repo.ui.note(_(b'removing directory %s\n') % f)
2257 2257 remove(repo.wvfs.rmdir, f)
2258 2258 res.append(f)
2259 2259
2260 2260 return res
2261 2261
2262 2262 finally:
2263 2263 matcher.traversedir = oldtraversedir
General Comments 0
You need to be logged in to leave comments. Login now