PageRenderTime 46ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/hgext/robustcheckout.py

https://gitlab.com/astian/build-tools
Python | 333 lines | 307 code | 10 blank | 16 comment | 1 complexity | ccfd32f5b3be272517a060d5ee55ce5e MD5 | raw file
  1. # This software may be used and distributed according to the terms of the
  2. # GNU General Public License version 2 or any later version.
  3. """Robustly perform a checkout.
  4. This extension provides the ``hg robustcheckout`` command for
  5. ensuring a working directory is updated to the specified revision
  6. from a source repo using best practices to ensure optimal clone
  7. times and storage efficiency.
  8. """
  9. from __future__ import absolute_import
  10. import contextlib
  11. import errno
  12. import functools
  13. import os
  14. import re
  15. from mercurial.i18n import _
  16. from mercurial.node import hex
  17. from mercurial import (
  18. commands,
  19. error,
  20. exchange,
  21. extensions,
  22. cmdutil,
  23. hg,
  24. scmutil,
  25. util,
  26. )
  27. testedwith = '3.5 3.6 3.7 3.8'
  28. minimumhgversion = '3.7'
  29. cmdtable = {}
  30. command = cmdutil.command(cmdtable)
  31. if os.name == 'nt':
  32. import ctypes
  33. # Get a reference to the DeleteFileW function
  34. # DeleteFileW accepts filenames encoded as a null terminated sequence of
  35. # wide chars (UTF-16). Python's ctypes.c_wchar_p correctly encodes unicode
  36. # strings to null terminated UTF-16 strings.
  37. # However, we receive (byte) strings from mercurial. When these are passed
  38. # to DeleteFileW via the c_wchar_p type, they are implicitly decoded via
  39. # the 'mbcs' encoding on windows.
  40. kernel32 = ctypes.windll.kernel32
  41. DeleteFile = kernel32.DeleteFileW
  42. DeleteFile.argtypes = [ctypes.c_wchar_p]
  43. DeleteFile.restype = ctypes.c_bool
  44. def unlinklong(fn):
  45. normalized_path = '\\\\?\\' + os.path.normpath(fn)
  46. if not DeleteFile(normalized_path):
  47. raise OSError(errno.EPERM, "couldn't remove long path", fn)
  48. # Not needed on other platforms, but is handy for testing
  49. else:
  50. def unlinklong(fn):
  51. os.unlink(fn)
  52. def unlinkwrapper(unlinkorig, fn, ui):
  53. '''Calls unlink_long if original unlink function fails.'''
  54. try:
  55. ui.debug('calling unlink_orig %s\n' % fn)
  56. return unlinkorig(fn)
  57. except WindowsError as e:
  58. # Windows error 3 corresponds to ERROR_PATH_NOT_FOUND
  59. # only handle this case; re-raise the exception for other kinds of
  60. # failures.
  61. if e.winerror != 3:
  62. raise
  63. ui.debug('caught WindowsError ERROR_PATH_NOT_FOUND; '
  64. 'calling unlink_long %s\n' % fn)
  65. return unlinklong(fn)
  66. @contextlib.contextmanager
  67. def wrapunlink(ui):
  68. '''Context manager that temporarily monkeypatches unlink functions.'''
  69. purgemod = extensions.find('purge')
  70. to_wrap = [(purgemod.util, 'unlink')]
  71. # Pass along the ui object to the unlink_wrapper so we can get logging out
  72. # of it.
  73. wrapped = functools.partial(unlinkwrapper, ui=ui)
  74. # Wrap the original function(s) with our unlink wrapper.
  75. originals = {}
  76. for mod, func in to_wrap:
  77. ui.debug('wrapping %s %s\n' % (mod, func))
  78. originals[mod, func] = extensions.wrapfunction(mod, func, wrapped)
  79. try:
  80. yield
  81. finally:
  82. # Restore the originals.
  83. for mod, func in to_wrap:
  84. ui.debug('restoring %s %s\n' % (mod, func))
  85. setattr(mod, func, originals[mod, func])
  86. def purgewrapper(orig, ui, *args, **kwargs):
  87. '''Runs original purge() command with unlink monkeypatched.'''
  88. with wrapunlink(ui):
  89. return orig(ui, *args, **kwargs)
  90. @command('robustcheckout', [
  91. ('', 'upstream', '', 'URL of upstream repo to clone from'),
  92. ('r', 'revision', '', 'Revision to check out'),
  93. ('b', 'branch', '', 'Branch to check out'),
  94. ('', 'purge', False, 'Whether to purge the working directory'),
  95. ('', 'sharebase', '', 'Directory where shared repos should be placed'),
  96. ],
  97. '[OPTION]... URL DEST',
  98. norepo=True)
  99. def robustcheckout(ui, url, dest, upstream=None, revision=None, branch=None,
  100. purge=False, sharebase=None):
  101. """Ensure a working copy has the specified revision checked out."""
  102. if not revision and not branch:
  103. raise error.Abort('must specify one of --revision or --branch')
  104. if revision and branch:
  105. raise error.Abort('cannot specify both --revision and --branch')
  106. # Require revision to look like a SHA-1.
  107. if revision:
  108. if len(revision) < 12 or len(revision) > 40 or not re.match('^[a-f0-9]+$', revision):
  109. raise error.Abort('--revision must be a SHA-1 fragment 12-40 '
  110. 'characters long')
  111. sharebase = sharebase or ui.config('share', 'pool')
  112. if not sharebase:
  113. raise error.Abort('share base directory not defined; refusing to operate',
  114. hint='define share.pool config option or pass --sharebase')
  115. # worker.backgroundclose only makes things faster if running anti-virus,
  116. # which our automation doesn't. Disable it.
  117. ui.setconfig('worker', 'backgroundclose', False)
  118. sharebase = os.path.realpath(sharebase)
  119. return _docheckout(ui, url, dest, upstream, revision, branch, purge,
  120. sharebase)
  121. def _docheckout(ui, url, dest, upstream, revision, branch, purge, sharebase):
  122. def callself():
  123. return _docheckout(ui, url, dest, upstream, revision, branch, purge,
  124. sharebase)
  125. ui.write('ensuring %s@%s is available at %s\n' % (url, revision or branch,
  126. dest))
  127. destvfs = scmutil.vfs(dest, audit=False, realpath=True)
  128. if destvfs.exists() and not destvfs.exists('.hg'):
  129. raise error.Abort('destination exists but no .hg directory')
  130. # Require checkouts to be tied to shared storage because efficiency.
  131. if destvfs.exists('.hg') and not destvfs.exists('.hg/sharedpath'):
  132. ui.warn('(destination is not shared; deleting)\n')
  133. destvfs.rmtree(forcibly=True)
  134. # Verify the shared path exists and is using modern pooled storage.
  135. if destvfs.exists('.hg/sharedpath'):
  136. storepath = destvfs.read('.hg/sharedpath').strip()
  137. ui.write('(existing repository shared store: %s)\n' % storepath)
  138. if not os.path.exists(storepath):
  139. ui.warn('(shared store does not exist; deleting)\n')
  140. destvfs.rmtree(forcibly=True)
  141. elif not re.search('[a-f0-9]{40}/\.hg$', storepath.replace('\\', '/')):
  142. ui.warn('(shared store does not belong to pooled storage; '
  143. 'deleting to improve efficiency)\n')
  144. destvfs.rmtree(forcibly=True)
  145. # FUTURE when we require generaldelta, this is where we can check
  146. # for that.
  147. def deletesharedstore():
  148. storepath = destvfs.read('.hg/sharedpath').strip()
  149. if storepath.endswith('.hg'):
  150. storepath = os.path.dirname(storepath)
  151. storevfs = scmutil.vfs(storepath, audit=False)
  152. storevfs.rmtree(forcibly=True)
  153. def handlerepoerror(e):
  154. if e.message == _('abandoned transaction found'):
  155. ui.warn('(abandoned transaction found; trying to recover)\n')
  156. repo = hg.repository(ui, dest)
  157. if not repo.recover():
  158. ui.warn('(could not recover repo state; '
  159. 'deleting shared store)\n')
  160. deletesharedstore()
  161. ui.warn('(attempting checkout from beginning)\n')
  162. return callself()
  163. raise
  164. # At this point we either have an existing working directory using
  165. # shared, pooled storage or we have nothing.
  166. created = False
  167. if not destvfs.exists():
  168. # Ensure parent directories of destination exist.
  169. # Mercurial 3.8 removed ensuredirs and made makedirs race safe.
  170. if util.safehasattr(util, 'ensuredirs'):
  171. makedirs = util.ensuredirs
  172. else:
  173. makedirs = util.makedirs
  174. makedirs(os.path.dirname(destvfs.base), notindexed=True)
  175. makedirs(sharebase, notindexed=True)
  176. if upstream:
  177. ui.write('(cloning from upstream repo %s)\n' % upstream)
  178. cloneurl = upstream or url
  179. try:
  180. res = hg.clone(ui, {}, cloneurl, dest=dest, update=False,
  181. shareopts={'pool': sharebase, 'mode': 'identity'})
  182. except error.RepoError as e:
  183. return handlerepoerror(e)
  184. except error.RevlogError as e:
  185. ui.warn('(repo corruption: %s; deleting shared store)\n' % e.message)
  186. deletesharedstore()
  187. return callself()
  188. # TODO retry here.
  189. if res is None:
  190. raise error.Abort('clone failed')
  191. # Verify it is using shared pool storage.
  192. if not destvfs.exists('.hg/sharedpath'):
  193. raise error.Abort('clone did not create a shared repo')
  194. created = True
  195. # The destination .hg directory should exist. Now make sure we have the
  196. # wanted revision.
  197. repo = hg.repository(ui, dest)
  198. # We only pull if we are using symbolic names or the requested revision
  199. # doesn't exist.
  200. havewantedrev = False
  201. if revision and revision in repo:
  202. ctx = repo[revision]
  203. if not ctx.hex().startswith(revision):
  204. raise error.Abort('--revision argument is ambiguous',
  205. hint='must be the first 12+ characters of a '
  206. 'SHA-1 fragment')
  207. checkoutrevision = ctx.hex()
  208. havewantedrev = True
  209. if not havewantedrev:
  210. ui.write('(pulling to obtain %s)\n' % (revision or branch,))
  211. try:
  212. remote = hg.peer(repo, {}, url)
  213. pullrevs = [remote.lookup(revision or branch)]
  214. checkoutrevision = hex(pullrevs[0])
  215. if branch:
  216. ui.warn('(remote resolved %s to %s; '
  217. 'result is not deterministic)\n' %
  218. (branch, checkoutrevision))
  219. if checkoutrevision in repo:
  220. ui.warn('(revision already present locally; not pulling)\n')
  221. else:
  222. pullop = exchange.pull(repo, remote, heads=pullrevs)
  223. if not pullop.rheads:
  224. raise error.Abort('unable to pull requested revision')
  225. except error.Abort as e:
  226. if e.message == _('repository is unrelated'):
  227. ui.warn('(repository is unrelated; deleting)\n')
  228. destvfs.rmtree(forcibly=True)
  229. return callself()
  230. raise
  231. except error.RepoError as e:
  232. return handlerepoerror(e)
  233. except error.RevlogError as e:
  234. ui.warn('(repo corruption: %s; deleting shared store)\n' % e.message)
  235. deletesharedstore()
  236. return callself()
  237. finally:
  238. remote.close()
  239. # Now we should have the wanted revision in the store. Perform
  240. # working directory manipulation.
  241. # Purge if requested. We purge before update because this way we're
  242. # guaranteed to not have conflicts on `hg update`.
  243. if purge and not created:
  244. ui.write('(purging working directory)\n')
  245. purgeext = extensions.find('purge')
  246. if purgeext.purge(ui, repo, all=True, abort_on_err=True,
  247. # The function expects all arguments to be
  248. # defined.
  249. **{'print': None, 'print0': None, 'dirs': None,
  250. 'files': None}):
  251. raise error.Abort('error purging')
  252. # Update the working directory.
  253. if commands.update(ui, repo, rev=checkoutrevision, clean=True):
  254. raise error.Abort('error updating')
  255. ui.write('updated to %s\n' % checkoutrevision)
  256. return None
  257. def extsetup(ui):
  258. # Ensure required extensions are loaded.
  259. for ext in ('purge', 'share'):
  260. try:
  261. extensions.find(ext)
  262. except KeyError:
  263. extensions.load(ui, ext, None)
  264. purgemod = extensions.find('purge')
  265. extensions.wrapcommand(purgemod.cmdtable, 'purge', purgewrapper)