您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

351 行
17KB

  1. from .base import (
  2. Submodule,
  3. UpdateProgress
  4. )
  5. from .util import (
  6. find_first_remote_branch
  7. )
  8. from git.exc import InvalidGitRepositoryError
  9. import git
  10. import logging
  11. __all__ = ["RootModule", "RootUpdateProgress"]
  12. log = logging.getLogger('git.objects.submodule.root')
  13. log.addHandler(logging.NullHandler())
  14. class RootUpdateProgress(UpdateProgress):
  15. """Utility class which adds more opcodes to the UpdateProgress"""
  16. REMOVE, PATHCHANGE, BRANCHCHANGE, URLCHANGE = [
  17. 1 << x for x in range(UpdateProgress._num_op_codes, UpdateProgress._num_op_codes + 4)]
  18. _num_op_codes = UpdateProgress._num_op_codes + 4
  19. __slots__ = ()
  20. BEGIN = RootUpdateProgress.BEGIN
  21. END = RootUpdateProgress.END
  22. REMOVE = RootUpdateProgress.REMOVE
  23. BRANCHCHANGE = RootUpdateProgress.BRANCHCHANGE
  24. URLCHANGE = RootUpdateProgress.URLCHANGE
  25. PATHCHANGE = RootUpdateProgress.PATHCHANGE
  26. class RootModule(Submodule):
  27. """A (virtual) Root of all submodules in the given repository. It can be used
  28. to more easily traverse all submodules of the master repository"""
  29. __slots__ = ()
  30. k_root_name = '__ROOT__'
  31. def __init__(self, repo):
  32. # repo, binsha, mode=None, path=None, name = None, parent_commit=None, url=None, ref=None)
  33. super(RootModule, self).__init__(
  34. repo,
  35. binsha=self.NULL_BIN_SHA,
  36. mode=self.k_default_mode,
  37. path='',
  38. name=self.k_root_name,
  39. parent_commit=repo.head.commit,
  40. url='',
  41. branch_path=git.Head.to_full_path(self.k_head_default)
  42. )
  43. def _clear_cache(self):
  44. """May not do anything"""
  45. pass
  46. #{ Interface
  47. def update(self, previous_commit=None, recursive=True, force_remove=False, init=True,
  48. to_latest_revision=False, progress=None, dry_run=False, force_reset=False,
  49. keep_going=False):
  50. """Update the submodules of this repository to the current HEAD commit.
  51. This method behaves smartly by determining changes of the path of a submodules
  52. repository, next to changes to the to-be-checked-out commit or the branch to be
  53. checked out. This works if the submodules ID does not change.
  54. Additionally it will detect addition and removal of submodules, which will be handled
  55. gracefully.
  56. :param previous_commit: If set to a commit'ish, the commit we should use
  57. as the previous commit the HEAD pointed to before it was set to the commit it points to now.
  58. If None, it defaults to HEAD@{1} otherwise
  59. :param recursive: if True, the children of submodules will be updated as well
  60. using the same technique
  61. :param force_remove: If submodules have been deleted, they will be forcibly removed.
  62. Otherwise the update may fail if a submodule's repository cannot be deleted as
  63. changes have been made to it (see Submodule.update() for more information)
  64. :param init: If we encounter a new module which would need to be initialized, then do it.
  65. :param to_latest_revision: If True, instead of checking out the revision pointed to
  66. by this submodule's sha, the checked out tracking branch will be merged with the
  67. latest remote branch fetched from the repository's origin.
  68. Unless force_reset is specified, a local tracking branch will never be reset into its past, therefore
  69. the remote branch must be in the future for this to have an effect.
  70. :param force_reset: if True, submodules may checkout or reset their branch even if the repository has
  71. pending changes that would be overwritten, or if the local tracking branch is in the future of the
  72. remote tracking branch and would be reset into its past.
  73. :param progress: RootUpdateProgress instance or None if no progress should be sent
  74. :param dry_run: if True, operations will not actually be performed. Progress messages
  75. will change accordingly to indicate the WOULD DO state of the operation.
  76. :param keep_going: if True, we will ignore but log all errors, and keep going recursively.
  77. Unless dry_run is set as well, keep_going could cause subsequent/inherited errors you wouldn't see
  78. otherwise.
  79. In conjunction with dry_run, it can be useful to anticipate all errors when updating submodules
  80. :return: self"""
  81. if self.repo.bare:
  82. raise InvalidGitRepositoryError("Cannot update submodules in bare repositories")
  83. # END handle bare
  84. if progress is None:
  85. progress = RootUpdateProgress()
  86. # END assure progress is set
  87. prefix = ''
  88. if dry_run:
  89. prefix = 'DRY-RUN: '
  90. repo = self.repo
  91. try:
  92. # SETUP BASE COMMIT
  93. ###################
  94. cur_commit = repo.head.commit
  95. if previous_commit is None:
  96. try:
  97. previous_commit = repo.commit(repo.head.log_entry(-1).oldhexsha)
  98. if previous_commit.binsha == previous_commit.NULL_BIN_SHA:
  99. raise IndexError
  100. # END handle initial commit
  101. except IndexError:
  102. # in new repositories, there is no previous commit
  103. previous_commit = cur_commit
  104. # END exception handling
  105. else:
  106. previous_commit = repo.commit(previous_commit) # obtain commit object
  107. # END handle previous commit
  108. psms = self.list_items(repo, parent_commit=previous_commit)
  109. sms = self.list_items(repo)
  110. spsms = set(psms)
  111. ssms = set(sms)
  112. # HANDLE REMOVALS
  113. ###################
  114. rrsm = (spsms - ssms)
  115. len_rrsm = len(rrsm)
  116. for i, rsm in enumerate(rrsm):
  117. op = REMOVE
  118. if i == 0:
  119. op |= BEGIN
  120. # END handle begin
  121. # fake it into thinking its at the current commit to allow deletion
  122. # of previous module. Trigger the cache to be updated before that
  123. progress.update(op, i, len_rrsm, prefix + "Removing submodule %r at %s" % (rsm.name, rsm.abspath))
  124. rsm._parent_commit = repo.head.commit
  125. rsm.remove(configuration=False, module=True, force=force_remove, dry_run=dry_run)
  126. if i == len_rrsm - 1:
  127. op |= END
  128. # END handle end
  129. progress.update(op, i, len_rrsm, prefix + "Done removing submodule %r" % rsm.name)
  130. # END for each removed submodule
  131. # HANDLE PATH RENAMES
  132. #####################
  133. # url changes + branch changes
  134. csms = (spsms & ssms)
  135. len_csms = len(csms)
  136. for i, csm in enumerate(csms):
  137. psm = psms[csm.name]
  138. sm = sms[csm.name]
  139. # PATH CHANGES
  140. ##############
  141. if sm.path != psm.path and psm.module_exists():
  142. progress.update(BEGIN | PATHCHANGE, i, len_csms, prefix +
  143. "Moving repository of submodule %r from %s to %s"
  144. % (sm.name, psm.abspath, sm.abspath))
  145. # move the module to the new path
  146. if not dry_run:
  147. psm.move(sm.path, module=True, configuration=False)
  148. # END handle dry_run
  149. progress.update(
  150. END | PATHCHANGE, i, len_csms, prefix + "Done moving repository of submodule %r" % sm.name)
  151. # END handle path changes
  152. if sm.module_exists():
  153. # HANDLE URL CHANGE
  154. ###################
  155. if sm.url != psm.url:
  156. # Add the new remote, remove the old one
  157. # This way, if the url just changes, the commits will not
  158. # have to be re-retrieved
  159. nn = '__new_origin__'
  160. smm = sm.module()
  161. rmts = smm.remotes
  162. # don't do anything if we already have the url we search in place
  163. if len([r for r in rmts if r.url == sm.url]) == 0:
  164. progress.update(BEGIN | URLCHANGE, i, len_csms, prefix +
  165. "Changing url of submodule %r from %s to %s" % (sm.name, psm.url, sm.url))
  166. if not dry_run:
  167. assert nn not in [r.name for r in rmts]
  168. smr = smm.create_remote(nn, sm.url)
  169. smr.fetch(progress=progress)
  170. # If we have a tracking branch, it should be available
  171. # in the new remote as well.
  172. if len([r for r in smr.refs if r.remote_head == sm.branch_name]) == 0:
  173. raise ValueError(
  174. "Submodule branch named %r was not available in new submodule remote at %r"
  175. % (sm.branch_name, sm.url)
  176. )
  177. # END head is not detached
  178. # now delete the changed one
  179. rmt_for_deletion = None
  180. for remote in rmts:
  181. if remote.url == psm.url:
  182. rmt_for_deletion = remote
  183. break
  184. # END if urls match
  185. # END for each remote
  186. # if we didn't find a matching remote, but have exactly one,
  187. # we can safely use this one
  188. if rmt_for_deletion is None:
  189. if len(rmts) == 1:
  190. rmt_for_deletion = rmts[0]
  191. else:
  192. # if we have not found any remote with the original url
  193. # we may not have a name. This is a special case,
  194. # and its okay to fail here
  195. # Alternatively we could just generate a unique name and leave all
  196. # existing ones in place
  197. raise InvalidGitRepositoryError(
  198. "Couldn't find original remote-repo at url %r" % psm.url)
  199. # END handle one single remote
  200. # END handle check we found a remote
  201. orig_name = rmt_for_deletion.name
  202. smm.delete_remote(rmt_for_deletion)
  203. # NOTE: Currently we leave tags from the deleted remotes
  204. # as well as separate tracking branches in the possibly totally
  205. # changed repository ( someone could have changed the url to
  206. # another project ). At some point, one might want to clean
  207. # it up, but the danger is high to remove stuff the user
  208. # has added explicitly
  209. # rename the new remote back to what it was
  210. smr.rename(orig_name)
  211. # early on, we verified that the our current tracking branch
  212. # exists in the remote. Now we have to assure that the
  213. # sha we point to is still contained in the new remote
  214. # tracking branch.
  215. smsha = sm.binsha
  216. found = False
  217. rref = smr.refs[self.branch_name]
  218. for c in rref.commit.traverse():
  219. if c.binsha == smsha:
  220. found = True
  221. break
  222. # END traverse all commits in search for sha
  223. # END for each commit
  224. if not found:
  225. # adjust our internal binsha to use the one of the remote
  226. # this way, it will be checked out in the next step
  227. # This will change the submodule relative to us, so
  228. # the user will be able to commit the change easily
  229. log.warn("Current sha %s was not contained in the tracking\
  230. branch at the new remote, setting it the the remote's tracking branch", sm.hexsha)
  231. sm.binsha = rref.commit.binsha
  232. # END reset binsha
  233. # NOTE: All checkout is performed by the base implementation of update
  234. # END handle dry_run
  235. progress.update(
  236. END | URLCHANGE, i, len_csms, prefix + "Done adjusting url of submodule %r" % (sm.name))
  237. # END skip remote handling if new url already exists in module
  238. # END handle url
  239. # HANDLE PATH CHANGES
  240. #####################
  241. if sm.branch_path != psm.branch_path:
  242. # finally, create a new tracking branch which tracks the
  243. # new remote branch
  244. progress.update(BEGIN | BRANCHCHANGE, i, len_csms, prefix +
  245. "Changing branch of submodule %r from %s to %s"
  246. % (sm.name, psm.branch_path, sm.branch_path))
  247. if not dry_run:
  248. smm = sm.module()
  249. smmr = smm.remotes
  250. # As the branch might not exist yet, we will have to fetch all remotes to be sure ... .
  251. for remote in smmr:
  252. remote.fetch(progress=progress)
  253. # end for each remote
  254. try:
  255. tbr = git.Head.create(smm, sm.branch_name, logmsg='branch: Created from HEAD')
  256. except OSError:
  257. # ... or reuse the existing one
  258. tbr = git.Head(smm, sm.branch_path)
  259. # END assure tracking branch exists
  260. tbr.set_tracking_branch(find_first_remote_branch(smmr, sm.branch_name))
  261. # NOTE: All head-resetting is done in the base implementation of update
  262. # but we will have to checkout the new branch here. As it still points to the currently
  263. # checkout out commit, we don't do any harm.
  264. # As we don't want to update working-tree or index, changing the ref is all there is to do
  265. smm.head.reference = tbr
  266. # END handle dry_run
  267. progress.update(
  268. END | BRANCHCHANGE, i, len_csms, prefix + "Done changing branch of submodule %r" % sm.name)
  269. # END handle branch
  270. # END handle
  271. # END for each common submodule
  272. except Exception as err:
  273. if not keep_going:
  274. raise
  275. log.error(str(err))
  276. # end handle keep_going
  277. # FINALLY UPDATE ALL ACTUAL SUBMODULES
  278. ######################################
  279. for sm in sms:
  280. # update the submodule using the default method
  281. sm.update(recursive=False, init=init, to_latest_revision=to_latest_revision,
  282. progress=progress, dry_run=dry_run, force=force_reset, keep_going=keep_going)
  283. # update recursively depth first - question is which inconsitent
  284. # state will be better in case it fails somewhere. Defective branch
  285. # or defective depth. The RootSubmodule type will never process itself,
  286. # which was done in the previous expression
  287. if recursive:
  288. # the module would exist by now if we are not in dry_run mode
  289. if sm.module_exists():
  290. type(self)(sm.module()).update(recursive=True, force_remove=force_remove,
  291. init=init, to_latest_revision=to_latest_revision,
  292. progress=progress, dry_run=dry_run, force_reset=force_reset,
  293. keep_going=keep_going)
  294. # END handle dry_run
  295. # END handle recursive
  296. # END for each submodule to update
  297. return self
  298. def module(self):
  299. """:return: the actual repository containing the submodules"""
  300. return self.repo
  301. #} END interface
  302. #} END classes