project.py 70 KB

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