project.py 72 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413
  1. # Copyright (C) 2008 The Android Open Source Project
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. from __future__ import print_function
  15. import traceback
  16. import errno
  17. import filecmp
  18. import os
  19. import random
  20. import re
  21. import shutil
  22. import stat
  23. import subprocess
  24. import sys
  25. import tempfile
  26. import time
  27. from color import Coloring
  28. from git_command import GitCommand, git_require
  29. from git_config import GitConfig, IsId, GetSchemeFromUrl, ID_RE
  30. from error import GitError, HookError, UploadError
  31. from error import ManifestInvalidRevisionError
  32. from error import NoManifestException
  33. from trace import IsTrace, Trace
  34. from git_refs import GitRefs, HEAD, R_HEADS, R_TAGS, R_PUB, R_M
  35. from pyversion import is_python3
  36. if not is_python3():
  37. # pylint:disable=W0622
  38. input = raw_input
  39. # pylint:enable=W0622
  40. def _lwrite(path, content):
  41. lock = '%s.lock' % path
  42. fd = open(lock, 'wb')
  43. try:
  44. fd.write(content)
  45. finally:
  46. fd.close()
  47. try:
  48. os.rename(lock, path)
  49. except OSError:
  50. os.remove(lock)
  51. raise
  52. def _error(fmt, *args):
  53. msg = fmt % args
  54. print('error: %s' % msg, file=sys.stderr)
  55. def not_rev(r):
  56. return '^' + r
  57. def sq(r):
  58. return "'" + r.replace("'", "'\''") + "'"
  59. _project_hook_list = None
  60. def _ProjectHooks():
  61. """List the hooks present in the 'hooks' directory.
  62. These hooks are project hooks and are copied to the '.git/hooks' directory
  63. of all subprojects.
  64. This function caches the list of hooks (based on the contents of the
  65. 'repo/hooks' directory) on the first call.
  66. Returns:
  67. A list of absolute paths to all of the files in the hooks directory.
  68. """
  69. global _project_hook_list
  70. if _project_hook_list is None:
  71. d = os.path.abspath(os.path.dirname(__file__))
  72. d = os.path.join(d , 'hooks')
  73. _project_hook_list = [os.path.join(d, x) for x in os.listdir(d)]
  74. return _project_hook_list
  75. class DownloadedChange(object):
  76. _commit_cache = None
  77. def __init__(self, project, base, change_id, ps_id, commit):
  78. self.project = project
  79. self.base = base
  80. self.change_id = change_id
  81. self.ps_id = ps_id
  82. self.commit = commit
  83. @property
  84. def commits(self):
  85. if self._commit_cache is None:
  86. self._commit_cache = self.project.bare_git.rev_list(
  87. '--abbrev=8',
  88. '--abbrev-commit',
  89. '--pretty=oneline',
  90. '--reverse',
  91. '--date-order',
  92. not_rev(self.base),
  93. self.commit,
  94. '--')
  95. return self._commit_cache
  96. class ReviewableBranch(object):
  97. _commit_cache = None
  98. def __init__(self, project, branch, base):
  99. self.project = project
  100. self.branch = branch
  101. self.base = base
  102. @property
  103. def name(self):
  104. return self.branch.name
  105. @property
  106. def commits(self):
  107. if self._commit_cache is None:
  108. self._commit_cache = self.project.bare_git.rev_list(
  109. '--abbrev=8',
  110. '--abbrev-commit',
  111. '--pretty=oneline',
  112. '--reverse',
  113. '--date-order',
  114. not_rev(self.base),
  115. R_HEADS + self.name,
  116. '--')
  117. return self._commit_cache
  118. @property
  119. def unabbrev_commits(self):
  120. r = dict()
  121. for commit in self.project.bare_git.rev_list(
  122. not_rev(self.base),
  123. R_HEADS + self.name,
  124. '--'):
  125. r[commit[0:8]] = commit
  126. return r
  127. @property
  128. def date(self):
  129. return self.project.bare_git.log(
  130. '--pretty=format:%cd',
  131. '-n', '1',
  132. R_HEADS + self.name,
  133. '--')
  134. def UploadForReview(self, people, auto_topic=False, draft=False):
  135. self.project.UploadForReview(self.name,
  136. people,
  137. auto_topic=auto_topic,
  138. draft=draft)
  139. def GetPublishedRefs(self):
  140. refs = {}
  141. output = self.project.bare_git.ls_remote(
  142. self.branch.remote.SshReviewUrl(self.project.UserEmail),
  143. 'refs/changes/*')
  144. for line in output.split('\n'):
  145. try:
  146. (sha, ref) = line.split()
  147. refs[sha] = ref
  148. except ValueError:
  149. pass
  150. return refs
  151. class StatusColoring(Coloring):
  152. def __init__(self, config):
  153. Coloring.__init__(self, config, 'status')
  154. self.project = self.printer('header', attr = 'bold')
  155. self.branch = self.printer('header', attr = 'bold')
  156. self.nobranch = self.printer('nobranch', fg = 'red')
  157. self.important = self.printer('important', fg = 'red')
  158. self.added = self.printer('added', fg = 'green')
  159. self.changed = self.printer('changed', fg = 'red')
  160. self.untracked = self.printer('untracked', fg = 'red')
  161. class DiffColoring(Coloring):
  162. def __init__(self, config):
  163. Coloring.__init__(self, config, 'diff')
  164. self.project = self.printer('header', attr = 'bold')
  165. class _Annotation:
  166. def __init__(self, name, value, keep):
  167. self.name = name
  168. self.value = value
  169. self.keep = keep
  170. class _CopyFile:
  171. def __init__(self, src, dest, abssrc, absdest):
  172. self.src = src
  173. self.dest = dest
  174. self.abs_src = abssrc
  175. self.abs_dest = absdest
  176. def _Copy(self):
  177. src = self.abs_src
  178. dest = self.abs_dest
  179. # copy file if it does not exist or is out of date
  180. if not os.path.exists(dest) or not filecmp.cmp(src, dest):
  181. try:
  182. # remove existing file first, since it might be read-only
  183. if os.path.exists(dest):
  184. os.remove(dest)
  185. else:
  186. dest_dir = os.path.dirname(dest)
  187. if not os.path.isdir(dest_dir):
  188. os.makedirs(dest_dir)
  189. shutil.copy(src, dest)
  190. # make the file read-only
  191. mode = os.stat(dest)[stat.ST_MODE]
  192. mode = mode & ~(stat.S_IWUSR | stat.S_IWGRP | stat.S_IWOTH)
  193. os.chmod(dest, mode)
  194. except IOError:
  195. _error('Cannot copy file %s to %s', src, dest)
  196. class RemoteSpec(object):
  197. def __init__(self,
  198. name,
  199. url = None,
  200. review = None):
  201. self.name = name
  202. self.url = url
  203. self.review = review
  204. class RepoHook(object):
  205. """A RepoHook contains information about a script to run as a hook.
  206. Hooks are used to run a python script before running an upload (for instance,
  207. to run presubmit checks). Eventually, we may have hooks for other actions.
  208. This shouldn't be confused with files in the 'repo/hooks' directory. Those
  209. files are copied into each '.git/hooks' folder for each project. Repo-level
  210. hooks are associated instead with repo actions.
  211. Hooks are always python. When a hook is run, we will load the hook into the
  212. interpreter and execute its main() function.
  213. """
  214. def __init__(self,
  215. hook_type,
  216. hooks_project,
  217. topdir,
  218. abort_if_user_denies=False):
  219. """RepoHook constructor.
  220. Params:
  221. hook_type: A string representing the type of hook. This is also used
  222. to figure out the name of the file containing the hook. For
  223. example: 'pre-upload'.
  224. hooks_project: The project containing the repo hooks. If you have a
  225. manifest, this is manifest.repo_hooks_project. OK if this is None,
  226. which will make the hook a no-op.
  227. topdir: Repo's top directory (the one containing the .repo directory).
  228. Scripts will run with CWD as this directory. If you have a manifest,
  229. this is manifest.topdir
  230. abort_if_user_denies: If True, we'll throw a HookError() if the user
  231. doesn't allow us to run the hook.
  232. """
  233. self._hook_type = hook_type
  234. self._hooks_project = hooks_project
  235. self._topdir = topdir
  236. self._abort_if_user_denies = abort_if_user_denies
  237. # Store the full path to the script for convenience.
  238. if self._hooks_project:
  239. self._script_fullpath = os.path.join(self._hooks_project.worktree,
  240. self._hook_type + '.py')
  241. else:
  242. self._script_fullpath = None
  243. def _GetHash(self):
  244. """Return a hash of the contents of the hooks directory.
  245. We'll just use git to do this. This hash has the property that if anything
  246. changes in the directory we will return a different has.
  247. SECURITY CONSIDERATION:
  248. This hash only represents the contents of files in the hook directory, not
  249. any other files imported or called by hooks. Changes to imported files
  250. can change the script behavior without affecting the hash.
  251. Returns:
  252. A string representing the hash. This will always be ASCII so that it can
  253. be printed to the user easily.
  254. """
  255. assert self._hooks_project, "Must have hooks to calculate their hash."
  256. # We will use the work_git object rather than just calling GetRevisionId().
  257. # That gives us a hash of the latest checked in version of the files that
  258. # the user will actually be executing. Specifically, GetRevisionId()
  259. # doesn't appear to change even if a user checks out a different version
  260. # of the hooks repo (via git checkout) nor if a user commits their own revs.
  261. #
  262. # NOTE: Local (non-committed) changes will not be factored into this hash.
  263. # I think this is OK, since we're really only worried about warning the user
  264. # about upstream changes.
  265. return self._hooks_project.work_git.rev_parse('HEAD')
  266. def _GetMustVerb(self):
  267. """Return 'must' if the hook is required; 'should' if not."""
  268. if self._abort_if_user_denies:
  269. return 'must'
  270. else:
  271. return 'should'
  272. def _CheckForHookApproval(self):
  273. """Check to see whether this hook has been approved.
  274. We'll look at the hash of all of the hooks. If this matches the hash that
  275. the user last approved, we're done. If it doesn't, we'll ask the user
  276. about approval.
  277. Note that we ask permission for each individual hook even though we use
  278. the hash of all hooks when detecting changes. We'd like the user to be
  279. able to approve / deny each hook individually. We only use the hash of all
  280. hooks because there is no other easy way to detect changes to local imports.
  281. Returns:
  282. True if this hook is approved to run; False otherwise.
  283. Raises:
  284. HookError: Raised if the user doesn't approve and abort_if_user_denies
  285. was passed to the consturctor.
  286. """
  287. hooks_config = self._hooks_project.config
  288. git_approval_key = 'repo.hooks.%s.approvedhash' % self._hook_type
  289. # Get the last hash that the user approved for this hook; may be None.
  290. old_hash = hooks_config.GetString(git_approval_key)
  291. # Get the current hash so we can tell if scripts changed since approval.
  292. new_hash = self._GetHash()
  293. if old_hash is not None:
  294. # User previously approved hook and asked not to be prompted again.
  295. if new_hash == old_hash:
  296. # Approval matched. We're done.
  297. return True
  298. else:
  299. # Give the user a reason why we're prompting, since they last told
  300. # us to "never ask again".
  301. prompt = 'WARNING: Scripts have changed since %s was allowed.\n\n' % (
  302. self._hook_type)
  303. else:
  304. prompt = ''
  305. # Prompt the user if we're not on a tty; on a tty we'll assume "no".
  306. if sys.stdout.isatty():
  307. prompt += ('Repo %s run the script:\n'
  308. ' %s\n'
  309. '\n'
  310. 'Do you want to allow this script to run '
  311. '(yes/yes-never-ask-again/NO)? ') % (
  312. self._GetMustVerb(), self._script_fullpath)
  313. response = input(prompt).lower()
  314. print()
  315. # User is doing a one-time approval.
  316. if response in ('y', 'yes'):
  317. return True
  318. elif response == 'yes-never-ask-again':
  319. hooks_config.SetString(git_approval_key, new_hash)
  320. return True
  321. # For anything else, we'll assume no approval.
  322. if self._abort_if_user_denies:
  323. raise HookError('You must allow the %s hook or use --no-verify.' %
  324. self._hook_type)
  325. return False
  326. def _ExecuteHook(self, **kwargs):
  327. """Actually execute the given hook.
  328. This will run the hook's 'main' function in our python interpreter.
  329. Args:
  330. kwargs: Keyword arguments to pass to the hook. These are often specific
  331. to the hook type. For instance, pre-upload hooks will contain
  332. a project_list.
  333. """
  334. # Keep sys.path and CWD stashed away so that we can always restore them
  335. # upon function exit.
  336. orig_path = os.getcwd()
  337. orig_syspath = sys.path
  338. try:
  339. # Always run hooks with CWD as topdir.
  340. os.chdir(self._topdir)
  341. # Put the hook dir as the first item of sys.path so hooks can do
  342. # relative imports. We want to replace the repo dir as [0] so
  343. # hooks can't import repo files.
  344. sys.path = [os.path.dirname(self._script_fullpath)] + sys.path[1:]
  345. # Exec, storing global context in the context dict. We catch exceptions
  346. # and convert to a HookError w/ just the failing traceback.
  347. context = {}
  348. try:
  349. execfile(self._script_fullpath, context)
  350. except Exception:
  351. raise HookError('%s\nFailed to import %s hook; see traceback above.' % (
  352. traceback.format_exc(), self._hook_type))
  353. # Running the script should have defined a main() function.
  354. if 'main' not in context:
  355. raise HookError('Missing main() in: "%s"' % self._script_fullpath)
  356. # Add 'hook_should_take_kwargs' to the arguments to be passed to main.
  357. # We don't actually want hooks to define their main with this argument--
  358. # it's there to remind them that their hook should always take **kwargs.
  359. # For instance, a pre-upload hook should be defined like:
  360. # def main(project_list, **kwargs):
  361. #
  362. # This allows us to later expand the API without breaking old hooks.
  363. kwargs = kwargs.copy()
  364. kwargs['hook_should_take_kwargs'] = True
  365. # Call the main function in the hook. If the hook should cause the
  366. # build to fail, it will raise an Exception. We'll catch that convert
  367. # to a HookError w/ just the failing traceback.
  368. try:
  369. context['main'](**kwargs)
  370. except Exception:
  371. raise HookError('%s\nFailed to run main() for %s hook; see traceback '
  372. 'above.' % (
  373. traceback.format_exc(), self._hook_type))
  374. finally:
  375. # Restore sys.path and CWD.
  376. sys.path = orig_syspath
  377. os.chdir(orig_path)
  378. def Run(self, user_allows_all_hooks, **kwargs):
  379. """Run the hook.
  380. If the hook doesn't exist (because there is no hooks project or because
  381. this particular hook is not enabled), this is a no-op.
  382. Args:
  383. user_allows_all_hooks: If True, we will never prompt about running the
  384. hook--we'll just assume it's OK to run it.
  385. kwargs: Keyword arguments to pass to the hook. These are often specific
  386. to the hook type. For instance, pre-upload hooks will contain
  387. a project_list.
  388. Raises:
  389. HookError: If there was a problem finding the hook or the user declined
  390. to run a required hook (from _CheckForHookApproval).
  391. """
  392. # No-op if there is no hooks project or if hook is disabled.
  393. if ((not self._hooks_project) or
  394. (self._hook_type not in self._hooks_project.enabled_repo_hooks)):
  395. return
  396. # Bail with a nice error if we can't find the hook.
  397. if not os.path.isfile(self._script_fullpath):
  398. raise HookError('Couldn\'t find repo hook: "%s"' % self._script_fullpath)
  399. # Make sure the user is OK with running the hook.
  400. if (not user_allows_all_hooks) and (not self._CheckForHookApproval()):
  401. return
  402. # Run the hook with the same version of python we're using.
  403. self._ExecuteHook(**kwargs)
  404. class Project(object):
  405. def __init__(self,
  406. manifest,
  407. name,
  408. remote,
  409. gitdir,
  410. worktree,
  411. relpath,
  412. revisionExpr,
  413. revisionId,
  414. rebase = True,
  415. groups = None,
  416. sync_c = False,
  417. sync_s = False,
  418. clone_depth = None,
  419. upstream = None,
  420. parent = None,
  421. is_derived = False):
  422. """Init a Project object.
  423. Args:
  424. manifest: The XmlManifest object.
  425. name: The `name` attribute of manifest.xml's project element.
  426. remote: RemoteSpec object specifying its remote's properties.
  427. gitdir: Absolute path of git directory.
  428. worktree: Absolute path of git working tree.
  429. relpath: Relative path of git working tree to repo's top directory.
  430. revisionExpr: The `revision` attribute of manifest.xml's project element.
  431. revisionId: git commit id for checking out.
  432. rebase: The `rebase` attribute of manifest.xml's project element.
  433. groups: The `groups` attribute of manifest.xml's project element.
  434. sync_c: The `sync-c` attribute of manifest.xml's project element.
  435. sync_s: The `sync-s` attribute of manifest.xml's project element.
  436. upstream: The `upstream` attribute of manifest.xml's project element.
  437. parent: The parent Project object.
  438. is_derived: False if the project was explicitly defined in the manifest;
  439. True if the project is a discovered submodule.
  440. """
  441. self.manifest = manifest
  442. self.name = name
  443. self.remote = remote
  444. self.gitdir = gitdir.replace('\\', '/')
  445. if worktree:
  446. self.worktree = worktree.replace('\\', '/')
  447. else:
  448. self.worktree = None
  449. self.relpath = relpath
  450. self.revisionExpr = revisionExpr
  451. if revisionId is None \
  452. and revisionExpr \
  453. and IsId(revisionExpr):
  454. self.revisionId = revisionExpr
  455. else:
  456. self.revisionId = revisionId
  457. self.rebase = rebase
  458. self.groups = groups
  459. self.sync_c = sync_c
  460. self.sync_s = sync_s
  461. self.clone_depth = clone_depth
  462. self.upstream = upstream
  463. self.parent = parent
  464. self.is_derived = is_derived
  465. self.subprojects = []
  466. self.snapshots = {}
  467. self.copyfiles = []
  468. self.annotations = []
  469. self.config = GitConfig.ForRepository(
  470. gitdir = self.gitdir,
  471. defaults = self.manifest.globalConfig)
  472. if self.worktree:
  473. self.work_git = self._GitGetByExec(self, bare=False)
  474. else:
  475. self.work_git = None
  476. self.bare_git = self._GitGetByExec(self, bare=True)
  477. self.bare_ref = GitRefs(gitdir)
  478. # This will be filled in if a project is later identified to be the
  479. # project containing repo hooks.
  480. self.enabled_repo_hooks = []
  481. @property
  482. def Derived(self):
  483. return self.is_derived
  484. @property
  485. def Exists(self):
  486. return os.path.isdir(self.gitdir)
  487. @property
  488. def CurrentBranch(self):
  489. """Obtain the name of the currently checked out branch.
  490. The branch name omits the 'refs/heads/' prefix.
  491. None is returned if the project is on a detached HEAD.
  492. """
  493. b = self.work_git.GetHead()
  494. if b.startswith(R_HEADS):
  495. return b[len(R_HEADS):]
  496. return None
  497. def IsRebaseInProgress(self):
  498. w = self.worktree
  499. g = os.path.join(w, '.git')
  500. return os.path.exists(os.path.join(g, 'rebase-apply')) \
  501. or os.path.exists(os.path.join(g, 'rebase-merge')) \
  502. or os.path.exists(os.path.join(w, '.dotest'))
  503. def IsDirty(self, consider_untracked=True):
  504. """Is the working directory modified in some way?
  505. """
  506. self.work_git.update_index('-q',
  507. '--unmerged',
  508. '--ignore-missing',
  509. '--refresh')
  510. if self.work_git.DiffZ('diff-index', '-M', '--cached', HEAD):
  511. return True
  512. if self.work_git.DiffZ('diff-files'):
  513. return True
  514. if consider_untracked and self.work_git.LsOthers():
  515. return True
  516. return False
  517. _userident_name = None
  518. _userident_email = None
  519. @property
  520. def UserName(self):
  521. """Obtain the user's personal name.
  522. """
  523. if self._userident_name is None:
  524. self._LoadUserIdentity()
  525. return self._userident_name
  526. @property
  527. def UserEmail(self):
  528. """Obtain the user's email address. This is very likely
  529. to be their Gerrit login.
  530. """
  531. if self._userident_email is None:
  532. self._LoadUserIdentity()
  533. return self._userident_email
  534. def _LoadUserIdentity(self):
  535. u = self.bare_git.var('GIT_COMMITTER_IDENT')
  536. m = re.compile("^(.*) <([^>]*)> ").match(u)
  537. if m:
  538. self._userident_name = m.group(1)
  539. self._userident_email = m.group(2)
  540. else:
  541. self._userident_name = ''
  542. self._userident_email = ''
  543. def GetRemote(self, name):
  544. """Get the configuration for a single remote.
  545. """
  546. return self.config.GetRemote(name)
  547. def GetBranch(self, name):
  548. """Get the configuration for a single branch.
  549. """
  550. return self.config.GetBranch(name)
  551. def GetBranches(self):
  552. """Get all existing local branches.
  553. """
  554. current = self.CurrentBranch
  555. all_refs = self._allrefs
  556. heads = {}
  557. for name, ref_id in all_refs.items():
  558. if name.startswith(R_HEADS):
  559. name = name[len(R_HEADS):]
  560. b = self.GetBranch(name)
  561. b.current = name == current
  562. b.published = None
  563. b.revision = ref_id
  564. heads[name] = b
  565. for name, ref_id in all_refs.items():
  566. if name.startswith(R_PUB):
  567. name = name[len(R_PUB):]
  568. b = heads.get(name)
  569. if b:
  570. b.published = ref_id
  571. return heads
  572. def MatchesGroups(self, manifest_groups):
  573. """Returns true if the manifest groups specified at init should cause
  574. this project to be synced.
  575. Prefixing a manifest group with "-" inverts the meaning of a group.
  576. All projects are implicitly labelled with "all".
  577. labels are resolved in order. In the example case of
  578. project_groups: "all,group1,group2"
  579. manifest_groups: "-group1,group2"
  580. the project will be matched.
  581. The special manifest group "default" will match any project that
  582. does not have the special project group "notdefault"
  583. """
  584. expanded_manifest_groups = manifest_groups or ['default']
  585. expanded_project_groups = ['all'] + (self.groups or [])
  586. if not 'notdefault' in expanded_project_groups:
  587. expanded_project_groups += ['default']
  588. matched = False
  589. for group in expanded_manifest_groups:
  590. if group.startswith('-') and group[1:] in expanded_project_groups:
  591. matched = False
  592. elif group in expanded_project_groups:
  593. matched = True
  594. return matched
  595. ## Status Display ##
  596. def HasChanges(self):
  597. """Returns true if there are uncommitted changes.
  598. """
  599. self.work_git.update_index('-q',
  600. '--unmerged',
  601. '--ignore-missing',
  602. '--refresh')
  603. if self.IsRebaseInProgress():
  604. return True
  605. if self.work_git.DiffZ('diff-index', '--cached', HEAD):
  606. return True
  607. if self.work_git.DiffZ('diff-files'):
  608. return True
  609. if self.work_git.LsOthers():
  610. return True
  611. return False
  612. def PrintWorkTreeStatus(self, output_redir=None):
  613. """Prints the status of the repository to stdout.
  614. Args:
  615. output: If specified, redirect the output to this object.
  616. """
  617. if not os.path.isdir(self.worktree):
  618. if output_redir == None:
  619. output_redir = sys.stdout
  620. print(file=output_redir)
  621. print('project %s/' % self.relpath, file=output_redir)
  622. print(' missing (run "repo sync")', file=output_redir)
  623. return
  624. self.work_git.update_index('-q',
  625. '--unmerged',
  626. '--ignore-missing',
  627. '--refresh')
  628. rb = self.IsRebaseInProgress()
  629. di = self.work_git.DiffZ('diff-index', '-M', '--cached', HEAD)
  630. df = self.work_git.DiffZ('diff-files')
  631. do = self.work_git.LsOthers()
  632. if not rb and not di and not df and not do and not self.CurrentBranch:
  633. return 'CLEAN'
  634. out = StatusColoring(self.config)
  635. if not output_redir == None:
  636. out.redirect(output_redir)
  637. out.project('project %-40s', self.relpath + '/')
  638. branch = self.CurrentBranch
  639. if branch is None:
  640. out.nobranch('(*** NO BRANCH ***)')
  641. else:
  642. out.branch('branch %s', branch)
  643. out.nl()
  644. if rb:
  645. out.important('prior sync failed; rebase still in progress')
  646. out.nl()
  647. paths = list()
  648. paths.extend(di.keys())
  649. paths.extend(df.keys())
  650. paths.extend(do)
  651. for p in sorted(set(paths)):
  652. try:
  653. i = di[p]
  654. except KeyError:
  655. i = None
  656. try:
  657. f = df[p]
  658. except KeyError:
  659. f = None
  660. if i:
  661. i_status = i.status.upper()
  662. else:
  663. i_status = '-'
  664. if f:
  665. f_status = f.status.lower()
  666. else:
  667. f_status = '-'
  668. if i and i.src_path:
  669. line = ' %s%s\t%s => %s (%s%%)' % (i_status, f_status,
  670. i.src_path, p, i.level)
  671. else:
  672. line = ' %s%s\t%s' % (i_status, f_status, p)
  673. if i and not f:
  674. out.added('%s', line)
  675. elif (i and f) or (not i and f):
  676. out.changed('%s', line)
  677. elif not i and not f:
  678. out.untracked('%s', line)
  679. else:
  680. out.write('%s', line)
  681. out.nl()
  682. return 'DIRTY'
  683. def PrintWorkTreeDiff(self, absolute_paths=False):
  684. """Prints the status of the repository to stdout.
  685. """
  686. out = DiffColoring(self.config)
  687. cmd = ['diff']
  688. if out.is_on:
  689. cmd.append('--color')
  690. cmd.append(HEAD)
  691. if absolute_paths:
  692. cmd.append('--src-prefix=a/%s/' % self.relpath)
  693. cmd.append('--dst-prefix=b/%s/' % self.relpath)
  694. cmd.append('--')
  695. p = GitCommand(self,
  696. cmd,
  697. capture_stdout = True,
  698. capture_stderr = True)
  699. has_diff = False
  700. for line in p.process.stdout:
  701. if not has_diff:
  702. out.nl()
  703. out.project('project %s/' % self.relpath)
  704. out.nl()
  705. has_diff = True
  706. print(line[:-1])
  707. p.Wait()
  708. ## Publish / Upload ##
  709. def WasPublished(self, branch, all_refs=None):
  710. """Was the branch published (uploaded) for code review?
  711. If so, returns the SHA-1 hash of the last published
  712. state for the branch.
  713. """
  714. key = R_PUB + branch
  715. if all_refs is None:
  716. try:
  717. return self.bare_git.rev_parse(key)
  718. except GitError:
  719. return None
  720. else:
  721. try:
  722. return all_refs[key]
  723. except KeyError:
  724. return None
  725. def CleanPublishedCache(self, all_refs=None):
  726. """Prunes any stale published refs.
  727. """
  728. if all_refs is None:
  729. all_refs = self._allrefs
  730. heads = set()
  731. canrm = {}
  732. for name, ref_id in all_refs.items():
  733. if name.startswith(R_HEADS):
  734. heads.add(name)
  735. elif name.startswith(R_PUB):
  736. canrm[name] = ref_id
  737. for name, ref_id in canrm.items():
  738. n = name[len(R_PUB):]
  739. if R_HEADS + n not in heads:
  740. self.bare_git.DeleteRef(name, ref_id)
  741. def GetUploadableBranches(self, selected_branch=None):
  742. """List any branches which can be uploaded for review.
  743. """
  744. heads = {}
  745. pubed = {}
  746. for name, ref_id in self._allrefs.items():
  747. if name.startswith(R_HEADS):
  748. heads[name[len(R_HEADS):]] = ref_id
  749. elif name.startswith(R_PUB):
  750. pubed[name[len(R_PUB):]] = ref_id
  751. ready = []
  752. for branch, ref_id in heads.items():
  753. if branch in pubed and pubed[branch] == ref_id:
  754. continue
  755. if selected_branch and branch != selected_branch:
  756. continue
  757. rb = self.GetUploadableBranch(branch)
  758. if rb:
  759. ready.append(rb)
  760. return ready
  761. def GetUploadableBranch(self, branch_name):
  762. """Get a single uploadable branch, or None.
  763. """
  764. branch = self.GetBranch(branch_name)
  765. base = branch.LocalMerge
  766. if branch.LocalMerge:
  767. rb = ReviewableBranch(self, branch, base)
  768. if rb.commits:
  769. return rb
  770. return None
  771. def UploadForReview(self, branch=None,
  772. people=([],[]),
  773. auto_topic=False,
  774. draft=False):
  775. """Uploads the named branch for code review.
  776. """
  777. if branch is None:
  778. branch = self.CurrentBranch
  779. if branch is None:
  780. raise GitError('not currently on a branch')
  781. branch = self.GetBranch(branch)
  782. if not branch.LocalMerge:
  783. raise GitError('branch %s does not track a remote' % branch.name)
  784. if not branch.remote.review:
  785. raise GitError('remote %s has no review url' % branch.remote.name)
  786. dest_branch = branch.merge
  787. if not dest_branch.startswith(R_HEADS):
  788. dest_branch = R_HEADS + dest_branch
  789. if not branch.remote.projectname:
  790. branch.remote.projectname = self.name
  791. branch.remote.Save()
  792. url = branch.remote.ReviewUrl(self.UserEmail)
  793. if url is None:
  794. raise UploadError('review not configured')
  795. cmd = ['push']
  796. if url.startswith('ssh://'):
  797. rp = ['gerrit receive-pack']
  798. for e in people[0]:
  799. rp.append('--reviewer=%s' % sq(e))
  800. for e in people[1]:
  801. rp.append('--cc=%s' % sq(e))
  802. cmd.append('--receive-pack=%s' % " ".join(rp))
  803. cmd.append(url)
  804. if dest_branch.startswith(R_HEADS):
  805. dest_branch = dest_branch[len(R_HEADS):]
  806. upload_type = 'for'
  807. if draft:
  808. upload_type = 'drafts'
  809. ref_spec = '%s:refs/%s/%s' % (R_HEADS + branch.name, upload_type,
  810. dest_branch)
  811. if auto_topic:
  812. ref_spec = ref_spec + '/' + branch.name
  813. if not url.startswith('ssh://'):
  814. rp = ['r=%s' % p for p in people[0]] + \
  815. ['cc=%s' % p for p in people[1]]
  816. if rp:
  817. ref_spec = ref_spec + '%' + ','.join(rp)
  818. cmd.append(ref_spec)
  819. if GitCommand(self, cmd, bare = True).Wait() != 0:
  820. raise UploadError('Upload failed')
  821. msg = "posted to %s for %s" % (branch.remote.review, dest_branch)
  822. self.bare_git.UpdateRef(R_PUB + branch.name,
  823. R_HEADS + branch.name,
  824. message = msg)
  825. ## Sync ##
  826. def Sync_NetworkHalf(self,
  827. quiet=False,
  828. is_new=None,
  829. current_branch_only=False,
  830. clone_bundle=True,
  831. no_tags=False):
  832. """Perform only the network IO portion of the sync process.
  833. Local working directory/branch state is not affected.
  834. """
  835. if is_new is None:
  836. is_new = not self.Exists
  837. if is_new:
  838. self._InitGitDir()
  839. else:
  840. self._UpdateHooks()
  841. self._InitRemote()
  842. if is_new:
  843. alt = os.path.join(self.gitdir, 'objects/info/alternates')
  844. try:
  845. fd = open(alt, 'rb')
  846. try:
  847. alt_dir = fd.readline().rstrip()
  848. finally:
  849. fd.close()
  850. except IOError:
  851. alt_dir = None
  852. else:
  853. alt_dir = None
  854. if clone_bundle \
  855. and alt_dir is None \
  856. and self._ApplyCloneBundle(initial=is_new, quiet=quiet):
  857. is_new = False
  858. if not current_branch_only:
  859. if self.sync_c:
  860. current_branch_only = True
  861. elif not self.manifest._loaded:
  862. # Manifest cannot check defaults until it syncs.
  863. current_branch_only = False
  864. elif self.manifest.default.sync_c:
  865. current_branch_only = True
  866. if not self._RemoteFetch(initial=is_new, quiet=quiet, alt_dir=alt_dir,
  867. current_branch_only=current_branch_only,
  868. no_tags=no_tags):
  869. return False
  870. if self.worktree:
  871. self._InitMRef()
  872. else:
  873. self._InitMirrorHead()
  874. try:
  875. os.remove(os.path.join(self.gitdir, 'FETCH_HEAD'))
  876. except OSError:
  877. pass
  878. return True
  879. def PostRepoUpgrade(self):
  880. self._InitHooks()
  881. def _CopyFiles(self):
  882. for copyfile in self.copyfiles:
  883. copyfile._Copy()
  884. def GetRevisionId(self, all_refs=None):
  885. if self.revisionId:
  886. return self.revisionId
  887. rem = self.GetRemote(self.remote.name)
  888. rev = rem.ToLocal(self.revisionExpr)
  889. if all_refs is not None and rev in all_refs:
  890. return all_refs[rev]
  891. try:
  892. return self.bare_git.rev_parse('--verify', '%s^0' % rev)
  893. except GitError:
  894. raise ManifestInvalidRevisionError(
  895. 'revision %s in %s not found' % (self.revisionExpr,
  896. self.name))
  897. def Sync_LocalHalf(self, syncbuf):
  898. """Perform only the local IO portion of the sync process.
  899. Network access is not required.
  900. """
  901. all_refs = self.bare_ref.all
  902. self.CleanPublishedCache(all_refs)
  903. revid = self.GetRevisionId(all_refs)
  904. def _doff():
  905. self._FastForward(revid)
  906. self._CopyFiles()
  907. self._InitWorkTree()
  908. head = self.work_git.GetHead()
  909. if head.startswith(R_HEADS):
  910. branch = head[len(R_HEADS):]
  911. try:
  912. head = all_refs[head]
  913. except KeyError:
  914. head = None
  915. else:
  916. branch = None
  917. if branch is None or syncbuf.detach_head:
  918. # Currently on a detached HEAD. The user is assumed to
  919. # not have any local modifications worth worrying about.
  920. #
  921. if self.IsRebaseInProgress():
  922. syncbuf.fail(self, _PriorSyncFailedError())
  923. return
  924. if head == revid:
  925. # No changes; don't do anything further.
  926. # Except if the head needs to be detached
  927. #
  928. if not syncbuf.detach_head:
  929. return
  930. else:
  931. lost = self._revlist(not_rev(revid), HEAD)
  932. if lost:
  933. syncbuf.info(self, "discarding %d commits", len(lost))
  934. try:
  935. self._Checkout(revid, quiet=True)
  936. except GitError as e:
  937. syncbuf.fail(self, e)
  938. return
  939. self._CopyFiles()
  940. return
  941. if head == revid:
  942. # No changes; don't do anything further.
  943. #
  944. return
  945. branch = self.GetBranch(branch)
  946. if not branch.LocalMerge:
  947. # The current branch has no tracking configuration.
  948. # Jump off it to a detached HEAD.
  949. #
  950. syncbuf.info(self,
  951. "leaving %s; does not track upstream",
  952. branch.name)
  953. try:
  954. self._Checkout(revid, quiet=True)
  955. except GitError as e:
  956. syncbuf.fail(self, e)
  957. return
  958. self._CopyFiles()
  959. return
  960. upstream_gain = self._revlist(not_rev(HEAD), revid)
  961. pub = self.WasPublished(branch.name, all_refs)
  962. if pub:
  963. not_merged = self._revlist(not_rev(revid), pub)
  964. if not_merged:
  965. if upstream_gain:
  966. # The user has published this branch and some of those
  967. # commits are not yet merged upstream. We do not want
  968. # to rewrite the published commits so we punt.
  969. #
  970. syncbuf.fail(self,
  971. "branch %s is published (but not merged) and is now %d commits behind"
  972. % (branch.name, len(upstream_gain)))
  973. return
  974. elif pub == head:
  975. # All published commits are merged, and thus we are a
  976. # strict subset. We can fast-forward safely.
  977. #
  978. syncbuf.later1(self, _doff)
  979. return
  980. # Examine the local commits not in the remote. Find the
  981. # last one attributed to this user, if any.
  982. #
  983. local_changes = self._revlist(not_rev(revid), HEAD, format='%H %ce')
  984. last_mine = None
  985. cnt_mine = 0
  986. for commit in local_changes:
  987. commit_id, committer_email = commit.split(' ', 1)
  988. if committer_email == self.UserEmail:
  989. last_mine = commit_id
  990. cnt_mine += 1
  991. if not upstream_gain and cnt_mine == len(local_changes):
  992. return
  993. if self.IsDirty(consider_untracked=False):
  994. syncbuf.fail(self, _DirtyError())
  995. return
  996. # If the upstream switched on us, warn the user.
  997. #
  998. if branch.merge != self.revisionExpr:
  999. if branch.merge and self.revisionExpr:
  1000. syncbuf.info(self,
  1001. 'manifest switched %s...%s',
  1002. branch.merge,
  1003. self.revisionExpr)
  1004. elif branch.merge:
  1005. syncbuf.info(self,
  1006. 'manifest no longer tracks %s',
  1007. branch.merge)
  1008. if cnt_mine < len(local_changes):
  1009. # Upstream rebased. Not everything in HEAD
  1010. # was created by this user.
  1011. #
  1012. syncbuf.info(self,
  1013. "discarding %d commits removed from upstream",
  1014. len(local_changes) - cnt_mine)
  1015. branch.remote = self.GetRemote(self.remote.name)
  1016. if not ID_RE.match(self.revisionExpr):
  1017. # in case of manifest sync the revisionExpr might be a SHA1
  1018. branch.merge = self.revisionExpr
  1019. branch.Save()
  1020. if cnt_mine > 0 and self.rebase:
  1021. def _dorebase():
  1022. self._Rebase(upstream = '%s^1' % last_mine, onto = revid)
  1023. self._CopyFiles()
  1024. syncbuf.later2(self, _dorebase)
  1025. elif local_changes:
  1026. try:
  1027. self._ResetHard(revid)
  1028. self._CopyFiles()
  1029. except GitError as e:
  1030. syncbuf.fail(self, e)
  1031. return
  1032. else:
  1033. syncbuf.later1(self, _doff)
  1034. def AddCopyFile(self, src, dest, absdest):
  1035. # dest should already be an absolute path, but src is project relative
  1036. # make src an absolute path
  1037. abssrc = os.path.join(self.worktree, src)
  1038. self.copyfiles.append(_CopyFile(src, dest, abssrc, absdest))
  1039. def AddAnnotation(self, name, value, keep):
  1040. self.annotations.append(_Annotation(name, value, keep))
  1041. def DownloadPatchSet(self, change_id, patch_id):
  1042. """Download a single patch set of a single change to FETCH_HEAD.
  1043. """
  1044. remote = self.GetRemote(self.remote.name)
  1045. cmd = ['fetch', remote.name]
  1046. cmd.append('refs/changes/%2.2d/%d/%d' \
  1047. % (change_id % 100, change_id, patch_id))
  1048. cmd.extend(list(map(str, remote.fetch)))
  1049. if GitCommand(self, cmd, bare=True).Wait() != 0:
  1050. return None
  1051. return DownloadedChange(self,
  1052. self.GetRevisionId(),
  1053. change_id,
  1054. patch_id,
  1055. self.bare_git.rev_parse('FETCH_HEAD'))
  1056. ## Branch Management ##
  1057. def StartBranch(self, name):
  1058. """Create a new branch off the manifest's revision.
  1059. """
  1060. head = self.work_git.GetHead()
  1061. if head == (R_HEADS + name):
  1062. return True
  1063. all_refs = self.bare_ref.all
  1064. if (R_HEADS + name) in all_refs:
  1065. return GitCommand(self,
  1066. ['checkout', name, '--'],
  1067. capture_stdout = True,
  1068. capture_stderr = True).Wait() == 0
  1069. branch = self.GetBranch(name)
  1070. branch.remote = self.GetRemote(self.remote.name)
  1071. branch.merge = self.revisionExpr
  1072. revid = self.GetRevisionId(all_refs)
  1073. if head.startswith(R_HEADS):
  1074. try:
  1075. head = all_refs[head]
  1076. except KeyError:
  1077. head = None
  1078. if revid and head and revid == head:
  1079. ref = os.path.join(self.gitdir, R_HEADS + name)
  1080. try:
  1081. os.makedirs(os.path.dirname(ref))
  1082. except OSError:
  1083. pass
  1084. _lwrite(ref, '%s\n' % revid)
  1085. _lwrite(os.path.join(self.worktree, '.git', HEAD),
  1086. 'ref: %s%s\n' % (R_HEADS, name))
  1087. branch.Save()
  1088. return True
  1089. if GitCommand(self,
  1090. ['checkout', '-b', branch.name, revid],
  1091. capture_stdout = True,
  1092. capture_stderr = True).Wait() == 0:
  1093. branch.Save()
  1094. return True
  1095. return False
  1096. def CheckoutBranch(self, name):
  1097. """Checkout a local topic branch.
  1098. Args:
  1099. name: The name of the branch to checkout.
  1100. Returns:
  1101. True if the checkout succeeded; False if it didn't; None if the branch
  1102. didn't exist.
  1103. """
  1104. rev = R_HEADS + name
  1105. head = self.work_git.GetHead()
  1106. if head == rev:
  1107. # Already on the branch
  1108. #
  1109. return True
  1110. all_refs = self.bare_ref.all
  1111. try:
  1112. revid = all_refs[rev]
  1113. except KeyError:
  1114. # Branch does not exist in this project
  1115. #
  1116. return None
  1117. if head.startswith(R_HEADS):
  1118. try:
  1119. head = all_refs[head]
  1120. except KeyError:
  1121. head = None
  1122. if head == revid:
  1123. # Same revision; just update HEAD to point to the new
  1124. # target branch, but otherwise take no other action.
  1125. #
  1126. _lwrite(os.path.join(self.worktree, '.git', HEAD),
  1127. 'ref: %s%s\n' % (R_HEADS, name))
  1128. return True
  1129. return GitCommand(self,
  1130. ['checkout', name, '--'],
  1131. capture_stdout = True,
  1132. capture_stderr = True).Wait() == 0
  1133. def AbandonBranch(self, name):
  1134. """Destroy a local topic branch.
  1135. Args:
  1136. name: The name of the branch to abandon.
  1137. Returns:
  1138. True if the abandon succeeded; False if it didn't; None if the branch
  1139. didn't exist.
  1140. """
  1141. rev = R_HEADS + name
  1142. all_refs = self.bare_ref.all
  1143. if rev not in all_refs:
  1144. # Doesn't exist
  1145. return None
  1146. head = self.work_git.GetHead()
  1147. if head == rev:
  1148. # We can't destroy the branch while we are sitting
  1149. # on it. Switch to a detached HEAD.
  1150. #
  1151. head = all_refs[head]
  1152. revid = self.GetRevisionId(all_refs)
  1153. if head == revid:
  1154. _lwrite(os.path.join(self.worktree, '.git', HEAD),
  1155. '%s\n' % revid)
  1156. else:
  1157. self._Checkout(revid, quiet=True)
  1158. return GitCommand(self,
  1159. ['branch', '-D', name],
  1160. capture_stdout = True,
  1161. capture_stderr = True).Wait() == 0
  1162. def PruneHeads(self):
  1163. """Prune any topic branches already merged into upstream.
  1164. """
  1165. cb = self.CurrentBranch
  1166. kill = []
  1167. left = self._allrefs
  1168. for name in left.keys():
  1169. if name.startswith(R_HEADS):
  1170. name = name[len(R_HEADS):]
  1171. if cb is None or name != cb:
  1172. kill.append(name)
  1173. rev = self.GetRevisionId(left)
  1174. if cb is not None \
  1175. and not self._revlist(HEAD + '...' + rev) \
  1176. and not self.IsDirty(consider_untracked = False):
  1177. self.work_git.DetachHead(HEAD)
  1178. kill.append(cb)
  1179. if kill:
  1180. old = self.bare_git.GetHead()
  1181. if old is None:
  1182. old = 'refs/heads/please_never_use_this_as_a_branch_name'
  1183. try:
  1184. self.bare_git.DetachHead(rev)
  1185. b = ['branch', '-d']
  1186. b.extend(kill)
  1187. b = GitCommand(self, b, bare=True,
  1188. capture_stdout=True,
  1189. capture_stderr=True)
  1190. b.Wait()
  1191. finally:
  1192. self.bare_git.SetHead(old)
  1193. left = self._allrefs
  1194. for branch in kill:
  1195. if (R_HEADS + branch) not in left:
  1196. self.CleanPublishedCache()
  1197. break
  1198. if cb and cb not in kill:
  1199. kill.append(cb)
  1200. kill.sort()
  1201. kept = []
  1202. for branch in kill:
  1203. if (R_HEADS + branch) in left:
  1204. branch = self.GetBranch(branch)
  1205. base = branch.LocalMerge
  1206. if not base:
  1207. base = rev
  1208. kept.append(ReviewableBranch(self, branch, base))
  1209. return kept
  1210. ## Submodule Management ##
  1211. def GetRegisteredSubprojects(self):
  1212. result = []
  1213. def rec(subprojects):
  1214. if not subprojects:
  1215. return
  1216. result.extend(subprojects)
  1217. for p in subprojects:
  1218. rec(p.subprojects)
  1219. rec(self.subprojects)
  1220. return result
  1221. def _GetSubmodules(self):
  1222. # Unfortunately we cannot call `git submodule status --recursive` here
  1223. # because the working tree might not exist yet, and it cannot be used
  1224. # without a working tree in its current implementation.
  1225. def get_submodules(gitdir, rev):
  1226. # Parse .gitmodules for submodule sub_paths and sub_urls
  1227. sub_paths, sub_urls = parse_gitmodules(gitdir, rev)
  1228. if not sub_paths:
  1229. return []
  1230. # Run `git ls-tree` to read SHAs of submodule object, which happen to be
  1231. # revision of submodule repository
  1232. sub_revs = git_ls_tree(gitdir, rev, sub_paths)
  1233. submodules = []
  1234. for sub_path, sub_url in zip(sub_paths, sub_urls):
  1235. try:
  1236. sub_rev = sub_revs[sub_path]
  1237. except KeyError:
  1238. # Ignore non-exist submodules
  1239. continue
  1240. submodules.append((sub_rev, sub_path, sub_url))
  1241. return submodules
  1242. re_path = re.compile(r'^submodule\.([^.]+)\.path=(.*)$')
  1243. re_url = re.compile(r'^submodule\.([^.]+)\.url=(.*)$')
  1244. def parse_gitmodules(gitdir, rev):
  1245. cmd = ['cat-file', 'blob', '%s:.gitmodules' % rev]
  1246. try:
  1247. p = GitCommand(None, cmd, capture_stdout = True, capture_stderr = True,
  1248. bare = True, gitdir = gitdir)
  1249. except GitError:
  1250. return [], []
  1251. if p.Wait() != 0:
  1252. return [], []
  1253. gitmodules_lines = []
  1254. fd, temp_gitmodules_path = tempfile.mkstemp()
  1255. try:
  1256. os.write(fd, p.stdout)
  1257. os.close(fd)
  1258. cmd = ['config', '--file', temp_gitmodules_path, '--list']
  1259. p = GitCommand(None, cmd, capture_stdout = True, capture_stderr = True,
  1260. bare = True, gitdir = gitdir)
  1261. if p.Wait() != 0:
  1262. return [], []
  1263. gitmodules_lines = p.stdout.split('\n')
  1264. except GitError:
  1265. return [], []
  1266. finally:
  1267. os.remove(temp_gitmodules_path)
  1268. names = set()
  1269. paths = {}
  1270. urls = {}
  1271. for line in gitmodules_lines:
  1272. if not line:
  1273. continue
  1274. m = re_path.match(line)
  1275. if m:
  1276. names.add(m.group(1))
  1277. paths[m.group(1)] = m.group(2)
  1278. continue
  1279. m = re_url.match(line)
  1280. if m:
  1281. names.add(m.group(1))
  1282. urls[m.group(1)] = m.group(2)
  1283. continue
  1284. names = sorted(names)
  1285. return ([paths.get(name, '') for name in names],
  1286. [urls.get(name, '') for name in names])
  1287. def git_ls_tree(gitdir, rev, paths):
  1288. cmd = ['ls-tree', rev, '--']
  1289. cmd.extend(paths)
  1290. try:
  1291. p = GitCommand(None, cmd, capture_stdout = True, capture_stderr = True,
  1292. bare = True, gitdir = gitdir)
  1293. except GitError:
  1294. return []
  1295. if p.Wait() != 0:
  1296. return []
  1297. objects = {}
  1298. for line in p.stdout.split('\n'):
  1299. if not line.strip():
  1300. continue
  1301. object_rev, object_path = line.split()[2:4]
  1302. objects[object_path] = object_rev
  1303. return objects
  1304. try:
  1305. rev = self.GetRevisionId()
  1306. except GitError:
  1307. return []
  1308. return get_submodules(self.gitdir, rev)
  1309. def GetDerivedSubprojects(self):
  1310. result = []
  1311. if not self.Exists:
  1312. # If git repo does not exist yet, querying its submodules will
  1313. # mess up its states; so return here.
  1314. return result
  1315. for rev, path, url in self._GetSubmodules():
  1316. name = self.manifest.GetSubprojectName(self, path)
  1317. project = self.manifest.projects.get(name)
  1318. if project:
  1319. result.extend(project.GetDerivedSubprojects())
  1320. continue
  1321. relpath, worktree, gitdir = self.manifest.GetSubprojectPaths(self, path)
  1322. remote = RemoteSpec(self.remote.name,
  1323. url = url,
  1324. review = self.remote.review)
  1325. subproject = Project(manifest = self.manifest,
  1326. name = name,
  1327. remote = remote,
  1328. gitdir = gitdir,
  1329. worktree = worktree,
  1330. relpath = relpath,
  1331. revisionExpr = self.revisionExpr,
  1332. revisionId = rev,
  1333. rebase = self.rebase,
  1334. groups = self.groups,
  1335. sync_c = self.sync_c,
  1336. sync_s = self.sync_s,
  1337. parent = self,
  1338. is_derived = True)
  1339. result.append(subproject)
  1340. result.extend(subproject.GetDerivedSubprojects())
  1341. return result
  1342. ## Direct Git Commands ##
  1343. def _RemoteFetch(self, name=None,
  1344. current_branch_only=False,
  1345. initial=False,
  1346. quiet=False,
  1347. alt_dir=None,
  1348. no_tags=False):
  1349. is_sha1 = False
  1350. tag_name = None
  1351. def CheckForSha1():
  1352. try:
  1353. # if revision (sha or tag) is not present then following function
  1354. # throws an error.
  1355. self.bare_git.rev_parse('--verify', '%s^0' % self.revisionExpr)
  1356. return True
  1357. except GitError:
  1358. # There is no such persistent revision. We have to fetch it.
  1359. return False
  1360. if current_branch_only:
  1361. if ID_RE.match(self.revisionExpr) is not None:
  1362. is_sha1 = True
  1363. elif self.revisionExpr.startswith(R_TAGS):
  1364. # this is a tag and its sha1 value should never change
  1365. tag_name = self.revisionExpr[len(R_TAGS):]
  1366. if is_sha1 or tag_name is not None:
  1367. if CheckForSha1():
  1368. return True
  1369. if is_sha1 and (not self.upstream or ID_RE.match(self.upstream)):
  1370. current_branch_only = False
  1371. if not name:
  1372. name = self.remote.name
  1373. ssh_proxy = False
  1374. remote = self.GetRemote(name)
  1375. if remote.PreConnectFetch():
  1376. ssh_proxy = True
  1377. if initial:
  1378. if alt_dir and 'objects' == os.path.basename(alt_dir):
  1379. ref_dir = os.path.dirname(alt_dir)
  1380. packed_refs = os.path.join(self.gitdir, 'packed-refs')
  1381. remote = self.GetRemote(name)
  1382. all_refs = self.bare_ref.all
  1383. ids = set(all_refs.values())
  1384. tmp = set()
  1385. for r, ref_id in GitRefs(ref_dir).all.items():
  1386. if r not in all_refs:
  1387. if r.startswith(R_TAGS) or remote.WritesTo(r):
  1388. all_refs[r] = ref_id
  1389. ids.add(ref_id)
  1390. continue
  1391. if ref_id in ids:
  1392. continue
  1393. r = 'refs/_alt/%s' % ref_id
  1394. all_refs[r] = ref_id
  1395. ids.add(ref_id)
  1396. tmp.add(r)
  1397. tmp_packed = ''
  1398. old_packed = ''
  1399. for r in sorted(all_refs):
  1400. line = '%s %s\n' % (all_refs[r], r)
  1401. tmp_packed += line
  1402. if r not in tmp:
  1403. old_packed += line
  1404. _lwrite(packed_refs, tmp_packed)
  1405. else:
  1406. alt_dir = None
  1407. cmd = ['fetch']
  1408. # The --depth option only affects the initial fetch; after that we'll do
  1409. # full fetches of changes.
  1410. if self.clone_depth:
  1411. depth = self.clone_depth
  1412. else:
  1413. depth = self.manifest.manifestProject.config.GetString('repo.depth')
  1414. if depth and initial:
  1415. cmd.append('--depth=%s' % depth)
  1416. if quiet:
  1417. cmd.append('--quiet')
  1418. if not self.worktree:
  1419. cmd.append('--update-head-ok')
  1420. cmd.append(name)
  1421. if not current_branch_only:
  1422. # Fetch whole repo
  1423. # If using depth then we should not get all the tags since they may
  1424. # be outside of the depth.
  1425. if no_tags or depth:
  1426. cmd.append('--no-tags')
  1427. else:
  1428. cmd.append('--tags')
  1429. cmd.append(str((u'+refs/heads/*:') + remote.ToLocal('refs/heads/*')))
  1430. elif tag_name is not None:
  1431. cmd.append('tag')
  1432. cmd.append(tag_name)
  1433. else:
  1434. branch = self.revisionExpr
  1435. if is_sha1:
  1436. branch = self.upstream
  1437. if branch.startswith(R_HEADS):
  1438. branch = branch[len(R_HEADS):]
  1439. cmd.append(str((u'+refs/heads/%s:' % branch) + remote.ToLocal('refs/heads/%s' % branch)))
  1440. ok = False
  1441. for _i in range(2):
  1442. ret = GitCommand(self, cmd, bare=True, ssh_proxy=ssh_proxy).Wait()
  1443. if ret == 0:
  1444. ok = True
  1445. break
  1446. elif current_branch_only and is_sha1 and ret == 128:
  1447. # Exit code 128 means "couldn't find the ref you asked for"; if we're in sha1
  1448. # mode, we just tried sync'ing from the upstream field; it doesn't exist, thus
  1449. # abort the optimization attempt and do a full sync.
  1450. break
  1451. time.sleep(random.randint(30, 45))
  1452. if initial:
  1453. if alt_dir:
  1454. if old_packed != '':
  1455. _lwrite(packed_refs, old_packed)
  1456. else:
  1457. os.remove(packed_refs)
  1458. self.bare_git.pack_refs('--all', '--prune')
  1459. if is_sha1 and current_branch_only and self.upstream:
  1460. # We just synced the upstream given branch; verify we
  1461. # got what we wanted, else trigger a second run of all
  1462. # refs.
  1463. if not CheckForSha1():
  1464. return self._RemoteFetch(name=name, current_branch_only=False,
  1465. initial=False, quiet=quiet, alt_dir=alt_dir)
  1466. return ok
  1467. def _ApplyCloneBundle(self, initial=False, quiet=False):
  1468. if initial and (self.manifest.manifestProject.config.GetString('repo.depth') or self.clone_depth):
  1469. return False
  1470. remote = self.GetRemote(self.remote.name)
  1471. bundle_url = remote.url + '/clone.bundle'
  1472. bundle_url = GitConfig.ForUser().UrlInsteadOf(bundle_url)
  1473. if GetSchemeFromUrl(bundle_url) in ('persistent-http', 'persistent-https'):
  1474. bundle_url = bundle_url[len('persistent-'):]
  1475. if GetSchemeFromUrl(bundle_url) not in ('http', 'https'):
  1476. return False
  1477. bundle_dst = os.path.join(self.gitdir, 'clone.bundle')
  1478. bundle_tmp = os.path.join(self.gitdir, 'clone.bundle.tmp')
  1479. exist_dst = os.path.exists(bundle_dst)
  1480. exist_tmp = os.path.exists(bundle_tmp)
  1481. if not initial and not exist_dst and not exist_tmp:
  1482. return False
  1483. if not exist_dst:
  1484. exist_dst = self._FetchBundle(bundle_url, bundle_tmp, bundle_dst, quiet)
  1485. if not exist_dst:
  1486. return False
  1487. cmd = ['fetch']
  1488. if quiet:
  1489. cmd.append('--quiet')
  1490. if not self.worktree:
  1491. cmd.append('--update-head-ok')
  1492. cmd.append(bundle_dst)
  1493. for f in remote.fetch:
  1494. cmd.append(str(f))
  1495. cmd.append('refs/tags/*:refs/tags/*')
  1496. ok = GitCommand(self, cmd, bare=True).Wait() == 0
  1497. if os.path.exists(bundle_dst):
  1498. os.remove(bundle_dst)
  1499. if os.path.exists(bundle_tmp):
  1500. os.remove(bundle_tmp)
  1501. return ok
  1502. def _FetchBundle(self, srcUrl, tmpPath, dstPath, quiet):
  1503. if os.path.exists(dstPath):
  1504. os.remove(dstPath)
  1505. cmd = ['curl', '--fail', '--output', tmpPath, '--netrc', '--location']
  1506. if quiet:
  1507. cmd += ['--silent']
  1508. if os.path.exists(tmpPath):
  1509. size = os.stat(tmpPath).st_size
  1510. if size >= 1024:
  1511. cmd += ['--continue-at', '%d' % (size,)]
  1512. else:
  1513. os.remove(tmpPath)
  1514. if 'http_proxy' in os.environ and 'darwin' == sys.platform:
  1515. cmd += ['--proxy', os.environ['http_proxy']]
  1516. cookiefile = GitConfig.ForUser().GetString('http.cookiefile')
  1517. if cookiefile:
  1518. cmd += ['--cookie', cookiefile]
  1519. cmd += [srcUrl]
  1520. if IsTrace():
  1521. Trace('%s', ' '.join(cmd))
  1522. try:
  1523. proc = subprocess.Popen(cmd)
  1524. except OSError:
  1525. return False
  1526. curlret = proc.wait()
  1527. if curlret == 22:
  1528. # From curl man page:
  1529. # 22: HTTP page not retrieved. The requested url was not found or
  1530. # returned another error with the HTTP error code being 400 or above.
  1531. # This return code only appears if -f, --fail is used.
  1532. if not quiet:
  1533. print("Server does not provide clone.bundle; ignoring.",
  1534. file=sys.stderr)
  1535. return False
  1536. if os.path.exists(tmpPath):
  1537. if curlret == 0 and os.stat(tmpPath).st_size > 16:
  1538. os.rename(tmpPath, dstPath)
  1539. return True
  1540. else:
  1541. os.remove(tmpPath)
  1542. return False
  1543. else:
  1544. return False
  1545. def _Checkout(self, rev, quiet=False):
  1546. cmd = ['checkout']
  1547. if quiet:
  1548. cmd.append('-q')
  1549. cmd.append(rev)
  1550. cmd.append('--')
  1551. if GitCommand(self, cmd).Wait() != 0:
  1552. if self._allrefs:
  1553. raise GitError('%s checkout %s ' % (self.name, rev))
  1554. def _CherryPick(self, rev, quiet=False):
  1555. cmd = ['cherry-pick']
  1556. cmd.append(rev)
  1557. cmd.append('--')
  1558. if GitCommand(self, cmd).Wait() != 0:
  1559. if self._allrefs:
  1560. raise GitError('%s cherry-pick %s ' % (self.name, rev))
  1561. def _Revert(self, rev, quiet=False):
  1562. cmd = ['revert']
  1563. cmd.append('--no-edit')
  1564. cmd.append(rev)
  1565. cmd.append('--')
  1566. if GitCommand(self, cmd).Wait() != 0:
  1567. if self._allrefs:
  1568. raise GitError('%s revert %s ' % (self.name, rev))
  1569. def _ResetHard(self, rev, quiet=True):
  1570. cmd = ['reset', '--hard']
  1571. if quiet:
  1572. cmd.append('-q')
  1573. cmd.append(rev)
  1574. if GitCommand(self, cmd).Wait() != 0:
  1575. raise GitError('%s reset --hard %s ' % (self.name, rev))
  1576. def _Rebase(self, upstream, onto = None):
  1577. cmd = ['rebase']
  1578. if onto is not None:
  1579. cmd.extend(['--onto', onto])
  1580. cmd.append(upstream)
  1581. if GitCommand(self, cmd).Wait() != 0:
  1582. raise GitError('%s rebase %s ' % (self.name, upstream))
  1583. def _FastForward(self, head, ffonly=False):
  1584. cmd = ['merge', head]
  1585. if ffonly:
  1586. cmd.append("--ff-only")
  1587. if GitCommand(self, cmd).Wait() != 0:
  1588. raise GitError('%s merge %s ' % (self.name, head))
  1589. def _InitGitDir(self, mirror_git=None):
  1590. if not os.path.exists(self.gitdir):
  1591. os.makedirs(self.gitdir)
  1592. self.bare_git.init()
  1593. mp = self.manifest.manifestProject
  1594. ref_dir = mp.config.GetString('repo.reference') or ''
  1595. if ref_dir or mirror_git:
  1596. if not mirror_git:
  1597. mirror_git = os.path.join(ref_dir, self.name + '.git')
  1598. repo_git = os.path.join(ref_dir, '.repo', 'projects',
  1599. self.relpath + '.git')
  1600. if os.path.exists(mirror_git):
  1601. ref_dir = mirror_git
  1602. elif os.path.exists(repo_git):
  1603. ref_dir = repo_git
  1604. else:
  1605. ref_dir = None
  1606. if ref_dir:
  1607. _lwrite(os.path.join(self.gitdir, 'objects/info/alternates'),
  1608. os.path.join(ref_dir, 'objects') + '\n')
  1609. self._UpdateHooks()
  1610. m = self.manifest.manifestProject.config
  1611. for key in ['user.name', 'user.email']:
  1612. if m.Has(key, include_defaults = False):
  1613. self.config.SetString(key, m.GetString(key))
  1614. if self.manifest.IsMirror:
  1615. self.config.SetString('core.bare', 'true')
  1616. else:
  1617. self.config.SetString('core.bare', None)
  1618. def _UpdateHooks(self):
  1619. if os.path.exists(self.gitdir):
  1620. # Always recreate hooks since they can have been changed
  1621. # since the latest update.
  1622. hooks = self._gitdir_path('hooks')
  1623. try:
  1624. to_rm = os.listdir(hooks)
  1625. except OSError:
  1626. to_rm = []
  1627. for old_hook in to_rm:
  1628. os.remove(os.path.join(hooks, old_hook))
  1629. self._InitHooks()
  1630. def _InitHooks(self):
  1631. hooks = self._gitdir_path('hooks')
  1632. if not os.path.exists(hooks):
  1633. os.makedirs(hooks)
  1634. for stock_hook in _ProjectHooks():
  1635. name = os.path.basename(stock_hook)
  1636. if name in ('commit-msg',) and not self.remote.review \
  1637. and not self is self.manifest.manifestProject:
  1638. # Don't install a Gerrit Code Review hook if this
  1639. # project does not appear to use it for reviews.
  1640. #
  1641. # Since the manifest project is one of those, but also
  1642. # managed through gerrit, it's excluded
  1643. continue
  1644. dst = os.path.join(hooks, name)
  1645. if os.path.islink(dst):
  1646. continue
  1647. if os.path.exists(dst):
  1648. if filecmp.cmp(stock_hook, dst, shallow=False):
  1649. os.remove(dst)
  1650. else:
  1651. _error("%s: Not replacing %s hook", self.relpath, name)
  1652. continue
  1653. try:
  1654. os.symlink(os.path.relpath(stock_hook, os.path.dirname(dst)), dst)
  1655. except OSError as e:
  1656. if e.errno == errno.EPERM:
  1657. raise GitError('filesystem must support symlinks')
  1658. else:
  1659. raise
  1660. def _InitRemote(self):
  1661. if self.remote.url:
  1662. remote = self.GetRemote(self.remote.name)
  1663. remote.url = self.remote.url
  1664. remote.review = self.remote.review
  1665. remote.projectname = self.name
  1666. if self.worktree:
  1667. remote.ResetFetch(mirror=False)
  1668. else:
  1669. remote.ResetFetch(mirror=True)
  1670. remote.Save()
  1671. def _InitMRef(self):
  1672. if self.manifest.branch:
  1673. self._InitAnyMRef(R_M + self.manifest.branch)
  1674. def _InitMirrorHead(self):
  1675. self._InitAnyMRef(HEAD)
  1676. def _InitAnyMRef(self, ref):
  1677. cur = self.bare_ref.symref(ref)
  1678. if self.revisionId:
  1679. if cur != '' or self.bare_ref.get(ref) != self.revisionId:
  1680. msg = 'manifest set to %s' % self.revisionId
  1681. dst = self.revisionId + '^0'
  1682. self.bare_git.UpdateRef(ref, dst, message = msg, detach = True)
  1683. else:
  1684. remote = self.GetRemote(self.remote.name)
  1685. dst = remote.ToLocal(self.revisionExpr)
  1686. if cur != dst:
  1687. msg = 'manifest set to %s' % self.revisionExpr
  1688. self.bare_git.symbolic_ref('-m', msg, ref, dst)
  1689. def _InitWorkTree(self):
  1690. dotgit = os.path.join(self.worktree, '.git')
  1691. if not os.path.exists(dotgit):
  1692. os.makedirs(dotgit)
  1693. for name in ['config',
  1694. 'description',
  1695. 'hooks',
  1696. 'info',
  1697. 'logs',
  1698. 'objects',
  1699. 'packed-refs',
  1700. 'refs',
  1701. 'rr-cache',
  1702. 'svn']:
  1703. try:
  1704. src = os.path.join(self.gitdir, name)
  1705. dst = os.path.join(dotgit, name)
  1706. if os.path.islink(dst) or not os.path.exists(dst):
  1707. os.symlink(os.path.relpath(src, os.path.dirname(dst)), dst)
  1708. else:
  1709. raise GitError('cannot overwrite a local work tree')
  1710. except OSError as e:
  1711. if e.errno == errno.EPERM:
  1712. raise GitError('filesystem must support symlinks')
  1713. else:
  1714. raise
  1715. _lwrite(os.path.join(dotgit, HEAD), '%s\n' % self.GetRevisionId())
  1716. cmd = ['read-tree', '--reset', '-u']
  1717. cmd.append('-v')
  1718. cmd.append(HEAD)
  1719. if GitCommand(self, cmd).Wait() != 0:
  1720. raise GitError("cannot initialize work tree")
  1721. rr_cache = os.path.join(self.gitdir, 'rr-cache')
  1722. if not os.path.exists(rr_cache):
  1723. os.makedirs(rr_cache)
  1724. self._CopyFiles()
  1725. def _gitdir_path(self, path):
  1726. return os.path.join(self.gitdir, path)
  1727. def _revlist(self, *args, **kw):
  1728. a = []
  1729. a.extend(args)
  1730. a.append('--')
  1731. return self.work_git.rev_list(*a, **kw)
  1732. @property
  1733. def _allrefs(self):
  1734. return self.bare_ref.all
  1735. class _GitGetByExec(object):
  1736. def __init__(self, project, bare):
  1737. self._project = project
  1738. self._bare = bare
  1739. def LsOthers(self):
  1740. p = GitCommand(self._project,
  1741. ['ls-files',
  1742. '-z',
  1743. '--others',
  1744. '--exclude-standard'],
  1745. bare = False,
  1746. capture_stdout = True,
  1747. capture_stderr = True)
  1748. if p.Wait() == 0:
  1749. out = p.stdout
  1750. if out:
  1751. return out[:-1].split('\0') # pylint: disable=W1401
  1752. # Backslash is not anomalous
  1753. return []
  1754. def DiffZ(self, name, *args):
  1755. cmd = [name]
  1756. cmd.append('-z')
  1757. cmd.extend(args)
  1758. p = GitCommand(self._project,
  1759. cmd,
  1760. bare = False,
  1761. capture_stdout = True,
  1762. capture_stderr = True)
  1763. try:
  1764. out = p.process.stdout.read()
  1765. r = {}
  1766. if out:
  1767. out = iter(out[:-1].split('\0')) # pylint: disable=W1401
  1768. while out:
  1769. try:
  1770. info = out.next()
  1771. path = out.next()
  1772. except StopIteration:
  1773. break
  1774. class _Info(object):
  1775. def __init__(self, path, omode, nmode, oid, nid, state):
  1776. self.path = path
  1777. self.src_path = None
  1778. self.old_mode = omode
  1779. self.new_mode = nmode
  1780. self.old_id = oid
  1781. self.new_id = nid
  1782. if len(state) == 1:
  1783. self.status = state
  1784. self.level = None
  1785. else:
  1786. self.status = state[:1]
  1787. self.level = state[1:]
  1788. while self.level.startswith('0'):
  1789. self.level = self.level[1:]
  1790. info = info[1:].split(' ')
  1791. info = _Info(path, *info)
  1792. if info.status in ('R', 'C'):
  1793. info.src_path = info.path
  1794. info.path = out.next()
  1795. r[info.path] = info
  1796. return r
  1797. finally:
  1798. p.Wait()
  1799. def GetHead(self):
  1800. if self._bare:
  1801. path = os.path.join(self._project.gitdir, HEAD)
  1802. else:
  1803. path = os.path.join(self._project.worktree, '.git', HEAD)
  1804. try:
  1805. fd = open(path, 'rb')
  1806. except IOError:
  1807. raise NoManifestException(path)
  1808. try:
  1809. line = fd.read()
  1810. finally:
  1811. fd.close()
  1812. try:
  1813. line = line.decode()
  1814. except AttributeError:
  1815. pass
  1816. if line.startswith('ref: '):
  1817. return line[5:-1]
  1818. return line[:-1]
  1819. def SetHead(self, ref, message=None):
  1820. cmdv = []
  1821. if message is not None:
  1822. cmdv.extend(['-m', message])
  1823. cmdv.append(HEAD)
  1824. cmdv.append(ref)
  1825. self.symbolic_ref(*cmdv)
  1826. def DetachHead(self, new, message=None):
  1827. cmdv = ['--no-deref']
  1828. if message is not None:
  1829. cmdv.extend(['-m', message])
  1830. cmdv.append(HEAD)
  1831. cmdv.append(new)
  1832. self.update_ref(*cmdv)
  1833. def UpdateRef(self, name, new, old=None,
  1834. message=None,
  1835. detach=False):
  1836. cmdv = []
  1837. if message is not None:
  1838. cmdv.extend(['-m', message])
  1839. if detach:
  1840. cmdv.append('--no-deref')
  1841. cmdv.append(name)
  1842. cmdv.append(new)
  1843. if old is not None:
  1844. cmdv.append(old)
  1845. self.update_ref(*cmdv)
  1846. def DeleteRef(self, name, old=None):
  1847. if not old:
  1848. old = self.rev_parse(name)
  1849. self.update_ref('-d', name, old)
  1850. self._project.bare_ref.deleted(name)
  1851. def rev_list(self, *args, **kw):
  1852. if 'format' in kw:
  1853. cmdv = ['log', '--pretty=format:%s' % kw['format']]
  1854. else:
  1855. cmdv = ['rev-list']
  1856. cmdv.extend(args)
  1857. p = GitCommand(self._project,
  1858. cmdv,
  1859. bare = self._bare,
  1860. capture_stdout = True,
  1861. capture_stderr = True)
  1862. r = []
  1863. for line in p.process.stdout:
  1864. if line[-1] == '\n':
  1865. line = line[:-1]
  1866. r.append(line)
  1867. if p.Wait() != 0:
  1868. raise GitError('%s rev-list %s: %s' % (
  1869. self._project.name,
  1870. str(args),
  1871. p.stderr))
  1872. return r
  1873. def __getattr__(self, name):
  1874. """Allow arbitrary git commands using pythonic syntax.
  1875. This allows you to do things like:
  1876. git_obj.rev_parse('HEAD')
  1877. Since we don't have a 'rev_parse' method defined, the __getattr__ will
  1878. run. We'll replace the '_' with a '-' and try to run a git command.
  1879. Any other positional arguments will be passed to the git command, and the
  1880. following keyword arguments are supported:
  1881. config: An optional dict of git config options to be passed with '-c'.
  1882. Args:
  1883. name: The name of the git command to call. Any '_' characters will
  1884. be replaced with '-'.
  1885. Returns:
  1886. A callable object that will try to call git with the named command.
  1887. """
  1888. name = name.replace('_', '-')
  1889. def runner(*args, **kwargs):
  1890. cmdv = []
  1891. config = kwargs.pop('config', None)
  1892. for k in kwargs:
  1893. raise TypeError('%s() got an unexpected keyword argument %r'
  1894. % (name, k))
  1895. if config is not None:
  1896. if not git_require((1, 7, 2)):
  1897. raise ValueError('cannot set config on command line for %s()'
  1898. % name)
  1899. for k, v in config.items():
  1900. cmdv.append('-c')
  1901. cmdv.append('%s=%s' % (k, v))
  1902. cmdv.append(name)
  1903. cmdv.extend(args)
  1904. p = GitCommand(self._project,
  1905. cmdv,
  1906. bare = self._bare,
  1907. capture_stdout = True,
  1908. capture_stderr = True)
  1909. if p.Wait() != 0:
  1910. raise GitError('%s %s: %s' % (
  1911. self._project.name,
  1912. name,
  1913. p.stderr))
  1914. r = p.stdout
  1915. try:
  1916. r = r.decode()
  1917. except AttributeError:
  1918. pass
  1919. if r.endswith('\n') and r.index('\n') == len(r) - 1:
  1920. return r[:-1]
  1921. return r
  1922. return runner
  1923. class _PriorSyncFailedError(Exception):
  1924. def __str__(self):
  1925. return 'prior sync failed; rebase still in progress'
  1926. class _DirtyError(Exception):
  1927. def __str__(self):
  1928. return 'contains uncommitted changes'
  1929. class _InfoMessage(object):
  1930. def __init__(self, project, text):
  1931. self.project = project
  1932. self.text = text
  1933. def Print(self, syncbuf):
  1934. syncbuf.out.info('%s/: %s', self.project.relpath, self.text)
  1935. syncbuf.out.nl()
  1936. class _Failure(object):
  1937. def __init__(self, project, why):
  1938. self.project = project
  1939. self.why = why
  1940. def Print(self, syncbuf):
  1941. syncbuf.out.fail('error: %s/: %s',
  1942. self.project.relpath,
  1943. str(self.why))
  1944. syncbuf.out.nl()
  1945. class _Later(object):
  1946. def __init__(self, project, action):
  1947. self.project = project
  1948. self.action = action
  1949. def Run(self, syncbuf):
  1950. out = syncbuf.out
  1951. out.project('project %s/', self.project.relpath)
  1952. out.nl()
  1953. try:
  1954. self.action()
  1955. out.nl()
  1956. return True
  1957. except GitError:
  1958. out.nl()
  1959. return False
  1960. class _SyncColoring(Coloring):
  1961. def __init__(self, config):
  1962. Coloring.__init__(self, config, 'reposync')
  1963. self.project = self.printer('header', attr = 'bold')
  1964. self.info = self.printer('info')
  1965. self.fail = self.printer('fail', fg='red')
  1966. class SyncBuffer(object):
  1967. def __init__(self, config, detach_head=False):
  1968. self._messages = []
  1969. self._failures = []
  1970. self._later_queue1 = []
  1971. self._later_queue2 = []
  1972. self.out = _SyncColoring(config)
  1973. self.out.redirect(sys.stderr)
  1974. self.detach_head = detach_head
  1975. self.clean = True
  1976. def info(self, project, fmt, *args):
  1977. self._messages.append(_InfoMessage(project, fmt % args))
  1978. def fail(self, project, err=None):
  1979. self._failures.append(_Failure(project, err))
  1980. self.clean = False
  1981. def later1(self, project, what):
  1982. self._later_queue1.append(_Later(project, what))
  1983. def later2(self, project, what):
  1984. self._later_queue2.append(_Later(project, what))
  1985. def Finish(self):
  1986. self._PrintMessages()
  1987. self._RunLater()
  1988. self._PrintMessages()
  1989. return self.clean
  1990. def _RunLater(self):
  1991. for q in ['_later_queue1', '_later_queue2']:
  1992. if not self._RunQueue(q):
  1993. return
  1994. def _RunQueue(self, queue):
  1995. for m in getattr(self, queue):
  1996. if not m.Run(self):
  1997. self.clean = False
  1998. return False
  1999. setattr(self, queue, [])
  2000. return True
  2001. def _PrintMessages(self):
  2002. for m in self._messages:
  2003. m.Print(self)
  2004. for m in self._failures:
  2005. m.Print(self)
  2006. self._messages = []
  2007. self._failures = []
  2008. class MetaProject(Project):
  2009. """A special project housed under .repo.
  2010. """
  2011. def __init__(self, manifest, name, gitdir, worktree):
  2012. Project.__init__(self,
  2013. manifest = manifest,
  2014. name = name,
  2015. gitdir = gitdir,
  2016. worktree = worktree,
  2017. remote = RemoteSpec('origin'),
  2018. relpath = '.repo/%s' % name,
  2019. revisionExpr = 'refs/heads/master',
  2020. revisionId = None,
  2021. groups = None)
  2022. def PreSync(self):
  2023. if self.Exists:
  2024. cb = self.CurrentBranch
  2025. if cb:
  2026. base = self.GetBranch(cb).merge
  2027. if base:
  2028. self.revisionExpr = base
  2029. self.revisionId = None
  2030. def MetaBranchSwitch(self, target):
  2031. """ Prepare MetaProject for manifest branch switch
  2032. """
  2033. # detach and delete manifest branch, allowing a new
  2034. # branch to take over
  2035. syncbuf = SyncBuffer(self.config, detach_head = True)
  2036. self.Sync_LocalHalf(syncbuf)
  2037. syncbuf.Finish()
  2038. return GitCommand(self,
  2039. ['update-ref', '-d', 'refs/heads/default'],
  2040. capture_stdout = True,
  2041. capture_stderr = True).Wait() == 0
  2042. @property
  2043. def LastFetch(self):
  2044. try:
  2045. fh = os.path.join(self.gitdir, 'FETCH_HEAD')
  2046. return os.path.getmtime(fh)
  2047. except OSError:
  2048. return 0
  2049. @property
  2050. def HasChanges(self):
  2051. """Has the remote received new commits not yet checked out?
  2052. """
  2053. if not self.remote or not self.revisionExpr:
  2054. return False
  2055. all_refs = self.bare_ref.all
  2056. revid = self.GetRevisionId(all_refs)
  2057. head = self.work_git.GetHead()
  2058. if head.startswith(R_HEADS):
  2059. try:
  2060. head = all_refs[head]
  2061. except KeyError:
  2062. head = None
  2063. if revid == head:
  2064. return False
  2065. elif self._revlist(not_rev(HEAD), revid):
  2066. return True
  2067. return False