PageRenderTime 62ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 1ms

/mercurial/subrepo.py

https://bitbucket.org/mirror/mercurial/
Python | 1580 lines | 1434 code | 63 blank | 83 comment | 123 complexity | fd3c75b75b6257d20700ce92bfb8fed8 MD5 | raw file
Possible License(s): GPL-2.0
  1. # subrepo.py - sub-repository handling for Mercurial
  2. #
  3. # Copyright 2009-2010 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 errno, os, re, shutil, posixpath, sys
  8. import xml.dom.minidom
  9. import stat, subprocess, tarfile
  10. from i18n import _
  11. import config, util, node, error, cmdutil, bookmarks, match as matchmod
  12. import phases
  13. import pathutil
  14. hg = None
  15. propertycache = util.propertycache
  16. nullstate = ('', '', 'empty')
  17. def _expandedabspath(path):
  18. '''
  19. get a path or url and if it is a path expand it and return an absolute path
  20. '''
  21. expandedpath = util.urllocalpath(util.expandpath(path))
  22. u = util.url(expandedpath)
  23. if not u.scheme:
  24. path = util.normpath(os.path.abspath(u.path))
  25. return path
  26. def _getstorehashcachename(remotepath):
  27. '''get a unique filename for the store hash cache of a remote repository'''
  28. return util.sha1(_expandedabspath(remotepath)).hexdigest()[0:12]
  29. def _calcfilehash(filename):
  30. data = ''
  31. if os.path.exists(filename):
  32. fd = open(filename, 'rb')
  33. data = fd.read()
  34. fd.close()
  35. return util.sha1(data).hexdigest()
  36. class SubrepoAbort(error.Abort):
  37. """Exception class used to avoid handling a subrepo error more than once"""
  38. def __init__(self, *args, **kw):
  39. error.Abort.__init__(self, *args, **kw)
  40. self.subrepo = kw.get('subrepo')
  41. self.cause = kw.get('cause')
  42. def annotatesubrepoerror(func):
  43. def decoratedmethod(self, *args, **kargs):
  44. try:
  45. res = func(self, *args, **kargs)
  46. except SubrepoAbort, ex:
  47. # This exception has already been handled
  48. raise ex
  49. except error.Abort, ex:
  50. subrepo = subrelpath(self)
  51. errormsg = str(ex) + ' ' + _('(in subrepo %s)') % subrepo
  52. # avoid handling this exception by raising a SubrepoAbort exception
  53. raise SubrepoAbort(errormsg, hint=ex.hint, subrepo=subrepo,
  54. cause=sys.exc_info())
  55. return res
  56. return decoratedmethod
  57. def state(ctx, ui):
  58. """return a state dict, mapping subrepo paths configured in .hgsub
  59. to tuple: (source from .hgsub, revision from .hgsubstate, kind
  60. (key in types dict))
  61. """
  62. p = config.config()
  63. def read(f, sections=None, remap=None):
  64. if f in ctx:
  65. try:
  66. data = ctx[f].data()
  67. except IOError, err:
  68. if err.errno != errno.ENOENT:
  69. raise
  70. # handle missing subrepo spec files as removed
  71. ui.warn(_("warning: subrepo spec file %s not found\n") % f)
  72. return
  73. p.parse(f, data, sections, remap, read)
  74. else:
  75. raise util.Abort(_("subrepo spec file %s not found") % f)
  76. if '.hgsub' in ctx:
  77. read('.hgsub')
  78. for path, src in ui.configitems('subpaths'):
  79. p.set('subpaths', path, src, ui.configsource('subpaths', path))
  80. rev = {}
  81. if '.hgsubstate' in ctx:
  82. try:
  83. for i, l in enumerate(ctx['.hgsubstate'].data().splitlines()):
  84. l = l.lstrip()
  85. if not l:
  86. continue
  87. try:
  88. revision, path = l.split(" ", 1)
  89. except ValueError:
  90. raise util.Abort(_("invalid subrepository revision "
  91. "specifier in .hgsubstate line %d")
  92. % (i + 1))
  93. rev[path] = revision
  94. except IOError, err:
  95. if err.errno != errno.ENOENT:
  96. raise
  97. def remap(src):
  98. for pattern, repl in p.items('subpaths'):
  99. # Turn r'C:\foo\bar' into r'C:\\foo\\bar' since re.sub
  100. # does a string decode.
  101. repl = repl.encode('string-escape')
  102. # However, we still want to allow back references to go
  103. # through unharmed, so we turn r'\\1' into r'\1'. Again,
  104. # extra escapes are needed because re.sub string decodes.
  105. repl = re.sub(r'\\\\([0-9]+)', r'\\\1', repl)
  106. try:
  107. src = re.sub(pattern, repl, src, 1)
  108. except re.error, e:
  109. raise util.Abort(_("bad subrepository pattern in %s: %s")
  110. % (p.source('subpaths', pattern), e))
  111. return src
  112. state = {}
  113. for path, src in p[''].items():
  114. kind = 'hg'
  115. if src.startswith('['):
  116. if ']' not in src:
  117. raise util.Abort(_('missing ] in subrepo source'))
  118. kind, src = src.split(']', 1)
  119. kind = kind[1:]
  120. src = src.lstrip() # strip any extra whitespace after ']'
  121. if not util.url(src).isabs():
  122. parent = _abssource(ctx._repo, abort=False)
  123. if parent:
  124. parent = util.url(parent)
  125. parent.path = posixpath.join(parent.path or '', src)
  126. parent.path = posixpath.normpath(parent.path)
  127. joined = str(parent)
  128. # Remap the full joined path and use it if it changes,
  129. # else remap the original source.
  130. remapped = remap(joined)
  131. if remapped == joined:
  132. src = remap(src)
  133. else:
  134. src = remapped
  135. src = remap(src)
  136. state[util.pconvert(path)] = (src.strip(), rev.get(path, ''), kind)
  137. return state
  138. def writestate(repo, state):
  139. """rewrite .hgsubstate in (outer) repo with these subrepo states"""
  140. lines = ['%s %s\n' % (state[s][1], s) for s in sorted(state)]
  141. repo.wwrite('.hgsubstate', ''.join(lines), '')
  142. def submerge(repo, wctx, mctx, actx, overwrite):
  143. """delegated from merge.applyupdates: merging of .hgsubstate file
  144. in working context, merging context and ancestor context"""
  145. if mctx == actx: # backwards?
  146. actx = wctx.p1()
  147. s1 = wctx.substate
  148. s2 = mctx.substate
  149. sa = actx.substate
  150. sm = {}
  151. repo.ui.debug("subrepo merge %s %s %s\n" % (wctx, mctx, actx))
  152. def debug(s, msg, r=""):
  153. if r:
  154. r = "%s:%s:%s" % r
  155. repo.ui.debug(" subrepo %s: %s %s\n" % (s, msg, r))
  156. for s, l in sorted(s1.iteritems()):
  157. a = sa.get(s, nullstate)
  158. ld = l # local state with possible dirty flag for compares
  159. if wctx.sub(s).dirty():
  160. ld = (l[0], l[1] + "+")
  161. if wctx == actx: # overwrite
  162. a = ld
  163. if s in s2:
  164. r = s2[s]
  165. if ld == r or r == a: # no change or local is newer
  166. sm[s] = l
  167. continue
  168. elif ld == a: # other side changed
  169. debug(s, "other changed, get", r)
  170. wctx.sub(s).get(r, overwrite)
  171. sm[s] = r
  172. elif ld[0] != r[0]: # sources differ
  173. if repo.ui.promptchoice(
  174. _(' subrepository sources for %s differ\n'
  175. 'use (l)ocal source (%s) or (r)emote source (%s)?'
  176. '$$ &Local $$ &Remote') % (s, l[0], r[0]), 0):
  177. debug(s, "prompt changed, get", r)
  178. wctx.sub(s).get(r, overwrite)
  179. sm[s] = r
  180. elif ld[1] == a[1]: # local side is unchanged
  181. debug(s, "other side changed, get", r)
  182. wctx.sub(s).get(r, overwrite)
  183. sm[s] = r
  184. else:
  185. debug(s, "both sides changed")
  186. srepo = wctx.sub(s)
  187. option = repo.ui.promptchoice(
  188. _(' subrepository %s diverged (local revision: %s, '
  189. 'remote revision: %s)\n'
  190. '(M)erge, keep (l)ocal or keep (r)emote?'
  191. '$$ &Merge $$ &Local $$ &Remote')
  192. % (s, srepo.shortid(l[1]), srepo.shortid(r[1])), 0)
  193. if option == 0:
  194. wctx.sub(s).merge(r)
  195. sm[s] = l
  196. debug(s, "merge with", r)
  197. elif option == 1:
  198. sm[s] = l
  199. debug(s, "keep local subrepo revision", l)
  200. else:
  201. wctx.sub(s).get(r, overwrite)
  202. sm[s] = r
  203. debug(s, "get remote subrepo revision", r)
  204. elif ld == a: # remote removed, local unchanged
  205. debug(s, "remote removed, remove")
  206. wctx.sub(s).remove()
  207. elif a == nullstate: # not present in remote or ancestor
  208. debug(s, "local added, keep")
  209. sm[s] = l
  210. continue
  211. else:
  212. if repo.ui.promptchoice(
  213. _(' local changed subrepository %s which remote removed\n'
  214. 'use (c)hanged version or (d)elete?'
  215. '$$ &Changed $$ &Delete') % s, 0):
  216. debug(s, "prompt remove")
  217. wctx.sub(s).remove()
  218. for s, r in sorted(s2.items()):
  219. if s in s1:
  220. continue
  221. elif s not in sa:
  222. debug(s, "remote added, get", r)
  223. mctx.sub(s).get(r)
  224. sm[s] = r
  225. elif r != sa[s]:
  226. if repo.ui.promptchoice(
  227. _(' remote changed subrepository %s which local removed\n'
  228. 'use (c)hanged version or (d)elete?'
  229. '$$ &Changed $$ &Delete') % s, 0) == 0:
  230. debug(s, "prompt recreate", r)
  231. wctx.sub(s).get(r)
  232. sm[s] = r
  233. # record merged .hgsubstate
  234. writestate(repo, sm)
  235. return sm
  236. def _updateprompt(ui, sub, dirty, local, remote):
  237. if dirty:
  238. msg = (_(' subrepository sources for %s differ\n'
  239. 'use (l)ocal source (%s) or (r)emote source (%s)?\n'
  240. '$$ &Local $$ &Remote')
  241. % (subrelpath(sub), local, remote))
  242. else:
  243. msg = (_(' subrepository sources for %s differ (in checked out '
  244. 'version)\n'
  245. 'use (l)ocal source (%s) or (r)emote source (%s)?\n'
  246. '$$ &Local $$ &Remote')
  247. % (subrelpath(sub), local, remote))
  248. return ui.promptchoice(msg, 0)
  249. def reporelpath(repo):
  250. """return path to this (sub)repo as seen from outermost repo"""
  251. parent = repo
  252. while util.safehasattr(parent, '_subparent'):
  253. parent = parent._subparent
  254. return repo.root[len(pathutil.normasprefix(parent.root)):]
  255. def subrelpath(sub):
  256. """return path to this subrepo as seen from outermost repo"""
  257. if util.safehasattr(sub, '_relpath'):
  258. return sub._relpath
  259. if not util.safehasattr(sub, '_repo'):
  260. return sub._path
  261. return reporelpath(sub._repo)
  262. def _abssource(repo, push=False, abort=True):
  263. """return pull/push path of repo - either based on parent repo .hgsub info
  264. or on the top repo config. Abort or return None if no source found."""
  265. if util.safehasattr(repo, '_subparent'):
  266. source = util.url(repo._subsource)
  267. if source.isabs():
  268. return str(source)
  269. source.path = posixpath.normpath(source.path)
  270. parent = _abssource(repo._subparent, push, abort=False)
  271. if parent:
  272. parent = util.url(util.pconvert(parent))
  273. parent.path = posixpath.join(parent.path or '', source.path)
  274. parent.path = posixpath.normpath(parent.path)
  275. return str(parent)
  276. else: # recursion reached top repo
  277. if util.safehasattr(repo, '_subtoppath'):
  278. return repo._subtoppath
  279. if push and repo.ui.config('paths', 'default-push'):
  280. return repo.ui.config('paths', 'default-push')
  281. if repo.ui.config('paths', 'default'):
  282. return repo.ui.config('paths', 'default')
  283. if repo.sharedpath != repo.path:
  284. # chop off the .hg component to get the default path form
  285. return os.path.dirname(repo.sharedpath)
  286. if abort:
  287. raise util.Abort(_("default path for subrepository not found"))
  288. def _sanitize(ui, path, ignore):
  289. for dirname, dirs, names in os.walk(path):
  290. for i, d in enumerate(dirs):
  291. if d.lower() == ignore:
  292. del dirs[i]
  293. break
  294. if os.path.basename(dirname).lower() != '.hg':
  295. continue
  296. for f in names:
  297. if f.lower() == 'hgrc':
  298. ui.warn(_("warning: removing potentially hostile 'hgrc' "
  299. "in '%s'\n") % dirname)
  300. os.unlink(os.path.join(dirname, f))
  301. def subrepo(ctx, path):
  302. """return instance of the right subrepo class for subrepo in path"""
  303. # subrepo inherently violates our import layering rules
  304. # because it wants to make repo objects from deep inside the stack
  305. # so we manually delay the circular imports to not break
  306. # scripts that don't use our demand-loading
  307. global hg
  308. import hg as h
  309. hg = h
  310. pathutil.pathauditor(ctx._repo.root)(path)
  311. state = ctx.substate[path]
  312. if state[2] not in types:
  313. raise util.Abort(_('unknown subrepo type %s') % state[2])
  314. return types[state[2]](ctx, path, state[:2])
  315. def newcommitphase(ui, ctx):
  316. commitphase = phases.newcommitphase(ui)
  317. substate = getattr(ctx, "substate", None)
  318. if not substate:
  319. return commitphase
  320. check = ui.config('phases', 'checksubrepos', 'follow')
  321. if check not in ('ignore', 'follow', 'abort'):
  322. raise util.Abort(_('invalid phases.checksubrepos configuration: %s')
  323. % (check))
  324. if check == 'ignore':
  325. return commitphase
  326. maxphase = phases.public
  327. maxsub = None
  328. for s in sorted(substate):
  329. sub = ctx.sub(s)
  330. subphase = sub.phase(substate[s][1])
  331. if maxphase < subphase:
  332. maxphase = subphase
  333. maxsub = s
  334. if commitphase < maxphase:
  335. if check == 'abort':
  336. raise util.Abort(_("can't commit in %s phase"
  337. " conflicting %s from subrepository %s") %
  338. (phases.phasenames[commitphase],
  339. phases.phasenames[maxphase], maxsub))
  340. ui.warn(_("warning: changes are committed in"
  341. " %s phase from subrepository %s\n") %
  342. (phases.phasenames[maxphase], maxsub))
  343. return maxphase
  344. return commitphase
  345. # subrepo classes need to implement the following abstract class:
  346. class abstractsubrepo(object):
  347. def storeclean(self, path):
  348. """
  349. returns true if the repository has not changed since it was last
  350. cloned from or pushed to a given repository.
  351. """
  352. return False
  353. def dirty(self, ignoreupdate=False):
  354. """returns true if the dirstate of the subrepo is dirty or does not
  355. match current stored state. If ignoreupdate is true, only check
  356. whether the subrepo has uncommitted changes in its dirstate.
  357. """
  358. raise NotImplementedError
  359. def basestate(self):
  360. """current working directory base state, disregarding .hgsubstate
  361. state and working directory modifications"""
  362. raise NotImplementedError
  363. def checknested(self, path):
  364. """check if path is a subrepository within this repository"""
  365. return False
  366. def commit(self, text, user, date):
  367. """commit the current changes to the subrepo with the given
  368. log message. Use given user and date if possible. Return the
  369. new state of the subrepo.
  370. """
  371. raise NotImplementedError
  372. def phase(self, state):
  373. """returns phase of specified state in the subrepository.
  374. """
  375. return phases.public
  376. def remove(self):
  377. """remove the subrepo
  378. (should verify the dirstate is not dirty first)
  379. """
  380. raise NotImplementedError
  381. def get(self, state, overwrite=False):
  382. """run whatever commands are needed to put the subrepo into
  383. this state
  384. """
  385. raise NotImplementedError
  386. def merge(self, state):
  387. """merge currently-saved state with the new state."""
  388. raise NotImplementedError
  389. def push(self, opts):
  390. """perform whatever action is analogous to 'hg push'
  391. This may be a no-op on some systems.
  392. """
  393. raise NotImplementedError
  394. def add(self, ui, match, dryrun, listsubrepos, prefix, explicitonly):
  395. return []
  396. def cat(self, ui, match, prefix, **opts):
  397. return 1
  398. def status(self, rev2, **opts):
  399. return [], [], [], [], [], [], []
  400. def diff(self, ui, diffopts, node2, match, prefix, **opts):
  401. pass
  402. def outgoing(self, ui, dest, opts):
  403. return 1
  404. def incoming(self, ui, source, opts):
  405. return 1
  406. def files(self):
  407. """return filename iterator"""
  408. raise NotImplementedError
  409. def filedata(self, name):
  410. """return file data"""
  411. raise NotImplementedError
  412. def fileflags(self, name):
  413. """return file flags"""
  414. return ''
  415. def archive(self, ui, archiver, prefix, match=None):
  416. if match is not None:
  417. files = [f for f in self.files() if match(f)]
  418. else:
  419. files = self.files()
  420. total = len(files)
  421. relpath = subrelpath(self)
  422. ui.progress(_('archiving (%s)') % relpath, 0,
  423. unit=_('files'), total=total)
  424. for i, name in enumerate(files):
  425. flags = self.fileflags(name)
  426. mode = 'x' in flags and 0755 or 0644
  427. symlink = 'l' in flags
  428. archiver.addfile(os.path.join(prefix, self._path, name),
  429. mode, symlink, self.filedata(name))
  430. ui.progress(_('archiving (%s)') % relpath, i + 1,
  431. unit=_('files'), total=total)
  432. ui.progress(_('archiving (%s)') % relpath, None)
  433. return total
  434. def walk(self, match):
  435. '''
  436. walk recursively through the directory tree, finding all files
  437. matched by the match function
  438. '''
  439. pass
  440. def forget(self, ui, match, prefix):
  441. return ([], [])
  442. def revert(self, ui, substate, *pats, **opts):
  443. ui.warn('%s: reverting %s subrepos is unsupported\n' \
  444. % (substate[0], substate[2]))
  445. return []
  446. def shortid(self, revid):
  447. return revid
  448. class hgsubrepo(abstractsubrepo):
  449. def __init__(self, ctx, path, state):
  450. self._path = path
  451. self._state = state
  452. r = ctx._repo
  453. root = r.wjoin(path)
  454. create = False
  455. if not os.path.exists(os.path.join(root, '.hg')):
  456. create = True
  457. util.makedirs(root)
  458. self._repo = hg.repository(r.baseui, root, create=create)
  459. for s, k in [('ui', 'commitsubrepos')]:
  460. v = r.ui.config(s, k)
  461. if v:
  462. self._repo.ui.setconfig(s, k, v, 'subrepo')
  463. self._repo.ui.setconfig('ui', '_usedassubrepo', 'True', 'subrepo')
  464. self._initrepo(r, state[0], create)
  465. def storeclean(self, path):
  466. clean = True
  467. lock = self._repo.lock()
  468. itercache = self._calcstorehash(path)
  469. try:
  470. for filehash in self._readstorehashcache(path):
  471. if filehash != itercache.next():
  472. clean = False
  473. break
  474. except StopIteration:
  475. # the cached and current pull states have a different size
  476. clean = False
  477. if clean:
  478. try:
  479. itercache.next()
  480. # the cached and current pull states have a different size
  481. clean = False
  482. except StopIteration:
  483. pass
  484. lock.release()
  485. return clean
  486. def _calcstorehash(self, remotepath):
  487. '''calculate a unique "store hash"
  488. This method is used to to detect when there are changes that may
  489. require a push to a given remote path.'''
  490. # sort the files that will be hashed in increasing (likely) file size
  491. filelist = ('bookmarks', 'store/phaseroots', 'store/00changelog.i')
  492. yield '# %s\n' % _expandedabspath(remotepath)
  493. for relname in filelist:
  494. absname = os.path.normpath(self._repo.join(relname))
  495. yield '%s = %s\n' % (relname, _calcfilehash(absname))
  496. def _getstorehashcachepath(self, remotepath):
  497. '''get a unique path for the store hash cache'''
  498. return self._repo.join(os.path.join(
  499. 'cache', 'storehash', _getstorehashcachename(remotepath)))
  500. def _readstorehashcache(self, remotepath):
  501. '''read the store hash cache for a given remote repository'''
  502. cachefile = self._getstorehashcachepath(remotepath)
  503. if not os.path.exists(cachefile):
  504. return ''
  505. fd = open(cachefile, 'r')
  506. pullstate = fd.readlines()
  507. fd.close()
  508. return pullstate
  509. def _cachestorehash(self, remotepath):
  510. '''cache the current store hash
  511. Each remote repo requires its own store hash cache, because a subrepo
  512. store may be "clean" versus a given remote repo, but not versus another
  513. '''
  514. cachefile = self._getstorehashcachepath(remotepath)
  515. lock = self._repo.lock()
  516. storehash = list(self._calcstorehash(remotepath))
  517. cachedir = os.path.dirname(cachefile)
  518. if not os.path.exists(cachedir):
  519. util.makedirs(cachedir, notindexed=True)
  520. fd = open(cachefile, 'w')
  521. fd.writelines(storehash)
  522. fd.close()
  523. lock.release()
  524. @annotatesubrepoerror
  525. def _initrepo(self, parentrepo, source, create):
  526. self._repo._subparent = parentrepo
  527. self._repo._subsource = source
  528. if create:
  529. fp = self._repo.opener("hgrc", "w", text=True)
  530. fp.write('[paths]\n')
  531. def addpathconfig(key, value):
  532. if value:
  533. fp.write('%s = %s\n' % (key, value))
  534. self._repo.ui.setconfig('paths', key, value, 'subrepo')
  535. defpath = _abssource(self._repo, abort=False)
  536. defpushpath = _abssource(self._repo, True, abort=False)
  537. addpathconfig('default', defpath)
  538. if defpath != defpushpath:
  539. addpathconfig('default-push', defpushpath)
  540. fp.close()
  541. @annotatesubrepoerror
  542. def add(self, ui, match, dryrun, listsubrepos, prefix, explicitonly):
  543. return cmdutil.add(ui, self._repo, match, dryrun, listsubrepos,
  544. os.path.join(prefix, self._path), explicitonly)
  545. @annotatesubrepoerror
  546. def cat(self, ui, match, prefix, **opts):
  547. rev = self._state[1]
  548. ctx = self._repo[rev]
  549. return cmdutil.cat(ui, self._repo, ctx, match, prefix, **opts)
  550. @annotatesubrepoerror
  551. def status(self, rev2, **opts):
  552. try:
  553. rev1 = self._state[1]
  554. ctx1 = self._repo[rev1]
  555. ctx2 = self._repo[rev2]
  556. return self._repo.status(ctx1, ctx2, **opts)
  557. except error.RepoLookupError, inst:
  558. self._repo.ui.warn(_('warning: error "%s" in subrepository "%s"\n')
  559. % (inst, subrelpath(self)))
  560. return [], [], [], [], [], [], []
  561. @annotatesubrepoerror
  562. def diff(self, ui, diffopts, node2, match, prefix, **opts):
  563. try:
  564. node1 = node.bin(self._state[1])
  565. # We currently expect node2 to come from substate and be
  566. # in hex format
  567. if node2 is not None:
  568. node2 = node.bin(node2)
  569. cmdutil.diffordiffstat(ui, self._repo, diffopts,
  570. node1, node2, match,
  571. prefix=posixpath.join(prefix, self._path),
  572. listsubrepos=True, **opts)
  573. except error.RepoLookupError, inst:
  574. self._repo.ui.warn(_('warning: error "%s" in subrepository "%s"\n')
  575. % (inst, subrelpath(self)))
  576. @annotatesubrepoerror
  577. def archive(self, ui, archiver, prefix, match=None):
  578. self._get(self._state + ('hg',))
  579. total = abstractsubrepo.archive(self, ui, archiver, prefix, match)
  580. rev = self._state[1]
  581. ctx = self._repo[rev]
  582. for subpath in ctx.substate:
  583. s = subrepo(ctx, subpath)
  584. submatch = matchmod.narrowmatcher(subpath, match)
  585. total += s.archive(
  586. ui, archiver, os.path.join(prefix, self._path), submatch)
  587. return total
  588. @annotatesubrepoerror
  589. def dirty(self, ignoreupdate=False):
  590. r = self._state[1]
  591. if r == '' and not ignoreupdate: # no state recorded
  592. return True
  593. w = self._repo[None]
  594. if r != w.p1().hex() and not ignoreupdate:
  595. # different version checked out
  596. return True
  597. return w.dirty() # working directory changed
  598. def basestate(self):
  599. return self._repo['.'].hex()
  600. def checknested(self, path):
  601. return self._repo._checknested(self._repo.wjoin(path))
  602. @annotatesubrepoerror
  603. def commit(self, text, user, date):
  604. # don't bother committing in the subrepo if it's only been
  605. # updated
  606. if not self.dirty(True):
  607. return self._repo['.'].hex()
  608. self._repo.ui.debug("committing subrepo %s\n" % subrelpath(self))
  609. n = self._repo.commit(text, user, date)
  610. if not n:
  611. return self._repo['.'].hex() # different version checked out
  612. return node.hex(n)
  613. @annotatesubrepoerror
  614. def phase(self, state):
  615. return self._repo[state].phase()
  616. @annotatesubrepoerror
  617. def remove(self):
  618. # we can't fully delete the repository as it may contain
  619. # local-only history
  620. self._repo.ui.note(_('removing subrepo %s\n') % subrelpath(self))
  621. hg.clean(self._repo, node.nullid, False)
  622. def _get(self, state):
  623. source, revision, kind = state
  624. if revision in self._repo.unfiltered():
  625. return True
  626. self._repo._subsource = source
  627. srcurl = _abssource(self._repo)
  628. other = hg.peer(self._repo, {}, srcurl)
  629. if len(self._repo) == 0:
  630. self._repo.ui.status(_('cloning subrepo %s from %s\n')
  631. % (subrelpath(self), srcurl))
  632. parentrepo = self._repo._subparent
  633. shutil.rmtree(self._repo.path)
  634. other, cloned = hg.clone(self._repo._subparent.baseui, {},
  635. other, self._repo.root,
  636. update=False)
  637. self._repo = cloned.local()
  638. self._initrepo(parentrepo, source, create=True)
  639. self._cachestorehash(srcurl)
  640. else:
  641. self._repo.ui.status(_('pulling subrepo %s from %s\n')
  642. % (subrelpath(self), srcurl))
  643. cleansub = self.storeclean(srcurl)
  644. remotebookmarks = other.listkeys('bookmarks')
  645. self._repo.pull(other)
  646. bookmarks.updatefromremote(self._repo.ui, self._repo,
  647. remotebookmarks, srcurl)
  648. if cleansub:
  649. # keep the repo clean after pull
  650. self._cachestorehash(srcurl)
  651. return False
  652. @annotatesubrepoerror
  653. def get(self, state, overwrite=False):
  654. inrepo = self._get(state)
  655. source, revision, kind = state
  656. repo = self._repo
  657. repo.ui.debug("getting subrepo %s\n" % self._path)
  658. if inrepo:
  659. urepo = repo.unfiltered()
  660. ctx = urepo[revision]
  661. if ctx.hidden():
  662. urepo.ui.warn(
  663. _('revision %s in subrepo %s is hidden\n') \
  664. % (revision[0:12], self._path))
  665. repo = urepo
  666. hg.updaterepo(repo, revision, overwrite)
  667. @annotatesubrepoerror
  668. def merge(self, state):
  669. self._get(state)
  670. cur = self._repo['.']
  671. dst = self._repo[state[1]]
  672. anc = dst.ancestor(cur)
  673. def mergefunc():
  674. if anc == cur and dst.branch() == cur.branch():
  675. self._repo.ui.debug("updating subrepo %s\n" % subrelpath(self))
  676. hg.update(self._repo, state[1])
  677. elif anc == dst:
  678. self._repo.ui.debug("skipping subrepo %s\n" % subrelpath(self))
  679. else:
  680. self._repo.ui.debug("merging subrepo %s\n" % subrelpath(self))
  681. hg.merge(self._repo, state[1], remind=False)
  682. wctx = self._repo[None]
  683. if self.dirty():
  684. if anc != dst:
  685. if _updateprompt(self._repo.ui, self, wctx.dirty(), cur, dst):
  686. mergefunc()
  687. else:
  688. mergefunc()
  689. else:
  690. mergefunc()
  691. @annotatesubrepoerror
  692. def push(self, opts):
  693. force = opts.get('force')
  694. newbranch = opts.get('new_branch')
  695. ssh = opts.get('ssh')
  696. # push subrepos depth-first for coherent ordering
  697. c = self._repo['']
  698. subs = c.substate # only repos that are committed
  699. for s in sorted(subs):
  700. if c.sub(s).push(opts) == 0:
  701. return False
  702. dsturl = _abssource(self._repo, True)
  703. if not force:
  704. if self.storeclean(dsturl):
  705. self._repo.ui.status(
  706. _('no changes made to subrepo %s since last push to %s\n')
  707. % (subrelpath(self), dsturl))
  708. return None
  709. self._repo.ui.status(_('pushing subrepo %s to %s\n') %
  710. (subrelpath(self), dsturl))
  711. other = hg.peer(self._repo, {'ssh': ssh}, dsturl)
  712. res = self._repo.push(other, force, newbranch=newbranch)
  713. # the repo is now clean
  714. self._cachestorehash(dsturl)
  715. return res
  716. @annotatesubrepoerror
  717. def outgoing(self, ui, dest, opts):
  718. return hg.outgoing(ui, self._repo, _abssource(self._repo, True), opts)
  719. @annotatesubrepoerror
  720. def incoming(self, ui, source, opts):
  721. return hg.incoming(ui, self._repo, _abssource(self._repo, False), opts)
  722. @annotatesubrepoerror
  723. def files(self):
  724. rev = self._state[1]
  725. ctx = self._repo[rev]
  726. return ctx.manifest()
  727. def filedata(self, name):
  728. rev = self._state[1]
  729. return self._repo[rev][name].data()
  730. def fileflags(self, name):
  731. rev = self._state[1]
  732. ctx = self._repo[rev]
  733. return ctx.flags(name)
  734. def walk(self, match):
  735. ctx = self._repo[None]
  736. return ctx.walk(match)
  737. @annotatesubrepoerror
  738. def forget(self, ui, match, prefix):
  739. return cmdutil.forget(ui, self._repo, match,
  740. os.path.join(prefix, self._path), True)
  741. @annotatesubrepoerror
  742. def revert(self, ui, substate, *pats, **opts):
  743. # reverting a subrepo is a 2 step process:
  744. # 1. if the no_backup is not set, revert all modified
  745. # files inside the subrepo
  746. # 2. update the subrepo to the revision specified in
  747. # the corresponding substate dictionary
  748. ui.status(_('reverting subrepo %s\n') % substate[0])
  749. if not opts.get('no_backup'):
  750. # Revert all files on the subrepo, creating backups
  751. # Note that this will not recursively revert subrepos
  752. # We could do it if there was a set:subrepos() predicate
  753. opts = opts.copy()
  754. opts['date'] = None
  755. opts['rev'] = substate[1]
  756. pats = []
  757. if not opts.get('all'):
  758. pats = ['set:modified()']
  759. self.filerevert(ui, *pats, **opts)
  760. # Update the repo to the revision specified in the given substate
  761. self.get(substate, overwrite=True)
  762. def filerevert(self, ui, *pats, **opts):
  763. ctx = self._repo[opts['rev']]
  764. parents = self._repo.dirstate.parents()
  765. if opts.get('all'):
  766. pats = ['set:modified()']
  767. else:
  768. pats = []
  769. cmdutil.revert(ui, self._repo, ctx, parents, *pats, **opts)
  770. def shortid(self, revid):
  771. return revid[:12]
  772. class svnsubrepo(abstractsubrepo):
  773. def __init__(self, ctx, path, state):
  774. self._path = path
  775. self._state = state
  776. self._ctx = ctx
  777. self._ui = ctx._repo.ui
  778. self._exe = util.findexe('svn')
  779. if not self._exe:
  780. raise util.Abort(_("'svn' executable not found for subrepo '%s'")
  781. % self._path)
  782. def _svncommand(self, commands, filename='', failok=False):
  783. cmd = [self._exe]
  784. extrakw = {}
  785. if not self._ui.interactive():
  786. # Making stdin be a pipe should prevent svn from behaving
  787. # interactively even if we can't pass --non-interactive.
  788. extrakw['stdin'] = subprocess.PIPE
  789. # Starting in svn 1.5 --non-interactive is a global flag
  790. # instead of being per-command, but we need to support 1.4 so
  791. # we have to be intelligent about what commands take
  792. # --non-interactive.
  793. if commands[0] in ('update', 'checkout', 'commit'):
  794. cmd.append('--non-interactive')
  795. cmd.extend(commands)
  796. if filename is not None:
  797. path = os.path.join(self._ctx._repo.origroot, self._path, filename)
  798. cmd.append(path)
  799. env = dict(os.environ)
  800. # Avoid localized output, preserve current locale for everything else.
  801. lc_all = env.get('LC_ALL')
  802. if lc_all:
  803. env['LANG'] = lc_all
  804. del env['LC_ALL']
  805. env['LC_MESSAGES'] = 'C'
  806. p = subprocess.Popen(cmd, bufsize=-1, close_fds=util.closefds,
  807. stdout=subprocess.PIPE, stderr=subprocess.PIPE,
  808. universal_newlines=True, env=env, **extrakw)
  809. stdout, stderr = p.communicate()
  810. stderr = stderr.strip()
  811. if not failok:
  812. if p.returncode:
  813. raise util.Abort(stderr or 'exited with code %d' % p.returncode)
  814. if stderr:
  815. self._ui.warn(stderr + '\n')
  816. return stdout, stderr
  817. @propertycache
  818. def _svnversion(self):
  819. output, err = self._svncommand(['--version', '--quiet'], filename=None)
  820. m = re.search(r'^(\d+)\.(\d+)', output)
  821. if not m:
  822. raise util.Abort(_('cannot retrieve svn tool version'))
  823. return (int(m.group(1)), int(m.group(2)))
  824. def _wcrevs(self):
  825. # Get the working directory revision as well as the last
  826. # commit revision so we can compare the subrepo state with
  827. # both. We used to store the working directory one.
  828. output, err = self._svncommand(['info', '--xml'])
  829. doc = xml.dom.minidom.parseString(output)
  830. entries = doc.getElementsByTagName('entry')
  831. lastrev, rev = '0', '0'
  832. if entries:
  833. rev = str(entries[0].getAttribute('revision')) or '0'
  834. commits = entries[0].getElementsByTagName('commit')
  835. if commits:
  836. lastrev = str(commits[0].getAttribute('revision')) or '0'
  837. return (lastrev, rev)
  838. def _wcrev(self):
  839. return self._wcrevs()[0]
  840. def _wcchanged(self):
  841. """Return (changes, extchanges, missing) where changes is True
  842. if the working directory was changed, extchanges is
  843. True if any of these changes concern an external entry and missing
  844. is True if any change is a missing entry.
  845. """
  846. output, err = self._svncommand(['status', '--xml'])
  847. externals, changes, missing = [], [], []
  848. doc = xml.dom.minidom.parseString(output)
  849. for e in doc.getElementsByTagName('entry'):
  850. s = e.getElementsByTagName('wc-status')
  851. if not s:
  852. continue
  853. item = s[0].getAttribute('item')
  854. props = s[0].getAttribute('props')
  855. path = e.getAttribute('path')
  856. if item == 'external':
  857. externals.append(path)
  858. elif item == 'missing':
  859. missing.append(path)
  860. if (item not in ('', 'normal', 'unversioned', 'external')
  861. or props not in ('', 'none', 'normal')):
  862. changes.append(path)
  863. for path in changes:
  864. for ext in externals:
  865. if path == ext or path.startswith(ext + os.sep):
  866. return True, True, bool(missing)
  867. return bool(changes), False, bool(missing)
  868. def dirty(self, ignoreupdate=False):
  869. if not self._wcchanged()[0]:
  870. if self._state[1] in self._wcrevs() or ignoreupdate:
  871. return False
  872. return True
  873. def basestate(self):
  874. lastrev, rev = self._wcrevs()
  875. if lastrev != rev:
  876. # Last committed rev is not the same than rev. We would
  877. # like to take lastrev but we do not know if the subrepo
  878. # URL exists at lastrev. Test it and fallback to rev it
  879. # is not there.
  880. try:
  881. self._svncommand(['list', '%s@%s' % (self._state[0], lastrev)])
  882. return lastrev
  883. except error.Abort:
  884. pass
  885. return rev
  886. @annotatesubrepoerror
  887. def commit(self, text, user, date):
  888. # user and date are out of our hands since svn is centralized
  889. changed, extchanged, missing = self._wcchanged()
  890. if not changed:
  891. return self.basestate()
  892. if extchanged:
  893. # Do not try to commit externals
  894. raise util.Abort(_('cannot commit svn externals'))
  895. if missing:
  896. # svn can commit with missing entries but aborting like hg
  897. # seems a better approach.
  898. raise util.Abort(_('cannot commit missing svn entries'))
  899. commitinfo, err = self._svncommand(['commit', '-m', text])
  900. self._ui.status(commitinfo)
  901. newrev = re.search('Committed revision ([0-9]+).', commitinfo)
  902. if not newrev:
  903. if not commitinfo.strip():
  904. # Sometimes, our definition of "changed" differs from
  905. # svn one. For instance, svn ignores missing files
  906. # when committing. If there are only missing files, no
  907. # commit is made, no output and no error code.
  908. raise util.Abort(_('failed to commit svn changes'))
  909. raise util.Abort(commitinfo.splitlines()[-1])
  910. newrev = newrev.groups()[0]
  911. self._ui.status(self._svncommand(['update', '-r', newrev])[0])
  912. return newrev
  913. @annotatesubrepoerror
  914. def remove(self):
  915. if self.dirty():
  916. self._ui.warn(_('not removing repo %s because '
  917. 'it has changes.\n') % self._path)
  918. return
  919. self._ui.note(_('removing subrepo %s\n') % self._path)
  920. def onerror(function, path, excinfo):
  921. if function is not os.remove:
  922. raise
  923. # read-only files cannot be unlinked under Windows
  924. s = os.stat(path)
  925. if (s.st_mode & stat.S_IWRITE) != 0:
  926. raise
  927. os.chmod(path, stat.S_IMODE(s.st_mode) | stat.S_IWRITE)
  928. os.remove(path)
  929. path = self._ctx._repo.wjoin(self._path)
  930. shutil.rmtree(path, onerror=onerror)
  931. try:
  932. os.removedirs(os.path.dirname(path))
  933. except OSError:
  934. pass
  935. @annotatesubrepoerror
  936. def get(self, state, overwrite=False):
  937. if overwrite:
  938. self._svncommand(['revert', '--recursive'])
  939. args = ['checkout']
  940. if self._svnversion >= (1, 5):
  941. args.append('--force')
  942. # The revision must be specified at the end of the URL to properly
  943. # update to a directory which has since been deleted and recreated.
  944. args.append('%s@%s' % (state[0], state[1]))
  945. status, err = self._svncommand(args, failok=True)
  946. _sanitize(self._ui, self._ctx._repo.wjoin(self._path), '.svn')
  947. if not re.search('Checked out revision [0-9]+.', status):
  948. if ('is already a working copy for a different URL' in err
  949. and (self._wcchanged()[:2] == (False, False))):
  950. # obstructed but clean working copy, so just blow it away.
  951. self.remove()
  952. self.get(state, overwrite=False)
  953. return
  954. raise util.Abort((status or err).splitlines()[-1])
  955. self._ui.status(status)
  956. @annotatesubrepoerror
  957. def merge(self, state):
  958. old = self._state[1]
  959. new = state[1]
  960. wcrev = self._wcrev()
  961. if new != wcrev:
  962. dirty = old == wcrev or self._wcchanged()[0]
  963. if _updateprompt(self._ui, self, dirty, wcrev, new):
  964. self.get(state, False)
  965. def push(self, opts):
  966. # push is a no-op for SVN
  967. return True
  968. @annotatesubrepoerror
  969. def files(self):
  970. output = self._svncommand(['list', '--recursive', '--xml'])[0]
  971. doc = xml.dom.minidom.parseString(output)
  972. paths = []
  973. for e in doc.getElementsByTagName('entry'):
  974. kind = str(e.getAttribute('kind'))
  975. if kind != 'file':
  976. continue
  977. name = ''.join(c.data for c
  978. in e.getElementsByTagName('name')[0].childNodes
  979. if c.nodeType == c.TEXT_NODE)
  980. paths.append(name.encode('utf-8'))
  981. return paths
  982. def filedata(self, name):
  983. return self._svncommand(['cat'], name)[0]
  984. class gitsubrepo(abstractsubrepo):
  985. def __init__(self, ctx, path, state):
  986. self._state = state
  987. self._ctx = ctx
  988. self._path = path
  989. self._relpath = os.path.join(reporelpath(ctx._repo), path)
  990. self._abspath = ctx._repo.wjoin(path)
  991. self._subparent = ctx._repo
  992. self._ui = ctx._repo.ui
  993. self._ensuregit()
  994. def _ensuregit(self):
  995. try:
  996. self._gitexecutable = 'git'
  997. out, err = self._gitnodir(['--version'])
  998. except OSError, e:
  999. if e.errno != 2 or os.name != 'nt':
  1000. raise
  1001. self._gitexecutable = 'git.cmd'
  1002. out, err = self._gitnodir(['--version'])
  1003. versionstatus = self._checkversion(out)
  1004. if versionstatus == 'unknown':
  1005. self._ui.warn(_('cannot retrieve git version\n'))
  1006. elif versionstatus == 'abort':
  1007. raise util.Abort(_('git subrepo requires at least 1.6.0 or later'))
  1008. elif versionstatus == 'warning':
  1009. self._ui.warn(_('git subrepo requires at least 1.6.0 or later\n'))
  1010. @staticmethod
  1011. def _checkversion(out):
  1012. '''ensure git version is new enough
  1013. >>> _checkversion = gitsubrepo._checkversion
  1014. >>> _checkversion('git version 1.6.0')
  1015. 'ok'
  1016. >>> _checkversion('git version 1.8.5')
  1017. 'ok'
  1018. >>> _checkversion('git version 1.4.0')
  1019. 'abort'
  1020. >>> _checkversion('git version 1.5.0')
  1021. 'warning'
  1022. >>> _checkversion('git version 1.9-rc0')
  1023. 'ok'
  1024. >>> _checkversion('git version 1.9.0.265.g81cdec2')
  1025. 'ok'
  1026. >>> _checkversion('git version 1.9.0.GIT')
  1027. 'ok'
  1028. >>> _checkversion('git version 12345')
  1029. 'unknown'
  1030. >>> _checkversion('no')
  1031. 'unknown'
  1032. '''
  1033. m = re.search(r'^git version (\d+)\.(\d+)', out)
  1034. if not m:
  1035. return 'unknown'
  1036. version = (int(m.group(1)), int(m.group(2)))
  1037. # git 1.4.0 can't work at all, but 1.5.X can in at least some cases,
  1038. # despite the docstring comment. For now, error on 1.4.0, warn on
  1039. # 1.5.0 but attempt to continue.
  1040. if version < (1, 5):
  1041. return 'abort'
  1042. elif version < (1, 6):
  1043. return 'warning'
  1044. return 'ok'
  1045. def _gitcommand(self, commands, env=None, stream=False):
  1046. return self._gitdir(commands, env=env, stream=stream)[0]
  1047. def _gitdir(self, commands, env=None, stream=False):
  1048. return self._gitnodir(commands, env=env, stream=stream,
  1049. cwd=self._abspath)
  1050. def _gitnodir(self, commands, env=None, stream=False, cwd=None):
  1051. """Calls the git command
  1052. The methods tries to call the git command. versions prior to 1.6.0
  1053. are not supported and very probably fail.
  1054. """
  1055. self._ui.debug('%s: git %s\n' % (self._relpath, ' '.join(commands)))
  1056. # unless ui.quiet is set, print git's stderr,
  1057. # which is mostly progress and useful info
  1058. errpipe = None
  1059. if self._ui.quiet:
  1060. errpipe = open(os.devnull, 'w')
  1061. p = subprocess.Popen([self._gitexecutable] + commands, bufsize=-1,
  1062. cwd=cwd, env=env, close_fds=util.closefds,
  1063. stdout=subprocess.PIPE, stderr=errpipe)
  1064. if stream:
  1065. return p.stdout, None
  1066. retdata = p.stdout.read().strip()
  1067. # wait for the child to exit to avoid race condition.
  1068. p.wait()
  1069. if p.returncode != 0 and p.returncode != 1:
  1070. # there are certain error codes that are ok
  1071. command = commands[0]
  1072. if command in ('cat-file', 'symbolic-ref'):
  1073. return retdata, p.returncode
  1074. # for all others, abort
  1075. raise util.Abort('git %s error %d in %s' %
  1076. (command, p.returncode, self._relpath))
  1077. return retdata, p.returncode
  1078. def _gitmissing(self):
  1079. return not os.path.exists(os.path.join(self._abspath, '.git'))
  1080. def _gitstate(self):
  1081. return self._gitcommand(['rev-parse', 'HEAD'])
  1082. def _gitcurrentbranch(self):
  1083. current, err = self._gitdir(['symbolic-ref', 'HEAD', '--quiet'])
  1084. if err:
  1085. current = None
  1086. return current
  1087. def _gitremote(self, remote):
  1088. out = self._gitcommand(['remote', 'show', '-n', remote])
  1089. line = out.split('\n')[1]
  1090. i = line.index('URL: ') + len('URL: ')
  1091. return line[i:]
  1092. def _githavelocally(self, revision):
  1093. out, code = self._gitdir(['cat-file', '-e', revision])
  1094. return code == 0
  1095. def _gitisancestor(self, r1, r2):
  1096. base = self._gitcommand(['merge-base', r1, r2])
  1097. return base == r1
  1098. def _gitisbare(self):
  1099. return self._gitcommand(['config', '--bool', 'core.bare']) == 'true'
  1100. def _gitupdatestat(self):
  1101. """This must be run before git diff-index.
  1102. diff-index only looks at changes to file stat;
  1103. this command looks at file contents and updates the stat."""
  1104. self._gitcommand(['update-index', '-q', '--refresh'])
  1105. def _gitbranchmap(self):
  1106. '''returns 2 things:
  1107. a map from git branch to revision
  1108. a map from revision to branches'''
  1109. branch2rev = {}
  1110. rev2branch = {}
  1111. out = self._gitcommand(['for-each-ref', '--format',
  1112. '%(objectname) %(refname)'])
  1113. for line in out.split('\n'):
  1114. revision, ref = line.split(' ')
  1115. if (not ref.startswith('refs/heads/') and
  1116. not ref.startswith('refs/remotes/')):
  1117. continue
  1118. if ref.startswith('refs/remotes/') and ref.endswith('/HEAD'):
  1119. continue # ignore remote/HEAD redirects
  1120. branch2rev[ref] = revision
  1121. rev2branch.setdefault(revision, []).append(ref)
  1122. return branch2rev, rev2branch
  1123. def _gittracking(self, branches):
  1124. 'return map of remote branch to local tracking branch'
  1125. # assumes no more than one local tracking branch for each remote
  1126. tracking = {}
  1127. for b in branches:
  1128. if b.startswith('refs/remotes/'):
  1129. continue
  1130. bname = b.split('/', 2)[2]
  1131. remote = self._gitcommand(['config', 'branch.%s.remote' % bname])
  1132. if remote:
  1133. ref = self._gitcommand(['config', 'branch.%s.merge' % bname])
  1134. tracking['refs/remotes/%s/%s' %
  1135. (remote, ref.split('/', 2)[2])] = b
  1136. return tracking
  1137. def _abssource(self, source):
  1138. if '://' not in source:
  1139. # recognize the scp syntax as an absolute source
  1140. colon = source.find(':')
  1141. if colon != -1 and '/' not in source[:colon]:
  1142. return source
  1143. self._subsource = source
  1144. return _abssource(self)
  1145. def _fetch(self, source, revision):
  1146. if self._gitmissing():
  1147. source = self._abssource(source)
  1148. self._ui.status(_('cloning subrepo %s from %s\n') %
  1149. (self._relpath, source))
  1150. self._gitnodir(['clone', source, self._abspath])
  1151. if self._githavelocally(revision):
  1152. return
  1153. self._ui.status(_('pulling subrepo %s from %s\n') %
  1154. (self._relpath, self._gitremote('origin')))
  1155. # try only origin: the originally cloned repo
  1156. self._gitcommand(['fetch'])
  1157. if not self._githavelocally(revision):
  1158. raise util.Abort(_("revision %s does not exist in subrepo %s\n") %
  1159. (revision, self._relpath))
  1160. @annotatesubrepoerror
  1161. def dirty(self, ignoreupdate=False):
  1162. if self._gitmissing():
  1163. return self._state[1] != ''
  1164. if self._gitisbare():
  1165. return True
  1166. if not ignoreupdate and self._state[1] != self._gitstate():
  1167. # different version checked out
  1168. return True
  1169. # check for staged changes or modified files; ignore untracked files
  1170. self._gitupdatestat()
  1171. out, code = self._gitdir(['diff-index', '--quiet', 'HEAD'])
  1172. return code == 1
  1173. def basestate(self):
  1174. return self._gitstate()
  1175. @annotatesubrepoerror
  1176. def get(self, state, overwrite=False):
  1177. source, revision, kind = state
  1178. if not revision:
  1179. self.remove()
  1180. return
  1181. self._fetch(source, revision)
  1182. # if the repo was set to be bare, unbare it
  1183. if self._gitisbare():
  1184. self._gitcommand(['config', 'core.bare', 'false'])
  1185. if self._gitstate() == revision:
  1186. self._gitcommand(['reset', '--hard', 'HEAD'])
  1187. return
  1188. elif self._gitstate() == revision:
  1189. if overwrite:
  1190. # first reset the index to unmark new files for commit, because
  1191. # reset --hard will otherwise throw away files added for commit,
  1192. # not just unmark them.
  1193. self._gitcommand(['reset', 'HEAD'])
  1194. self._gitcommand(['reset', '--hard', 'HEAD'])
  1195. return
  1196. branch2rev, rev2branch = self._gitbranchmap()
  1197. def checkout(args):
  1198. cmd = ['checkout']
  1199. if overwrite:
  1200. # first reset the index to unmark new files for commit, because
  1201. # the -f option will otherwise throw away files added for
  1202. # commit, not just unmark them.
  1203. self._gitcommand(['reset', 'HEAD'])
  1204. cmd.append('-f')
  1205. self._gitcommand(cmd + args)
  1206. _sanitize(self._ui, self._abspath, '.git')
  1207. def rawcheckout():
  1208. # no branch to checkout, check it out with no branch
  1209. self._ui.warn(_('checking out detached HEAD in subrepo %s\n') %
  1210. self._relpath)
  1211. self._ui.warn(_('check out a git branch if you intend '
  1212. 'to make changes\n'))
  1213. checkout(['-q', revision])
  1214. if revision not in rev2branch:
  1215. rawcheckout()
  1216. return
  1217. branches = rev2branch[revision]
  1218. firstlocalbranch = None
  1219. for b in branches:
  1220. if b == 'refs/heads/master':
  1221. # master trumps all other branches
  1222. checkout(['refs/heads/master'])
  1223. return
  1224. if not firstlocalbranch and not b.startswith('refs/remotes/'):
  1225. firstlocalbranch = b
  1226. if firstlocalbranch:
  1227. checkout([firstlocalbranch])
  1228. return
  1229. tracking = self._gittracking(branch2rev.keys())
  1230. # choose a remote branch already tracked if possible
  1231. remote = branches[0]
  1232. if remote not in tracking:
  1233. for b in branches:
  1234. if b in tracking:
  1235. remote = b
  1236. break
  1237. if remote not in tracking:
  1238. # create a new local tracking branch
  1239. local = remote.split('/', 3)[3]
  1240. checkout(['-b', local, remote])
  1241. elif self._gitisancestor(branch2rev[tracking[remote]], remote):
  1242. # When updating to a tracked remote branch,
  1243. # if the local tracking branch is downstream of it,
  1244. # a normal `git pull` would have performed a "fast-forward merge"
  1245. # which is equivalent to updating the local branch to the remote.
  1246. # Since we are only looking at branching at update, we need to
  1247. # detect this situation and perform this action lazily.
  1248. if tracking[remote] != self._gitcurrentbranch():
  1249. checkout([tracking[remote]])
  1250. self._gitcommand(['merge', '--ff', remote])
  1251. _sanitize(self._ui, self._abspath, '.git')
  1252. else:
  1253. # a real merge would be required, just checkout the revision
  1254. rawcheckout()
  1255. @annotatesubrepoerror
  1256. def commit(self, text, user, date):
  1257. if self._gitmissing():
  1258. raise util.Abort(_("subrepo %s is missing") % self._relpath)
  1259. cmd = ['commit', '-a', '-m', text]
  1260. env = os.environ.copy()
  1261. if user:
  1262. cmd += ['--author', user]
  1263. if date:
  1264. # git's date parser silently ignores when seconds < 1e9
  1265. # convert to ISO8601
  1266. env['GIT_AUTHOR_DATE'] = util.datestr(date,
  1267. '%Y-%m-%dT%H:%M:%S %1%2')
  1268. self._gitcommand(cmd, env=env)
  1269. # make sure commit works otherwise HEAD might not exist under certain
  1270. # circumstances
  1271. return self._gitstate()
  1272. @annotatesubrepoerror
  1273. def merge(self, state):
  1274. source, revision, kind = state
  1275. self._fetch(source, revision)
  1276. base = self._gitcommand(['merge-base', revision, self._state[1]])
  1277. self._gitupdatestat()
  1278. out, code = self._gitdir(['diff-index', '--quiet', 'HEAD'])
  1279. def mergefunc():
  1280. if base == revision:
  1281. self.get(state) # fast forward merge
  1282. elif base != self._state[1]:
  1283. self._gitcommand(['merge', '--no-commit', revision])
  1284. _sanitize(self._ui, self._abspath, '.git')
  1285. if self.dirty():
  1286. if self._gitstate() != revision:
  1287. dirty = self._gitstate() == self._state[1] or code != 0
  1288. if _updateprompt(self._ui, self, dirty,
  1289. self._state[1][:7], revision[:7]):
  1290. mergefunc()
  1291. else:
  1292. mergefunc()
  1293. @annotatesubrepoerror
  1294. def push(self, opts):
  1295. force = opts.get('force')
  1296. if not self._state[1]:
  1297. return True
  1298. if self._gitmissing():
  1299. raise util.Abort(_("subrepo %s is missing") % self._relpath)
  1300. # if a branch in origin contains the revision, nothing to do
  1301. branch2rev, rev2branch = self._gitbranchmap()
  1302. if self._state[1] in rev2branch:
  1303. for b in rev2branch[self._state[1]]:
  1304. if b.startswith('refs/remotes/origin/'):
  1305. return True
  1306. for b, revision in branch2rev.iteritems():
  1307. if b.startswith('refs/remotes/origin/'):
  1308. if self._gitisancestor(self._state[1], revision):
  1309. return True
  1310. # otherwise, try to push the currently checked out branch
  1311. cmd = ['push']
  1312. if force:
  1313. cmd.append('--force')
  1314. current = self._gitcurrentbranch()
  1315. if current:
  1316. # determine if the current branch is even useful
  1317. if not self._gitisancestor(self._state[1], current):
  1318. self._ui.warn(_('unrelated git branch checked out '
  1319. 'in subrepo %s\n') % self._relpath)
  1320. return False
  1321. self._ui.status(_('pushing branch %s of subrepo %s\n') %
  1322. (current.split('/', 2)[2], self._relpath))
  1323. ret = self._gitdir(cmd + ['origin', current])
  1324. return ret[1] == 0
  1325. else:
  1326. self._ui.warn(_('no branch checked out in subrepo %s\n'
  1327. 'cannot push revision %s\n') %
  1328. (self._relpath, self._state[1]))
  1329. return False
  1330. @annotatesubrepoerror
  1331. def remove(self):
  1332. if self._gitmissing():
  1333. return
  1334. if self.dirty():
  1335. self._ui.warn(_('not removing repo %s because '
  1336. 'it has changes.\n') % self._relpath)
  1337. return
  1338. # we can't fully delete the repository as it may contain
  1339. # local-only history
  1340. self._ui.note(_('removing subrepo %s\n') % self._relpath)
  1341. self._gitcommand(['config', 'core.bare', 'true'])
  1342. for f in os.listdir(self._abspath):
  1343. if f == '.git':
  1344. continue
  1345. path = os.path.join(self._abspath, f)
  1346. if os.path.isdir(path) and not os.path.islink(path):
  1347. shutil.rmtree(path)
  1348. else:
  1349. os.remove(path)
  1350. def archive(self, ui, archiver, prefix, match=None):
  1351. total = 0
  1352. source, revision = self._state
  1353. if not revision:
  1354. return total
  1355. self._fetch(source, revision)
  1356. # Parse git's native archive command.
  1357. # This should be much faster than manually traversing the trees
  1358. # and objects with many subprocess calls.
  1359. tarstream = self._gitcommand(['archive', revision], stream=True)
  1360. tar = tarfile.open(fileobj=tarstream, mode='r|')
  1361. relpath = subrelpath(self)
  1362. ui.progress(_('archiving (%s)') % relpath, 0, unit=_('files'))
  1363. for i, info in enumerate(tar):
  1364. if info.isdir():
  1365. continue
  1366. if match and not match(info.name):
  1367. continue
  1368. if info.issym():
  1369. data = info.linkname
  1370. else:
  1371. data = tar.extractfile(info).read()
  1372. archiver.addfile(os.path.join(prefix, self._path, info.name),
  1373. info.mode, info.issym(), data)
  1374. total += 1
  1375. ui.progress(_('archiving (%s)') % relpath, i + 1,
  1376. unit=_('files'))
  1377. ui.progress(_('archiving (%s)') % relpath, None)
  1378. return total
  1379. @annotatesubrepoerror
  1380. def status(self, rev2, **opts):
  1381. rev1 = self._state[1]
  1382. if self._gitmissing() or not rev1:
  1383. # if the repo is missing, return no results
  1384. return [], [], [], [], [], [], []
  1385. modified, added, removed = [], [], []
  1386. self._gitupdatestat()
  1387. if rev2:
  1388. command = ['diff-tree', rev1, rev2]
  1389. else:
  1390. command = ['diff-index', rev1]
  1391. out = self._gitcommand(command)
  1392. for line in out.split('\n'):
  1393. tab = line.find('\t')
  1394. if tab == -1:
  1395. continue
  1396. status, f = line[tab - 1], line[tab + 1:]
  1397. if status == 'M':
  1398. modified.append(f)
  1399. elif status == 'A':
  1400. added.append(f)
  1401. elif status == 'D':
  1402. removed.append(f)
  1403. deleted = unknown = ignored = clean = []
  1404. return modified, added, removed, deleted, unknown, ignored, clean
  1405. def shortid(self, revid):
  1406. return revid[:7]
  1407. types = {
  1408. 'hg': hgsubrepo,
  1409. 'svn': svnsubrepo,
  1410. 'git': gitsubrepo,
  1411. }