PageRenderTime 51ms CodeModel.GetById 19ms RepoModel.GetById 1ms app.codeStats 0ms

/mercurial/merge.py

https://bitbucket.org/mirror/mercurial/
Python | 1149 lines | 1119 code | 5 blank | 25 comment | 14 complexity | ecd3250e9c965808f5390ce2c696ab2c MD5 | raw file
Possible License(s): GPL-2.0
  1. # merge.py - directory-level update/merge handling for Mercurial
  2. #
  3. # Copyright 2006, 2007 Matt Mackall <mpm@selenic.com>
  4. #
  5. # This software may be used and distributed according to the terms of the
  6. # GNU General Public License version 2 or any later version.
  7. import struct
  8. from node import nullid, nullrev, hex, bin
  9. from i18n import _
  10. from mercurial import obsolete
  11. import error, util, filemerge, copies, subrepo, worker, dicthelpers
  12. import errno, os, shutil
  13. _pack = struct.pack
  14. _unpack = struct.unpack
  15. def _droponode(data):
  16. # used for compatibility for v1
  17. bits = data.split("\0")
  18. bits = bits[:-2] + bits[-1:]
  19. return "\0".join(bits)
  20. class mergestate(object):
  21. '''track 3-way merge state of individual files
  22. it is stored on disk when needed. Two file are used, one with an old
  23. format, one with a new format. Both contains similar data, but the new
  24. format can store new kind of field.
  25. Current new format is a list of arbitrary record of the form:
  26. [type][length][content]
  27. Type is a single character, length is a 4 bytes integer, content is an
  28. arbitrary suites of bytes of length `length`.
  29. Type should be a letter. Capital letter are mandatory record, Mercurial
  30. should abort if they are unknown. lower case record can be safely ignored.
  31. Currently known record:
  32. L: the node of the "local" part of the merge (hexified version)
  33. O: the node of the "other" part of the merge (hexified version)
  34. F: a file to be merged entry
  35. '''
  36. statepathv1 = "merge/state"
  37. statepathv2 = "merge/state2"
  38. def __init__(self, repo):
  39. self._repo = repo
  40. self._dirty = False
  41. self._read()
  42. def reset(self, node=None, other=None):
  43. self._state = {}
  44. self._local = None
  45. self._other = None
  46. if node:
  47. self._local = node
  48. self._other = other
  49. shutil.rmtree(self._repo.join("merge"), True)
  50. self._dirty = False
  51. def _read(self):
  52. """Analyse each record content to restore a serialized state from disk
  53. This function process "record" entry produced by the de-serialization
  54. of on disk file.
  55. """
  56. self._state = {}
  57. self._local = None
  58. self._other = None
  59. records = self._readrecords()
  60. for rtype, record in records:
  61. if rtype == 'L':
  62. self._local = bin(record)
  63. elif rtype == 'O':
  64. self._other = bin(record)
  65. elif rtype == "F":
  66. bits = record.split("\0")
  67. self._state[bits[0]] = bits[1:]
  68. elif not rtype.islower():
  69. raise util.Abort(_('unsupported merge state record: %s')
  70. % rtype)
  71. self._dirty = False
  72. def _readrecords(self):
  73. """Read merge state from disk and return a list of record (TYPE, data)
  74. We read data from both v1 and v2 files and decide which one to use.
  75. V1 has been used by version prior to 2.9.1 and contains less data than
  76. v2. We read both versions and check if no data in v2 contradicts
  77. v1. If there is not contradiction we can safely assume that both v1
  78. and v2 were written at the same time and use the extract data in v2. If
  79. there is contradiction we ignore v2 content as we assume an old version
  80. of Mercurial has overwritten the mergestate file and left an old v2
  81. file around.
  82. returns list of record [(TYPE, data), ...]"""
  83. v1records = self._readrecordsv1()
  84. v2records = self._readrecordsv2()
  85. oldv2 = set() # old format version of v2 record
  86. for rec in v2records:
  87. if rec[0] == 'L':
  88. oldv2.add(rec)
  89. elif rec[0] == 'F':
  90. # drop the onode data (not contained in v1)
  91. oldv2.add(('F', _droponode(rec[1])))
  92. for rec in v1records:
  93. if rec not in oldv2:
  94. # v1 file is newer than v2 file, use it
  95. # we have to infer the "other" changeset of the merge
  96. # we cannot do better than that with v1 of the format
  97. mctx = self._repo[None].parents()[-1]
  98. v1records.append(('O', mctx.hex()))
  99. # add place holder "other" file node information
  100. # nobody is using it yet so we do no need to fetch the data
  101. # if mctx was wrong `mctx[bits[-2]]` may fails.
  102. for idx, r in enumerate(v1records):
  103. if r[0] == 'F':
  104. bits = r[1].split("\0")
  105. bits.insert(-2, '')
  106. v1records[idx] = (r[0], "\0".join(bits))
  107. return v1records
  108. else:
  109. return v2records
  110. def _readrecordsv1(self):
  111. """read on disk merge state for version 1 file
  112. returns list of record [(TYPE, data), ...]
  113. Note: the "F" data from this file are one entry short
  114. (no "other file node" entry)
  115. """
  116. records = []
  117. try:
  118. f = self._repo.opener(self.statepathv1)
  119. for i, l in enumerate(f):
  120. if i == 0:
  121. records.append(('L', l[:-1]))
  122. else:
  123. records.append(('F', l[:-1]))
  124. f.close()
  125. except IOError, err:
  126. if err.errno != errno.ENOENT:
  127. raise
  128. return records
  129. def _readrecordsv2(self):
  130. """read on disk merge state for version 2 file
  131. returns list of record [(TYPE, data), ...]
  132. """
  133. records = []
  134. try:
  135. f = self._repo.opener(self.statepathv2)
  136. data = f.read()
  137. off = 0
  138. end = len(data)
  139. while off < end:
  140. rtype = data[off]
  141. off += 1
  142. length = _unpack('>I', data[off:(off + 4)])[0]
  143. off += 4
  144. record = data[off:(off + length)]
  145. off += length
  146. records.append((rtype, record))
  147. f.close()
  148. except IOError, err:
  149. if err.errno != errno.ENOENT:
  150. raise
  151. return records
  152. def active(self):
  153. """Whether mergestate is active.
  154. Returns True if there appears to be mergestate. This is a rough proxy
  155. for "is a merge in progress."
  156. """
  157. # Check local variables before looking at filesystem for performance
  158. # reasons.
  159. return bool(self._local) or bool(self._state) or \
  160. self._repo.opener.exists(self.statepathv1) or \
  161. self._repo.opener.exists(self.statepathv2)
  162. def commit(self):
  163. """Write current state on disk (if necessary)"""
  164. if self._dirty:
  165. records = []
  166. records.append(("L", hex(self._local)))
  167. records.append(("O", hex(self._other)))
  168. for d, v in self._state.iteritems():
  169. records.append(("F", "\0".join([d] + v)))
  170. self._writerecords(records)
  171. self._dirty = False
  172. def _writerecords(self, records):
  173. """Write current state on disk (both v1 and v2)"""
  174. self._writerecordsv1(records)
  175. self._writerecordsv2(records)
  176. def _writerecordsv1(self, records):
  177. """Write current state on disk in a version 1 file"""
  178. f = self._repo.opener(self.statepathv1, "w")
  179. irecords = iter(records)
  180. lrecords = irecords.next()
  181. assert lrecords[0] == 'L'
  182. f.write(hex(self._local) + "\n")
  183. for rtype, data in irecords:
  184. if rtype == "F":
  185. f.write("%s\n" % _droponode(data))
  186. f.close()
  187. def _writerecordsv2(self, records):
  188. """Write current state on disk in a version 2 file"""
  189. f = self._repo.opener(self.statepathv2, "w")
  190. for key, data in records:
  191. assert len(key) == 1
  192. format = ">sI%is" % len(data)
  193. f.write(_pack(format, key, len(data), data))
  194. f.close()
  195. def add(self, fcl, fco, fca, fd):
  196. """add a new (potentially?) conflicting file the merge state
  197. fcl: file context for local,
  198. fco: file context for remote,
  199. fca: file context for ancestors,
  200. fd: file path of the resulting merge.
  201. note: also write the local version to the `.hg/merge` directory.
  202. """
  203. hash = util.sha1(fcl.path()).hexdigest()
  204. self._repo.opener.write("merge/" + hash, fcl.data())
  205. self._state[fd] = ['u', hash, fcl.path(),
  206. fca.path(), hex(fca.filenode()),
  207. fco.path(), hex(fco.filenode()),
  208. fcl.flags()]
  209. self._dirty = True
  210. def __contains__(self, dfile):
  211. return dfile in self._state
  212. def __getitem__(self, dfile):
  213. return self._state[dfile][0]
  214. def __iter__(self):
  215. return iter(sorted(self._state))
  216. def files(self):
  217. return self._state.keys()
  218. def mark(self, dfile, state):
  219. self._state[dfile][0] = state
  220. self._dirty = True
  221. def unresolved(self):
  222. """Obtain the paths of unresolved files."""
  223. for f, entry in self._state.items():
  224. if entry[0] == 'u':
  225. yield f
  226. def resolve(self, dfile, wctx, labels=None):
  227. """rerun merge process for file path `dfile`"""
  228. if self[dfile] == 'r':
  229. return 0
  230. stateentry = self._state[dfile]
  231. state, hash, lfile, afile, anode, ofile, onode, flags = stateentry
  232. octx = self._repo[self._other]
  233. fcd = wctx[dfile]
  234. fco = octx[ofile]
  235. fca = self._repo.filectx(afile, fileid=anode)
  236. # "premerge" x flags
  237. flo = fco.flags()
  238. fla = fca.flags()
  239. if 'x' in flags + flo + fla and 'l' not in flags + flo + fla:
  240. if fca.node() == nullid:
  241. self._repo.ui.warn(_('warning: cannot merge flags for %s\n') %
  242. afile)
  243. elif flags == fla:
  244. flags = flo
  245. # restore local
  246. f = self._repo.opener("merge/" + hash)
  247. self._repo.wwrite(dfile, f.read(), flags)
  248. f.close()
  249. r = filemerge.filemerge(self._repo, self._local, lfile, fcd, fco, fca,
  250. labels=labels)
  251. if r is None:
  252. # no real conflict
  253. del self._state[dfile]
  254. self._dirty = True
  255. elif not r:
  256. self.mark(dfile, 'r')
  257. return r
  258. def _checkunknownfile(repo, wctx, mctx, f):
  259. return (not repo.dirstate._ignore(f)
  260. and os.path.isfile(repo.wjoin(f))
  261. and repo.wopener.audit.check(f)
  262. and repo.dirstate.normalize(f) not in repo.dirstate
  263. and mctx[f].cmp(wctx[f]))
  264. def _checkunknown(repo, wctx, mctx):
  265. "check for collisions between unknown files and files in mctx"
  266. error = False
  267. for f in mctx:
  268. if f not in wctx and _checkunknownfile(repo, wctx, mctx, f):
  269. error = True
  270. wctx._repo.ui.warn(_("%s: untracked file differs\n") % f)
  271. if error:
  272. raise util.Abort(_("untracked files in working directory differ "
  273. "from files in requested revision"))
  274. def _forgetremoved(wctx, mctx, branchmerge):
  275. """
  276. Forget removed files
  277. If we're jumping between revisions (as opposed to merging), and if
  278. neither the working directory nor the target rev has the file,
  279. then we need to remove it from the dirstate, to prevent the
  280. dirstate from listing the file when it is no longer in the
  281. manifest.
  282. If we're merging, and the other revision has removed a file
  283. that is not present in the working directory, we need to mark it
  284. as removed.
  285. """
  286. ractions = []
  287. factions = xactions = []
  288. if branchmerge:
  289. xactions = ractions
  290. for f in wctx.deleted():
  291. if f not in mctx:
  292. xactions.append((f, None, "forget deleted"))
  293. if not branchmerge:
  294. for f in wctx.removed():
  295. if f not in mctx:
  296. factions.append((f, None, "forget removed"))
  297. return ractions, factions
  298. def _checkcollision(repo, wmf, actions):
  299. # build provisional merged manifest up
  300. pmmf = set(wmf)
  301. if actions:
  302. # k, dr, e and rd are no-op
  303. for m in 'a', 'f', 'g', 'cd', 'dc':
  304. for f, args, msg in actions[m]:
  305. pmmf.add(f)
  306. for f, args, msg in actions['r']:
  307. pmmf.discard(f)
  308. for f, args, msg in actions['dm']:
  309. f2, flags = args
  310. pmmf.discard(f2)
  311. pmmf.add(f)
  312. for f, args, msg in actions['dg']:
  313. f2, flags = args
  314. pmmf.add(f)
  315. for f, args, msg in actions['m']:
  316. f1, f2, fa, move, anc = args
  317. if move:
  318. pmmf.discard(f1)
  319. pmmf.add(f)
  320. # check case-folding collision in provisional merged manifest
  321. foldmap = {}
  322. for f in sorted(pmmf):
  323. fold = util.normcase(f)
  324. if fold in foldmap:
  325. raise util.Abort(_("case-folding collision between %s and %s")
  326. % (f, foldmap[fold]))
  327. foldmap[fold] = f
  328. def manifestmerge(repo, wctx, p2, pa, branchmerge, force, partial,
  329. acceptremote, followcopies):
  330. """
  331. Merge p1 and p2 with ancestor pa and generate merge action list
  332. branchmerge and force are as passed in to update
  333. partial = function to filter file lists
  334. acceptremote = accept the incoming changes without prompting
  335. """
  336. actions = dict((m, []) for m in 'a f g cd dc r dm dg m dr e rd k'.split())
  337. copy, movewithdir = {}, {}
  338. # manifests fetched in order are going to be faster, so prime the caches
  339. [x.manifest() for x in
  340. sorted(wctx.parents() + [p2, pa], key=lambda x: x.rev())]
  341. if followcopies:
  342. ret = copies.mergecopies(repo, wctx, p2, pa)
  343. copy, movewithdir, diverge, renamedelete = ret
  344. for of, fl in diverge.iteritems():
  345. actions['dr'].append((of, (fl,), "divergent renames"))
  346. for of, fl in renamedelete.iteritems():
  347. actions['rd'].append((of, (fl,), "rename and delete"))
  348. repo.ui.note(_("resolving manifests\n"))
  349. repo.ui.debug(" branchmerge: %s, force: %s, partial: %s\n"
  350. % (bool(branchmerge), bool(force), bool(partial)))
  351. repo.ui.debug(" ancestor: %s, local: %s, remote: %s\n" % (pa, wctx, p2))
  352. m1, m2, ma = wctx.manifest(), p2.manifest(), pa.manifest()
  353. copied = set(copy.values())
  354. copied.update(movewithdir.values())
  355. if '.hgsubstate' in m1:
  356. # check whether sub state is modified
  357. for s in sorted(wctx.substate):
  358. if wctx.sub(s).dirty():
  359. m1['.hgsubstate'] += "+"
  360. break
  361. aborts = []
  362. # Compare manifests
  363. fdiff = dicthelpers.diff(m1, m2)
  364. flagsdiff = m1.flagsdiff(m2)
  365. diff12 = dicthelpers.join(fdiff, flagsdiff)
  366. for f, (n12, fl12) in diff12.iteritems():
  367. if n12:
  368. n1, n2 = n12
  369. else: # file contents didn't change, but flags did
  370. n1 = n2 = m1.get(f, None)
  371. if n1 is None:
  372. # Since n1 == n2, the file isn't present in m2 either. This
  373. # means that the file was removed or deleted locally and
  374. # removed remotely, but that residual entries remain in flags.
  375. # This can happen in manifests generated by workingctx.
  376. continue
  377. if fl12:
  378. fl1, fl2 = fl12
  379. else: # flags didn't change, file contents did
  380. fl1 = fl2 = m1.flags(f)
  381. if partial and not partial(f):
  382. continue
  383. if n1 and n2:
  384. fa = f
  385. a = ma.get(f, nullid)
  386. if a == nullid:
  387. fa = copy.get(f, f)
  388. # Note: f as default is wrong - we can't really make a 3-way
  389. # merge without an ancestor file.
  390. fla = ma.flags(fa)
  391. nol = 'l' not in fl1 + fl2 + fla
  392. if n2 == a and fl2 == fla:
  393. actions['k'].append((f, (), "keep")) # remote unchanged
  394. elif n1 == a and fl1 == fla: # local unchanged - use remote
  395. if n1 == n2: # optimization: keep local content
  396. actions['e'].append((f, (fl2,), "update permissions"))
  397. else:
  398. actions['g'].append((f, (fl2,), "remote is newer"))
  399. elif nol and n2 == a: # remote only changed 'x'
  400. actions['e'].append((f, (fl2,), "update permissions"))
  401. elif nol and n1 == a: # local only changed 'x'
  402. actions['g'].append((f, (fl1,), "remote is newer"))
  403. else: # both changed something
  404. actions['m'].append((f, (f, f, fa, False, pa.node()),
  405. "versions differ"))
  406. elif f in copied: # files we'll deal with on m2 side
  407. pass
  408. elif n1 and f in movewithdir: # directory rename, move local
  409. f2 = movewithdir[f]
  410. actions['dm'].append((f2, (f, fl1),
  411. "remote directory rename - move from " + f))
  412. elif n1 and f in copy:
  413. f2 = copy[f]
  414. actions['m'].append((f, (f, f2, f2, False, pa.node()),
  415. "local copied/moved from " + f2))
  416. elif n1 and f in ma: # clean, a different, no remote
  417. if n1 != ma[f]:
  418. if acceptremote:
  419. actions['r'].append((f, None, "remote delete"))
  420. else:
  421. actions['cd'].append((f, None, "prompt changed/deleted"))
  422. elif n1[20:] == "a": # added, no remote
  423. actions['f'].append((f, None, "remote deleted"))
  424. else:
  425. actions['r'].append((f, None, "other deleted"))
  426. elif n2 and f in movewithdir:
  427. f2 = movewithdir[f]
  428. actions['dg'].append((f2, (f, fl2),
  429. "local directory rename - get from " + f))
  430. elif n2 and f in copy:
  431. f2 = copy[f]
  432. if f2 in m2:
  433. actions['m'].append((f, (f2, f, f2, False, pa.node()),
  434. "remote copied from " + f2))
  435. else:
  436. actions['m'].append((f, (f2, f, f2, True, pa.node()),
  437. "remote moved from " + f2))
  438. elif n2 and f not in ma:
  439. # local unknown, remote created: the logic is described by the
  440. # following table:
  441. #
  442. # force branchmerge different | action
  443. # n * n | get
  444. # n * y | abort
  445. # y n * | get
  446. # y y n | get
  447. # y y y | merge
  448. #
  449. # Checking whether the files are different is expensive, so we
  450. # don't do that when we can avoid it.
  451. if force and not branchmerge:
  452. actions['g'].append((f, (fl2,), "remote created"))
  453. else:
  454. different = _checkunknownfile(repo, wctx, p2, f)
  455. if force and branchmerge and different:
  456. # FIXME: This is wrong - f is not in ma ...
  457. actions['m'].append((f, (f, f, f, False, pa.node()),
  458. "remote differs from untracked local"))
  459. elif not force and different:
  460. aborts.append((f, "ud"))
  461. else:
  462. actions['g'].append((f, (fl2,), "remote created"))
  463. elif n2 and n2 != ma[f]:
  464. different = _checkunknownfile(repo, wctx, p2, f)
  465. if not force and different:
  466. aborts.append((f, "ud"))
  467. else:
  468. # if different: old untracked f may be overwritten and lost
  469. if acceptremote:
  470. actions['g'].append((f, (m2.flags(f),),
  471. "remote recreating"))
  472. else:
  473. actions['dc'].append((f, (m2.flags(f),),
  474. "prompt deleted/changed"))
  475. for f, m in sorted(aborts):
  476. if m == "ud":
  477. repo.ui.warn(_("%s: untracked file differs\n") % f)
  478. else: assert False, m
  479. if aborts:
  480. raise util.Abort(_("untracked files in working directory differ "
  481. "from files in requested revision"))
  482. if not util.checkcase(repo.path):
  483. # check collision between files only in p2 for clean update
  484. if (not branchmerge and
  485. (force or not wctx.dirty(missing=True, branch=False))):
  486. _checkcollision(repo, m2, None)
  487. else:
  488. _checkcollision(repo, m1, actions)
  489. return actions
  490. def batchremove(repo, actions):
  491. """apply removes to the working directory
  492. yields tuples for progress updates
  493. """
  494. verbose = repo.ui.verbose
  495. unlink = util.unlinkpath
  496. wjoin = repo.wjoin
  497. audit = repo.wopener.audit
  498. i = 0
  499. for f, args, msg in actions:
  500. repo.ui.debug(" %s: %s -> r\n" % (f, msg))
  501. if verbose:
  502. repo.ui.note(_("removing %s\n") % f)
  503. audit(f)
  504. try:
  505. unlink(wjoin(f), ignoremissing=True)
  506. except OSError, inst:
  507. repo.ui.warn(_("update failed to remove %s: %s!\n") %
  508. (f, inst.strerror))
  509. if i == 100:
  510. yield i, f
  511. i = 0
  512. i += 1
  513. if i > 0:
  514. yield i, f
  515. def batchget(repo, mctx, actions):
  516. """apply gets to the working directory
  517. mctx is the context to get from
  518. yields tuples for progress updates
  519. """
  520. verbose = repo.ui.verbose
  521. fctx = mctx.filectx
  522. wwrite = repo.wwrite
  523. i = 0
  524. for f, args, msg in actions:
  525. repo.ui.debug(" %s: %s -> g\n" % (f, msg))
  526. if verbose:
  527. repo.ui.note(_("getting %s\n") % f)
  528. wwrite(f, fctx(f).data(), args[0])
  529. if i == 100:
  530. yield i, f
  531. i = 0
  532. i += 1
  533. if i > 0:
  534. yield i, f
  535. def applyupdates(repo, actions, wctx, mctx, overwrite, labels=None):
  536. """apply the merge action list to the working directory
  537. wctx is the working copy context
  538. mctx is the context to be merged into the working copy
  539. Return a tuple of counts (updated, merged, removed, unresolved) that
  540. describes how many files were affected by the update.
  541. """
  542. updated, merged, removed, unresolved = 0, 0, 0, 0
  543. ms = mergestate(repo)
  544. ms.reset(wctx.p1().node(), mctx.node())
  545. moves = []
  546. for m, l in actions.items():
  547. l.sort()
  548. # prescan for merges
  549. for f, args, msg in actions['m']:
  550. f1, f2, fa, move, anc = args
  551. if f == '.hgsubstate': # merged internally
  552. continue
  553. repo.ui.debug(" preserving %s for resolve of %s\n" % (f1, f))
  554. fcl = wctx[f1]
  555. fco = mctx[f2]
  556. actx = repo[anc]
  557. if fa in actx:
  558. fca = actx[fa]
  559. else:
  560. fca = repo.filectx(f1, fileid=nullrev)
  561. ms.add(fcl, fco, fca, f)
  562. if f1 != f and move:
  563. moves.append(f1)
  564. audit = repo.wopener.audit
  565. _updating = _('updating')
  566. _files = _('files')
  567. progress = repo.ui.progress
  568. # remove renamed files after safely stored
  569. for f in moves:
  570. if os.path.lexists(repo.wjoin(f)):
  571. repo.ui.debug("removing %s\n" % f)
  572. audit(f)
  573. util.unlinkpath(repo.wjoin(f))
  574. numupdates = sum(len(l) for m, l in actions.items() if m != 'k')
  575. if [a for a in actions['r'] if a[0] == '.hgsubstate']:
  576. subrepo.submerge(repo, wctx, mctx, wctx, overwrite)
  577. # remove in parallel (must come first)
  578. z = 0
  579. prog = worker.worker(repo.ui, 0.001, batchremove, (repo,), actions['r'])
  580. for i, item in prog:
  581. z += i
  582. progress(_updating, z, item=item, total=numupdates, unit=_files)
  583. removed = len(actions['r'])
  584. # get in parallel
  585. prog = worker.worker(repo.ui, 0.001, batchget, (repo, mctx), actions['g'])
  586. for i, item in prog:
  587. z += i
  588. progress(_updating, z, item=item, total=numupdates, unit=_files)
  589. updated = len(actions['g'])
  590. if [a for a in actions['g'] if a[0] == '.hgsubstate']:
  591. subrepo.submerge(repo, wctx, mctx, wctx, overwrite)
  592. # forget (manifest only, just log it) (must come first)
  593. for f, args, msg in actions['f']:
  594. repo.ui.debug(" %s: %s -> f\n" % (f, msg))
  595. z += 1
  596. progress(_updating, z, item=f, total=numupdates, unit=_files)
  597. # re-add (manifest only, just log it)
  598. for f, args, msg in actions['a']:
  599. repo.ui.debug(" %s: %s -> a\n" % (f, msg))
  600. z += 1
  601. progress(_updating, z, item=f, total=numupdates, unit=_files)
  602. # keep (noop, just log it)
  603. for f, args, msg in actions['k']:
  604. repo.ui.debug(" %s: %s -> k\n" % (f, msg))
  605. # no progress
  606. # merge
  607. for f, args, msg in actions['m']:
  608. repo.ui.debug(" %s: %s -> m\n" % (f, msg))
  609. z += 1
  610. progress(_updating, z, item=f, total=numupdates, unit=_files)
  611. f1, f2, fa, move, anc = args
  612. if f == '.hgsubstate': # subrepo states need updating
  613. subrepo.submerge(repo, wctx, mctx, wctx.ancestor(mctx),
  614. overwrite)
  615. continue
  616. audit(f)
  617. r = ms.resolve(f, wctx, labels=labels)
  618. if r is not None and r > 0:
  619. unresolved += 1
  620. else:
  621. if r is None:
  622. updated += 1
  623. else:
  624. merged += 1
  625. # directory rename, move local
  626. for f, args, msg in actions['dm']:
  627. repo.ui.debug(" %s: %s -> dm\n" % (f, msg))
  628. z += 1
  629. progress(_updating, z, item=f, total=numupdates, unit=_files)
  630. f0, flags = args
  631. repo.ui.note(_("moving %s to %s\n") % (f0, f))
  632. audit(f)
  633. repo.wwrite(f, wctx.filectx(f0).data(), flags)
  634. util.unlinkpath(repo.wjoin(f0))
  635. updated += 1
  636. # local directory rename, get
  637. for f, args, msg in actions['dg']:
  638. repo.ui.debug(" %s: %s -> dg\n" % (f, msg))
  639. z += 1
  640. progress(_updating, z, item=f, total=numupdates, unit=_files)
  641. f0, flags = args
  642. repo.ui.note(_("getting %s to %s\n") % (f0, f))
  643. repo.wwrite(f, mctx.filectx(f0).data(), flags)
  644. updated += 1
  645. # divergent renames
  646. for f, args, msg in actions['dr']:
  647. repo.ui.debug(" %s: %s -> dr\n" % (f, msg))
  648. z += 1
  649. progress(_updating, z, item=f, total=numupdates, unit=_files)
  650. fl, = args
  651. repo.ui.warn(_("note: possible conflict - %s was renamed "
  652. "multiple times to:\n") % f)
  653. for nf in fl:
  654. repo.ui.warn(" %s\n" % nf)
  655. # rename and delete
  656. for f, args, msg in actions['rd']:
  657. repo.ui.debug(" %s: %s -> rd\n" % (f, msg))
  658. z += 1
  659. progress(_updating, z, item=f, total=numupdates, unit=_files)
  660. fl, = args
  661. repo.ui.warn(_("note: possible conflict - %s was deleted "
  662. "and renamed to:\n") % f)
  663. for nf in fl:
  664. repo.ui.warn(" %s\n" % nf)
  665. # exec
  666. for f, args, msg in actions['e']:
  667. repo.ui.debug(" %s: %s -> e\n" % (f, msg))
  668. z += 1
  669. progress(_updating, z, item=f, total=numupdates, unit=_files)
  670. flags, = args
  671. audit(f)
  672. util.setflags(repo.wjoin(f), 'l' in flags, 'x' in flags)
  673. updated += 1
  674. ms.commit()
  675. progress(_updating, None, total=numupdates, unit=_files)
  676. return updated, merged, removed, unresolved
  677. def calculateupdates(repo, wctx, mctx, ancestors, branchmerge, force, partial,
  678. acceptremote, followcopies):
  679. "Calculate the actions needed to merge mctx into wctx using ancestors"
  680. if len(ancestors) == 1: # default
  681. actions = manifestmerge(repo, wctx, mctx, ancestors[0],
  682. branchmerge, force,
  683. partial, acceptremote, followcopies)
  684. else: # only when merge.preferancestor=* - experimentalish code
  685. repo.ui.status(
  686. _("note: merging %s and %s using bids from ancestors %s\n") %
  687. (wctx, mctx, _(' and ').join(str(anc) for anc in ancestors)))
  688. # Call for bids
  689. fbids = {} # mapping filename to bids (action method to list af actions)
  690. for ancestor in ancestors:
  691. repo.ui.note(_('\ncalculating bids for ancestor %s\n') % ancestor)
  692. actions = manifestmerge(repo, wctx, mctx, ancestor,
  693. branchmerge, force,
  694. partial, acceptremote, followcopies)
  695. for m, l in sorted(actions.items()):
  696. for a in l:
  697. f, args, msg = a
  698. repo.ui.debug(' %s: %s -> %s\n' % (f, msg, m))
  699. if f in fbids:
  700. d = fbids[f]
  701. if m in d:
  702. d[m].append(a)
  703. else:
  704. d[m] = [a]
  705. else:
  706. fbids[f] = {m: [a]}
  707. # Pick the best bid for each file
  708. repo.ui.note(_('\nauction for merging merge bids\n'))
  709. actions = dict((m, []) for m in actions.keys())
  710. for f, bids in sorted(fbids.items()):
  711. # bids is a mapping from action method to list af actions
  712. # Consensus?
  713. if len(bids) == 1: # all bids are the same kind of method
  714. m, l = bids.items()[0]
  715. if util.all(a == l[0] for a in l[1:]): # len(bids) is > 1
  716. repo.ui.note(" %s: consensus for %s\n" % (f, m))
  717. actions[m].append(l[0])
  718. continue
  719. # If keep is an option, just do it.
  720. if "k" in bids:
  721. repo.ui.note(" %s: picking 'keep' action\n" % f)
  722. actions['k'].append(bids["k"][0])
  723. continue
  724. # If there are gets and they all agree [how could they not?], do it.
  725. if "g" in bids:
  726. ga0 = bids["g"][0]
  727. if util.all(a == ga0 for a in bids["g"][1:]):
  728. repo.ui.note(" %s: picking 'get' action\n" % f)
  729. actions['g'].append(ga0)
  730. continue
  731. # TODO: Consider other simple actions such as mode changes
  732. # Handle inefficient democrazy.
  733. repo.ui.note(_(' %s: multiple bids for merge action:\n') % f)
  734. for m, l in sorted(bids.items()):
  735. for _f, args, msg in l:
  736. repo.ui.note(' %s -> %s\n' % (msg, m))
  737. # Pick random action. TODO: Instead, prompt user when resolving
  738. m, l = bids.items()[0]
  739. repo.ui.warn(_(' %s: ambiguous merge - picked %s action\n') %
  740. (f, m))
  741. actions[m].append(l[0])
  742. continue
  743. repo.ui.note(_('end of auction\n\n'))
  744. # Prompt and create actions. TODO: Move this towards resolve phase.
  745. for f, args, msg in actions['cd']:
  746. if repo.ui.promptchoice(
  747. _("local changed %s which remote deleted\n"
  748. "use (c)hanged version or (d)elete?"
  749. "$$ &Changed $$ &Delete") % f, 0):
  750. actions['r'].append((f, None, "prompt delete"))
  751. else:
  752. actions['a'].append((f, None, "prompt keep"))
  753. del actions['cd'][:]
  754. for f, args, msg in actions['dc']:
  755. flags, = args
  756. if repo.ui.promptchoice(
  757. _("remote changed %s which local deleted\n"
  758. "use (c)hanged version or leave (d)eleted?"
  759. "$$ &Changed $$ &Deleted") % f, 0) == 0:
  760. actions['g'].append((f, (flags,), "prompt recreating"))
  761. del actions['dc'][:]
  762. if wctx.rev() is None:
  763. ractions, factions = _forgetremoved(wctx, mctx, branchmerge)
  764. actions['r'].extend(ractions)
  765. actions['f'].extend(factions)
  766. return actions
  767. def recordupdates(repo, actions, branchmerge):
  768. "record merge actions to the dirstate"
  769. # remove (must come first)
  770. for f, args, msg in actions['r']:
  771. if branchmerge:
  772. repo.dirstate.remove(f)
  773. else:
  774. repo.dirstate.drop(f)
  775. # forget (must come first)
  776. for f, args, msg in actions['f']:
  777. repo.dirstate.drop(f)
  778. # re-add
  779. for f, args, msg in actions['a']:
  780. if not branchmerge:
  781. repo.dirstate.add(f)
  782. # exec change
  783. for f, args, msg in actions['e']:
  784. repo.dirstate.normallookup(f)
  785. # keep
  786. for f, args, msg in actions['k']:
  787. pass
  788. # get
  789. for f, args, msg in actions['g']:
  790. if branchmerge:
  791. repo.dirstate.otherparent(f)
  792. else:
  793. repo.dirstate.normal(f)
  794. # merge
  795. for f, args, msg in actions['m']:
  796. f1, f2, fa, move, anc = args
  797. if branchmerge:
  798. # We've done a branch merge, mark this file as merged
  799. # so that we properly record the merger later
  800. repo.dirstate.merge(f)
  801. if f1 != f2: # copy/rename
  802. if move:
  803. repo.dirstate.remove(f1)
  804. if f1 != f:
  805. repo.dirstate.copy(f1, f)
  806. else:
  807. repo.dirstate.copy(f2, f)
  808. else:
  809. # We've update-merged a locally modified file, so
  810. # we set the dirstate to emulate a normal checkout
  811. # of that file some time in the past. Thus our
  812. # merge will appear as a normal local file
  813. # modification.
  814. if f2 == f: # file not locally copied/moved
  815. repo.dirstate.normallookup(f)
  816. if move:
  817. repo.dirstate.drop(f1)
  818. # directory rename, move local
  819. for f, args, msg in actions['dm']:
  820. f0, flag = args
  821. if f0 not in repo.dirstate:
  822. # untracked file moved
  823. continue
  824. if branchmerge:
  825. repo.dirstate.add(f)
  826. repo.dirstate.remove(f0)
  827. repo.dirstate.copy(f0, f)
  828. else:
  829. repo.dirstate.normal(f)
  830. repo.dirstate.drop(f0)
  831. # directory rename, get
  832. for f, args, msg in actions['dg']:
  833. f0, flag = args
  834. if branchmerge:
  835. repo.dirstate.add(f)
  836. repo.dirstate.copy(f0, f)
  837. else:
  838. repo.dirstate.normal(f)
  839. def update(repo, node, branchmerge, force, partial, ancestor=None,
  840. mergeancestor=False, labels=None):
  841. """
  842. Perform a merge between the working directory and the given node
  843. node = the node to update to, or None if unspecified
  844. branchmerge = whether to merge between branches
  845. force = whether to force branch merging or file overwriting
  846. partial = a function to filter file lists (dirstate not updated)
  847. mergeancestor = whether it is merging with an ancestor. If true,
  848. we should accept the incoming changes for any prompts that occur.
  849. If false, merging with an ancestor (fast-forward) is only allowed
  850. between different named branches. This flag is used by rebase extension
  851. as a temporary fix and should be avoided in general.
  852. The table below shows all the behaviors of the update command
  853. given the -c and -C or no options, whether the working directory
  854. is dirty, whether a revision is specified, and the relationship of
  855. the parent rev to the target rev (linear, on the same named
  856. branch, or on another named branch).
  857. This logic is tested by test-update-branches.t.
  858. -c -C dirty rev | linear same cross
  859. n n n n | ok (1) x
  860. n n n y | ok ok ok
  861. n n y n | merge (2) (2)
  862. n n y y | merge (3) (3)
  863. n y * * | --- discard ---
  864. y n y * | --- (4) ---
  865. y n n * | --- ok ---
  866. y y * * | --- (5) ---
  867. x = can't happen
  868. * = don't-care
  869. 1 = abort: not a linear update (merge or update --check to force update)
  870. 2 = abort: uncommitted changes (commit and merge, or update --clean to
  871. discard changes)
  872. 3 = abort: uncommitted changes (commit or update --clean to discard changes)
  873. 4 = abort: uncommitted changes (checked in commands.py)
  874. 5 = incompatible options (checked in commands.py)
  875. Return the same tuple as applyupdates().
  876. """
  877. onode = node
  878. wlock = repo.wlock()
  879. try:
  880. wc = repo[None]
  881. pl = wc.parents()
  882. p1 = pl[0]
  883. pas = [None]
  884. if ancestor:
  885. pas = [repo[ancestor]]
  886. if node is None:
  887. # Here is where we should consider bookmarks, divergent bookmarks,
  888. # foreground changesets (successors), and tip of current branch;
  889. # but currently we are only checking the branch tips.
  890. try:
  891. node = repo.branchtip(wc.branch())
  892. except error.RepoLookupError:
  893. if wc.branch() == "default": # no default branch!
  894. node = repo.lookup("tip") # update to tip
  895. else:
  896. raise util.Abort(_("branch %s not found") % wc.branch())
  897. if p1.obsolete() and not p1.children():
  898. # allow updating to successors
  899. successors = obsolete.successorssets(repo, p1.node())
  900. # behavior of certain cases is as follows,
  901. #
  902. # divergent changesets: update to highest rev, similar to what
  903. # is currently done when there are more than one head
  904. # (i.e. 'tip')
  905. #
  906. # replaced changesets: same as divergent except we know there
  907. # is no conflict
  908. #
  909. # pruned changeset: no update is done; though, we could
  910. # consider updating to the first non-obsolete parent,
  911. # similar to what is current done for 'hg prune'
  912. if successors:
  913. # flatten the list here handles both divergent (len > 1)
  914. # and the usual case (len = 1)
  915. successors = [n for sub in successors for n in sub]
  916. # get the max revision for the given successors set,
  917. # i.e. the 'tip' of a set
  918. node = repo.revs("max(%ln)", successors)[0]
  919. pas = [p1]
  920. overwrite = force and not branchmerge
  921. p2 = repo[node]
  922. if pas[0] is None:
  923. if repo.ui.config("merge", "preferancestor") == '*':
  924. cahs = repo.changelog.commonancestorsheads(p1.node(), p2.node())
  925. pas = [repo[anc] for anc in (sorted(cahs) or [nullid])]
  926. else:
  927. pas = [p1.ancestor(p2, warn=True)]
  928. fp1, fp2, xp1, xp2 = p1.node(), p2.node(), str(p1), str(p2)
  929. ### check phase
  930. if not overwrite and len(pl) > 1:
  931. raise util.Abort(_("outstanding uncommitted merges"))
  932. if branchmerge:
  933. if pas == [p2]:
  934. raise util.Abort(_("merging with a working directory ancestor"
  935. " has no effect"))
  936. elif pas == [p1]:
  937. if not mergeancestor and p1.branch() == p2.branch():
  938. raise util.Abort(_("nothing to merge"),
  939. hint=_("use 'hg update' "
  940. "or check 'hg heads'"))
  941. if not force and (wc.files() or wc.deleted()):
  942. raise util.Abort(_("uncommitted changes"),
  943. hint=_("use 'hg status' to list changes"))
  944. for s in sorted(wc.substate):
  945. if wc.sub(s).dirty():
  946. raise util.Abort(_("uncommitted changes in "
  947. "subrepository '%s'") % s)
  948. elif not overwrite:
  949. if p1 == p2: # no-op update
  950. # call the hooks and exit early
  951. repo.hook('preupdate', throw=True, parent1=xp2, parent2='')
  952. repo.hook('update', parent1=xp2, parent2='', error=0)
  953. return 0, 0, 0, 0
  954. if pas not in ([p1], [p2]): # nonlinear
  955. dirty = wc.dirty(missing=True)
  956. if dirty or onode is None:
  957. # Branching is a bit strange to ensure we do the minimal
  958. # amount of call to obsolete.background.
  959. foreground = obsolete.foreground(repo, [p1.node()])
  960. # note: the <node> variable contains a random identifier
  961. if repo[node].node() in foreground:
  962. pas = [p1] # allow updating to successors
  963. elif dirty:
  964. msg = _("uncommitted changes")
  965. if onode is None:
  966. hint = _("commit and merge, or update --clean to"
  967. " discard changes")
  968. else:
  969. hint = _("commit or update --clean to discard"
  970. " changes")
  971. raise util.Abort(msg, hint=hint)
  972. else: # node is none
  973. msg = _("not a linear update")
  974. hint = _("merge or update --check to force update")
  975. raise util.Abort(msg, hint=hint)
  976. else:
  977. # Allow jumping branches if clean and specific rev given
  978. pas = [p1]
  979. followcopies = False
  980. if overwrite:
  981. pas = [wc]
  982. elif pas == [p2]: # backwards
  983. pas = [wc.p1()]
  984. elif not branchmerge and not wc.dirty(missing=True):
  985. pass
  986. elif pas[0] and repo.ui.configbool("merge", "followcopies", True):
  987. followcopies = True
  988. ### calculate phase
  989. actions = calculateupdates(repo, wc, p2, pas, branchmerge, force,
  990. partial, mergeancestor, followcopies)
  991. ### apply phase
  992. if not branchmerge: # just jump to the new rev
  993. fp1, fp2, xp1, xp2 = fp2, nullid, xp2, ''
  994. if not partial:
  995. repo.hook('preupdate', throw=True, parent1=xp1, parent2=xp2)
  996. # note that we're in the middle of an update
  997. repo.vfs.write('updatestate', p2.hex())
  998. stats = applyupdates(repo, actions, wc, p2, overwrite, labels=labels)
  999. if not partial:
  1000. repo.setparents(fp1, fp2)
  1001. recordupdates(repo, actions, branchmerge)
  1002. # update completed, clear state
  1003. util.unlink(repo.join('updatestate'))
  1004. if not branchmerge:
  1005. repo.dirstate.setbranch(p2.branch())
  1006. finally:
  1007. wlock.release()
  1008. if not partial:
  1009. repo.hook('update', parent1=xp1, parent2=xp2, error=stats[3])
  1010. return stats