PageRenderTime 68ms CodeModel.GetById 36ms RepoModel.GetById 0ms app.codeStats 0ms

/mercurial/hg.py

https://bitbucket.org/mirror/mercurial/
Python | 661 lines | 611 code | 23 blank | 27 comment | 39 complexity | f4c5cc2bc360769cdc8fd47657f21eb3 MD5 | raw file
Possible License(s): GPL-2.0
  1. # hg.py - repository classes for mercurial
  2. #
  3. # Copyright 2005-2007 Matt Mackall <mpm@selenic.com>
  4. # Copyright 2006 Vadim Gelfer <vadim.gelfer@gmail.com>
  5. #
  6. # This software may be used and distributed according to the terms of the
  7. # GNU General Public License version 2 or any later version.
  8. from i18n import _
  9. from lock import release
  10. from node import hex, nullid
  11. import localrepo, bundlerepo, unionrepo, httppeer, sshpeer, statichttprepo
  12. import bookmarks, lock, util, extensions, error, node, scmutil, phases, url
  13. import cmdutil, discovery
  14. import merge as mergemod
  15. import verify as verifymod
  16. import errno, os, shutil
  17. def _local(path):
  18. path = util.expandpath(util.urllocalpath(path))
  19. return (os.path.isfile(path) and bundlerepo or localrepo)
  20. def addbranchrevs(lrepo, other, branches, revs):
  21. peer = other.peer() # a courtesy to callers using a localrepo for other
  22. hashbranch, branches = branches
  23. if not hashbranch and not branches:
  24. return revs or None, revs and revs[0] or None
  25. revs = revs and list(revs) or []
  26. if not peer.capable('branchmap'):
  27. if branches:
  28. raise util.Abort(_("remote branch lookup not supported"))
  29. revs.append(hashbranch)
  30. return revs, revs[0]
  31. branchmap = peer.branchmap()
  32. def primary(branch):
  33. if branch == '.':
  34. if not lrepo:
  35. raise util.Abort(_("dirstate branch not accessible"))
  36. branch = lrepo.dirstate.branch()
  37. if branch in branchmap:
  38. revs.extend(node.hex(r) for r in reversed(branchmap[branch]))
  39. return True
  40. else:
  41. return False
  42. for branch in branches:
  43. if not primary(branch):
  44. raise error.RepoLookupError(_("unknown branch '%s'") % branch)
  45. if hashbranch:
  46. if not primary(hashbranch):
  47. revs.append(hashbranch)
  48. return revs, revs[0]
  49. def parseurl(path, branches=None):
  50. '''parse url#branch, returning (url, (branch, branches))'''
  51. u = util.url(path)
  52. branch = None
  53. if u.fragment:
  54. branch = u.fragment
  55. u.fragment = None
  56. return str(u), (branch, branches or [])
  57. schemes = {
  58. 'bundle': bundlerepo,
  59. 'union': unionrepo,
  60. 'file': _local,
  61. 'http': httppeer,
  62. 'https': httppeer,
  63. 'ssh': sshpeer,
  64. 'static-http': statichttprepo,
  65. }
  66. def _peerlookup(path):
  67. u = util.url(path)
  68. scheme = u.scheme or 'file'
  69. thing = schemes.get(scheme) or schemes['file']
  70. try:
  71. return thing(path)
  72. except TypeError:
  73. return thing
  74. def islocal(repo):
  75. '''return true if repo (or path pointing to repo) is local'''
  76. if isinstance(repo, str):
  77. try:
  78. return _peerlookup(repo).islocal(repo)
  79. except AttributeError:
  80. return False
  81. return repo.local()
  82. def openpath(ui, path):
  83. '''open path with open if local, url.open if remote'''
  84. pathurl = util.url(path, parsequery=False, parsefragment=False)
  85. if pathurl.islocal():
  86. return util.posixfile(pathurl.localpath(), 'rb')
  87. else:
  88. return url.open(ui, path)
  89. # a list of (ui, repo) functions called for wire peer initialization
  90. wirepeersetupfuncs = []
  91. def _peerorrepo(ui, path, create=False):
  92. """return a repository object for the specified path"""
  93. obj = _peerlookup(path).instance(ui, path, create)
  94. ui = getattr(obj, "ui", ui)
  95. for name, module in extensions.extensions(ui):
  96. hook = getattr(module, 'reposetup', None)
  97. if hook:
  98. hook(ui, obj)
  99. if not obj.local():
  100. for f in wirepeersetupfuncs:
  101. f(ui, obj)
  102. return obj
  103. def repository(ui, path='', create=False):
  104. """return a repository object for the specified path"""
  105. peer = _peerorrepo(ui, path, create)
  106. repo = peer.local()
  107. if not repo:
  108. raise util.Abort(_("repository '%s' is not local") %
  109. (path or peer.url()))
  110. return repo.filtered('visible')
  111. def peer(uiorrepo, opts, path, create=False):
  112. '''return a repository peer for the specified path'''
  113. rui = remoteui(uiorrepo, opts)
  114. return _peerorrepo(rui, path, create).peer()
  115. def defaultdest(source):
  116. '''return default destination of clone if none is given
  117. >>> defaultdest('foo')
  118. 'foo'
  119. >>> defaultdest('/foo/bar')
  120. 'bar'
  121. >>> defaultdest('/')
  122. ''
  123. >>> defaultdest('')
  124. ''
  125. >>> defaultdest('http://example.org/')
  126. ''
  127. >>> defaultdest('http://example.org/foo/')
  128. 'foo'
  129. '''
  130. path = util.url(source).path
  131. if not path:
  132. return ''
  133. return os.path.basename(os.path.normpath(path))
  134. def share(ui, source, dest=None, update=True):
  135. '''create a shared repository'''
  136. if not islocal(source):
  137. raise util.Abort(_('can only share local repositories'))
  138. if not dest:
  139. dest = defaultdest(source)
  140. else:
  141. dest = ui.expandpath(dest)
  142. if isinstance(source, str):
  143. origsource = ui.expandpath(source)
  144. source, branches = parseurl(origsource)
  145. srcrepo = repository(ui, source)
  146. rev, checkout = addbranchrevs(srcrepo, srcrepo, branches, None)
  147. else:
  148. srcrepo = source.local()
  149. origsource = source = srcrepo.url()
  150. checkout = None
  151. sharedpath = srcrepo.sharedpath # if our source is already sharing
  152. destwvfs = scmutil.vfs(dest, realpath=True)
  153. destvfs = scmutil.vfs(os.path.join(destwvfs.base, '.hg'), realpath=True)
  154. if destvfs.lexists():
  155. raise util.Abort(_('destination already exists'))
  156. if not destwvfs.isdir():
  157. destwvfs.mkdir()
  158. destvfs.makedir()
  159. requirements = ''
  160. try:
  161. requirements = srcrepo.opener.read('requires')
  162. except IOError, inst:
  163. if inst.errno != errno.ENOENT:
  164. raise
  165. requirements += 'shared\n'
  166. destvfs.write('requires', requirements)
  167. destvfs.write('sharedpath', sharedpath)
  168. r = repository(ui, destwvfs.base)
  169. default = srcrepo.ui.config('paths', 'default')
  170. if default:
  171. fp = r.opener("hgrc", "w", text=True)
  172. fp.write("[paths]\n")
  173. fp.write("default = %s\n" % default)
  174. fp.close()
  175. if update:
  176. r.ui.status(_("updating working directory\n"))
  177. if update is not True:
  178. checkout = update
  179. for test in (checkout, 'default', 'tip'):
  180. if test is None:
  181. continue
  182. try:
  183. uprev = r.lookup(test)
  184. break
  185. except error.RepoLookupError:
  186. continue
  187. _update(r, uprev)
  188. def copystore(ui, srcrepo, destpath):
  189. '''copy files from store of srcrepo in destpath
  190. returns destlock
  191. '''
  192. destlock = None
  193. try:
  194. hardlink = None
  195. num = 0
  196. srcpublishing = srcrepo.ui.configbool('phases', 'publish', True)
  197. srcvfs = scmutil.vfs(srcrepo.sharedpath)
  198. dstvfs = scmutil.vfs(destpath)
  199. for f in srcrepo.store.copylist():
  200. if srcpublishing and f.endswith('phaseroots'):
  201. continue
  202. dstbase = os.path.dirname(f)
  203. if dstbase and not dstvfs.exists(dstbase):
  204. dstvfs.mkdir(dstbase)
  205. if srcvfs.exists(f):
  206. if f.endswith('data'):
  207. # 'dstbase' may be empty (e.g. revlog format 0)
  208. lockfile = os.path.join(dstbase, "lock")
  209. # lock to avoid premature writing to the target
  210. destlock = lock.lock(dstvfs, lockfile)
  211. hardlink, n = util.copyfiles(srcvfs.join(f), dstvfs.join(f),
  212. hardlink)
  213. num += n
  214. if hardlink:
  215. ui.debug("linked %d files\n" % num)
  216. else:
  217. ui.debug("copied %d files\n" % num)
  218. return destlock
  219. except: # re-raises
  220. release(destlock)
  221. raise
  222. def clone(ui, peeropts, source, dest=None, pull=False, rev=None,
  223. update=True, stream=False, branch=None):
  224. """Make a copy of an existing repository.
  225. Create a copy of an existing repository in a new directory. The
  226. source and destination are URLs, as passed to the repository
  227. function. Returns a pair of repository peers, the source and
  228. newly created destination.
  229. The location of the source is added to the new repository's
  230. .hg/hgrc file, as the default to be used for future pulls and
  231. pushes.
  232. If an exception is raised, the partly cloned/updated destination
  233. repository will be deleted.
  234. Arguments:
  235. source: repository object or URL
  236. dest: URL of destination repository to create (defaults to base
  237. name of source repository)
  238. pull: always pull from source repository, even in local case
  239. stream: stream raw data uncompressed from repository (fast over
  240. LAN, slow over WAN)
  241. rev: revision to clone up to (implies pull=True)
  242. update: update working directory after clone completes, if
  243. destination is local repository (True means update to default rev,
  244. anything else is treated as a revision)
  245. branch: branches to clone
  246. """
  247. if isinstance(source, str):
  248. origsource = ui.expandpath(source)
  249. source, branch = parseurl(origsource, branch)
  250. srcpeer = peer(ui, peeropts, source)
  251. else:
  252. srcpeer = source.peer() # in case we were called with a localrepo
  253. branch = (None, branch or [])
  254. origsource = source = srcpeer.url()
  255. rev, checkout = addbranchrevs(srcpeer, srcpeer, branch, rev)
  256. if dest is None:
  257. dest = defaultdest(source)
  258. if dest:
  259. ui.status(_("destination directory: %s\n") % dest)
  260. else:
  261. dest = ui.expandpath(dest)
  262. dest = util.urllocalpath(dest)
  263. source = util.urllocalpath(source)
  264. if not dest:
  265. raise util.Abort(_("empty destination path is not valid"))
  266. destvfs = scmutil.vfs(dest, expandpath=True)
  267. if destvfs.lexists():
  268. if not destvfs.isdir():
  269. raise util.Abort(_("destination '%s' already exists") % dest)
  270. elif destvfs.listdir():
  271. raise util.Abort(_("destination '%s' is not empty") % dest)
  272. srclock = destlock = cleandir = None
  273. srcrepo = srcpeer.local()
  274. try:
  275. abspath = origsource
  276. if islocal(origsource):
  277. abspath = os.path.abspath(util.urllocalpath(origsource))
  278. if islocal(dest):
  279. cleandir = dest
  280. copy = False
  281. if (srcrepo and srcrepo.cancopy() and islocal(dest)
  282. and not phases.hassecret(srcrepo)):
  283. copy = not pull and not rev
  284. if copy:
  285. try:
  286. # we use a lock here because if we race with commit, we
  287. # can end up with extra data in the cloned revlogs that's
  288. # not pointed to by changesets, thus causing verify to
  289. # fail
  290. srclock = srcrepo.lock(wait=False)
  291. except error.LockError:
  292. copy = False
  293. if copy:
  294. srcrepo.hook('preoutgoing', throw=True, source='clone')
  295. hgdir = os.path.realpath(os.path.join(dest, ".hg"))
  296. if not os.path.exists(dest):
  297. os.mkdir(dest)
  298. else:
  299. # only clean up directories we create ourselves
  300. cleandir = hgdir
  301. try:
  302. destpath = hgdir
  303. util.makedir(destpath, notindexed=True)
  304. except OSError, inst:
  305. if inst.errno == errno.EEXIST:
  306. cleandir = None
  307. raise util.Abort(_("destination '%s' already exists")
  308. % dest)
  309. raise
  310. destlock = copystore(ui, srcrepo, destpath)
  311. # Recomputing branch cache might be slow on big repos,
  312. # so just copy it
  313. dstcachedir = os.path.join(destpath, 'cache')
  314. srcbranchcache = srcrepo.sjoin('cache/branch2')
  315. dstbranchcache = os.path.join(dstcachedir, 'branch2')
  316. if os.path.exists(srcbranchcache):
  317. if not os.path.exists(dstcachedir):
  318. os.mkdir(dstcachedir)
  319. util.copyfile(srcbranchcache, dstbranchcache)
  320. # we need to re-init the repo after manually copying the data
  321. # into it
  322. destpeer = peer(srcrepo, peeropts, dest)
  323. srcrepo.hook('outgoing', source='clone',
  324. node=node.hex(node.nullid))
  325. else:
  326. try:
  327. destpeer = peer(srcrepo or ui, peeropts, dest, create=True)
  328. # only pass ui when no srcrepo
  329. except OSError, inst:
  330. if inst.errno == errno.EEXIST:
  331. cleandir = None
  332. raise util.Abort(_("destination '%s' already exists")
  333. % dest)
  334. raise
  335. revs = None
  336. if rev:
  337. if not srcpeer.capable('lookup'):
  338. raise util.Abort(_("src repository does not support "
  339. "revision lookup and so doesn't "
  340. "support clone by revision"))
  341. revs = [srcpeer.lookup(r) for r in rev]
  342. checkout = revs[0]
  343. if destpeer.local():
  344. destpeer.local().clone(srcpeer, heads=revs, stream=stream)
  345. elif srcrepo:
  346. srcrepo.push(destpeer, revs=revs)
  347. else:
  348. raise util.Abort(_("clone from remote to remote not supported"))
  349. cleandir = None
  350. # clone all bookmarks except divergent ones
  351. destrepo = destpeer.local()
  352. if destrepo and srcpeer.capable("pushkey"):
  353. rb = srcpeer.listkeys('bookmarks')
  354. marks = destrepo._bookmarks
  355. for k, n in rb.iteritems():
  356. try:
  357. m = destrepo.lookup(n)
  358. marks[k] = m
  359. except error.RepoLookupError:
  360. pass
  361. if rb:
  362. marks.write()
  363. elif srcrepo and destpeer.capable("pushkey"):
  364. for k, n in srcrepo._bookmarks.iteritems():
  365. destpeer.pushkey('bookmarks', k, '', hex(n))
  366. if destrepo:
  367. fp = destrepo.opener("hgrc", "w", text=True)
  368. fp.write("[paths]\n")
  369. u = util.url(abspath)
  370. u.passwd = None
  371. defaulturl = str(u)
  372. fp.write("default = %s\n" % defaulturl)
  373. fp.close()
  374. destrepo.ui.setconfig('paths', 'default', defaulturl, 'clone')
  375. if update:
  376. if update is not True:
  377. checkout = srcpeer.lookup(update)
  378. uprev = None
  379. status = None
  380. if checkout is not None:
  381. try:
  382. uprev = destrepo.lookup(checkout)
  383. except error.RepoLookupError:
  384. pass
  385. if uprev is None:
  386. try:
  387. uprev = destrepo._bookmarks['@']
  388. update = '@'
  389. bn = destrepo[uprev].branch()
  390. if bn == 'default':
  391. status = _("updating to bookmark @\n")
  392. else:
  393. status = (_("updating to bookmark @ on branch %s\n")
  394. % bn)
  395. except KeyError:
  396. try:
  397. uprev = destrepo.branchtip('default')
  398. except error.RepoLookupError:
  399. uprev = destrepo.lookup('tip')
  400. if not status:
  401. bn = destrepo[uprev].branch()
  402. status = _("updating to branch %s\n") % bn
  403. destrepo.ui.status(status)
  404. _update(destrepo, uprev)
  405. if update in destrepo._bookmarks:
  406. bookmarks.setcurrent(destrepo, update)
  407. finally:
  408. release(srclock, destlock)
  409. if cleandir is not None:
  410. shutil.rmtree(cleandir, True)
  411. if srcpeer is not None:
  412. srcpeer.close()
  413. return srcpeer, destpeer
  414. def _showstats(repo, stats):
  415. repo.ui.status(_("%d files updated, %d files merged, "
  416. "%d files removed, %d files unresolved\n") % stats)
  417. def updaterepo(repo, node, overwrite):
  418. """Update the working directory to node.
  419. When overwrite is set, changes are clobbered, merged else
  420. returns stats (see pydoc mercurial.merge.applyupdates)"""
  421. return mergemod.update(repo, node, False, overwrite, None,
  422. labels=['working copy', 'destination'])
  423. def update(repo, node):
  424. """update the working directory to node, merging linear changes"""
  425. stats = updaterepo(repo, node, False)
  426. _showstats(repo, stats)
  427. if stats[3]:
  428. repo.ui.status(_("use 'hg resolve' to retry unresolved file merges\n"))
  429. return stats[3] > 0
  430. # naming conflict in clone()
  431. _update = update
  432. def clean(repo, node, show_stats=True):
  433. """forcibly switch the working directory to node, clobbering changes"""
  434. stats = updaterepo(repo, node, True)
  435. util.unlinkpath(repo.join('graftstate'), ignoremissing=True)
  436. if show_stats:
  437. _showstats(repo, stats)
  438. return stats[3] > 0
  439. def merge(repo, node, force=None, remind=True):
  440. """Branch merge with node, resolving changes. Return true if any
  441. unresolved conflicts."""
  442. stats = mergemod.update(repo, node, True, force, False)
  443. _showstats(repo, stats)
  444. if stats[3]:
  445. repo.ui.status(_("use 'hg resolve' to retry unresolved file merges "
  446. "or 'hg update -C .' to abandon\n"))
  447. elif remind:
  448. repo.ui.status(_("(branch merge, don't forget to commit)\n"))
  449. return stats[3] > 0
  450. def _incoming(displaychlist, subreporecurse, ui, repo, source,
  451. opts, buffered=False):
  452. """
  453. Helper for incoming / gincoming.
  454. displaychlist gets called with
  455. (remoterepo, incomingchangesetlist, displayer) parameters,
  456. and is supposed to contain only code that can't be unified.
  457. """
  458. source, branches = parseurl(ui.expandpath(source), opts.get('branch'))
  459. other = peer(repo, opts, source)
  460. ui.status(_('comparing with %s\n') % util.hidepassword(source))
  461. revs, checkout = addbranchrevs(repo, other, branches, opts.get('rev'))
  462. if revs:
  463. revs = [other.lookup(rev) for rev in revs]
  464. other, chlist, cleanupfn = bundlerepo.getremotechanges(ui, repo, other,
  465. revs, opts["bundle"], opts["force"])
  466. try:
  467. if not chlist:
  468. ui.status(_("no changes found\n"))
  469. return subreporecurse()
  470. displayer = cmdutil.show_changeset(ui, other, opts, buffered)
  471. displaychlist(other, chlist, displayer)
  472. displayer.close()
  473. finally:
  474. cleanupfn()
  475. subreporecurse()
  476. return 0 # exit code is zero since we found incoming changes
  477. def incoming(ui, repo, source, opts):
  478. def subreporecurse():
  479. ret = 1
  480. if opts.get('subrepos'):
  481. ctx = repo[None]
  482. for subpath in sorted(ctx.substate):
  483. sub = ctx.sub(subpath)
  484. ret = min(ret, sub.incoming(ui, source, opts))
  485. return ret
  486. def display(other, chlist, displayer):
  487. limit = cmdutil.loglimit(opts)
  488. if opts.get('newest_first'):
  489. chlist.reverse()
  490. count = 0
  491. for n in chlist:
  492. if limit is not None and count >= limit:
  493. break
  494. parents = [p for p in other.changelog.parents(n) if p != nullid]
  495. if opts.get('no_merges') and len(parents) == 2:
  496. continue
  497. count += 1
  498. displayer.show(other[n])
  499. return _incoming(display, subreporecurse, ui, repo, source, opts)
  500. def _outgoing(ui, repo, dest, opts):
  501. dest = ui.expandpath(dest or 'default-push', dest or 'default')
  502. dest, branches = parseurl(dest, opts.get('branch'))
  503. ui.status(_('comparing with %s\n') % util.hidepassword(dest))
  504. revs, checkout = addbranchrevs(repo, repo, branches, opts.get('rev'))
  505. if revs:
  506. revs = [repo.lookup(rev) for rev in scmutil.revrange(repo, revs)]
  507. other = peer(repo, opts, dest)
  508. outgoing = discovery.findcommonoutgoing(repo.unfiltered(), other, revs,
  509. force=opts.get('force'))
  510. o = outgoing.missing
  511. if not o:
  512. scmutil.nochangesfound(repo.ui, repo, outgoing.excluded)
  513. return o, other
  514. def outgoing(ui, repo, dest, opts):
  515. def recurse():
  516. ret = 1
  517. if opts.get('subrepos'):
  518. ctx = repo[None]
  519. for subpath in sorted(ctx.substate):
  520. sub = ctx.sub(subpath)
  521. ret = min(ret, sub.outgoing(ui, dest, opts))
  522. return ret
  523. limit = cmdutil.loglimit(opts)
  524. o, other = _outgoing(ui, repo, dest, opts)
  525. if not o:
  526. cmdutil.outgoinghooks(ui, repo, other, opts, o)
  527. return recurse()
  528. if opts.get('newest_first'):
  529. o.reverse()
  530. displayer = cmdutil.show_changeset(ui, repo, opts)
  531. count = 0
  532. for n in o:
  533. if limit is not None and count >= limit:
  534. break
  535. parents = [p for p in repo.changelog.parents(n) if p != nullid]
  536. if opts.get('no_merges') and len(parents) == 2:
  537. continue
  538. count += 1
  539. displayer.show(repo[n])
  540. displayer.close()
  541. cmdutil.outgoinghooks(ui, repo, other, opts, o)
  542. recurse()
  543. return 0 # exit code is zero since we found outgoing changes
  544. def revert(repo, node, choose):
  545. """revert changes to revision in node without updating dirstate"""
  546. return mergemod.update(repo, node, False, True, choose)[3] > 0
  547. def verify(repo):
  548. """verify the consistency of a repository"""
  549. return verifymod.verify(repo)
  550. def remoteui(src, opts):
  551. 'build a remote ui from ui or repo and opts'
  552. if util.safehasattr(src, 'baseui'): # looks like a repository
  553. dst = src.baseui.copy() # drop repo-specific config
  554. src = src.ui # copy target options from repo
  555. else: # assume it's a global ui object
  556. dst = src.copy() # keep all global options
  557. # copy ssh-specific options
  558. for o in 'ssh', 'remotecmd':
  559. v = opts.get(o) or src.config('ui', o)
  560. if v:
  561. dst.setconfig("ui", o, v, 'copied')
  562. # copy bundle-specific options
  563. r = src.config('bundle', 'mainreporoot')
  564. if r:
  565. dst.setconfig('bundle', 'mainreporoot', r, 'copied')
  566. # copy selected local settings to the remote ui
  567. for sect in ('auth', 'hostfingerprints', 'http_proxy'):
  568. for key, val in src.configitems(sect):
  569. dst.setconfig(sect, key, val, 'copied')
  570. v = src.config('web', 'cacerts')
  571. if v:
  572. dst.setconfig('web', 'cacerts', util.expandpath(v), 'copied')
  573. return dst