project.py 71 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392
  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. if not url.startswith('ssh://'):
  805. rp = ['r=%s' % p for p in people[0]] + \
  806. ['cc=%s' % p for p in people[1]]
  807. if rp:
  808. ref_spec = ref_spec + '%' + ','.join(rp)
  809. cmd.append(ref_spec)
  810. if GitCommand(self, cmd, bare = True).Wait() != 0:
  811. raise UploadError('Upload failed')
  812. msg = "posted to %s for %s" % (branch.remote.review, dest_branch)
  813. self.bare_git.UpdateRef(R_PUB + branch.name,
  814. R_HEADS + branch.name,
  815. message = msg)
  816. ## Sync ##
  817. def Sync_NetworkHalf(self,
  818. quiet=False,
  819. is_new=None,
  820. current_branch_only=False,
  821. clone_bundle=True,
  822. no_tags=False):
  823. """Perform only the network IO portion of the sync process.
  824. Local working directory/branch state is not affected.
  825. """
  826. if is_new is None:
  827. is_new = not self.Exists
  828. if is_new:
  829. self._InitGitDir()
  830. else:
  831. self._UpdateHooks()
  832. self._InitRemote()
  833. if is_new:
  834. alt = os.path.join(self.gitdir, 'objects/info/alternates')
  835. try:
  836. fd = open(alt, 'rb')
  837. try:
  838. alt_dir = fd.readline().rstrip()
  839. finally:
  840. fd.close()
  841. except IOError:
  842. alt_dir = None
  843. else:
  844. alt_dir = None
  845. if clone_bundle \
  846. and alt_dir is None \
  847. and self._ApplyCloneBundle(initial=is_new, quiet=quiet):
  848. is_new = False
  849. if not current_branch_only:
  850. if self.sync_c:
  851. current_branch_only = True
  852. elif not self.manifest._loaded:
  853. # Manifest cannot check defaults until it syncs.
  854. current_branch_only = False
  855. elif self.manifest.default.sync_c:
  856. current_branch_only = True
  857. if not self._RemoteFetch(initial=is_new, quiet=quiet, alt_dir=alt_dir,
  858. current_branch_only=current_branch_only,
  859. no_tags=no_tags):
  860. return False
  861. if self.worktree:
  862. self._InitMRef()
  863. else:
  864. self._InitMirrorHead()
  865. try:
  866. os.remove(os.path.join(self.gitdir, 'FETCH_HEAD'))
  867. except OSError:
  868. pass
  869. return True
  870. def PostRepoUpgrade(self):
  871. self._InitHooks()
  872. def _CopyFiles(self):
  873. for copyfile in self.copyfiles:
  874. copyfile._Copy()
  875. def GetRevisionId(self, all_refs=None):
  876. if self.revisionId:
  877. return self.revisionId
  878. rem = self.GetRemote(self.remote.name)
  879. rev = rem.ToLocal(self.revisionExpr)
  880. if all_refs is not None and rev in all_refs:
  881. return all_refs[rev]
  882. try:
  883. return self.bare_git.rev_parse('--verify', '%s^0' % rev)
  884. except GitError:
  885. raise ManifestInvalidRevisionError(
  886. 'revision %s in %s not found' % (self.revisionExpr,
  887. self.name))
  888. def Sync_LocalHalf(self, syncbuf):
  889. """Perform only the local IO portion of the sync process.
  890. Network access is not required.
  891. """
  892. all_refs = self.bare_ref.all
  893. self.CleanPublishedCache(all_refs)
  894. revid = self.GetRevisionId(all_refs)
  895. def _doff():
  896. self._FastForward(revid)
  897. self._CopyFiles()
  898. self._InitWorkTree()
  899. head = self.work_git.GetHead()
  900. if head.startswith(R_HEADS):
  901. branch = head[len(R_HEADS):]
  902. try:
  903. head = all_refs[head]
  904. except KeyError:
  905. head = None
  906. else:
  907. branch = None
  908. if branch is None or syncbuf.detach_head:
  909. # Currently on a detached HEAD. The user is assumed to
  910. # not have any local modifications worth worrying about.
  911. #
  912. if self.IsRebaseInProgress():
  913. syncbuf.fail(self, _PriorSyncFailedError())
  914. return
  915. if head == revid:
  916. # No changes; don't do anything further.
  917. # Except if the head needs to be detached
  918. #
  919. if not syncbuf.detach_head:
  920. return
  921. else:
  922. lost = self._revlist(not_rev(revid), HEAD)
  923. if lost:
  924. syncbuf.info(self, "discarding %d commits", len(lost))
  925. try:
  926. self._Checkout(revid, quiet=True)
  927. except GitError as e:
  928. syncbuf.fail(self, e)
  929. return
  930. self._CopyFiles()
  931. return
  932. if head == revid:
  933. # No changes; don't do anything further.
  934. #
  935. return
  936. branch = self.GetBranch(branch)
  937. if not branch.LocalMerge:
  938. # The current branch has no tracking configuration.
  939. # Jump off it to a detached HEAD.
  940. #
  941. syncbuf.info(self,
  942. "leaving %s; does not track upstream",
  943. branch.name)
  944. try:
  945. self._Checkout(revid, quiet=True)
  946. except GitError as e:
  947. syncbuf.fail(self, e)
  948. return
  949. self._CopyFiles()
  950. return
  951. upstream_gain = self._revlist(not_rev(HEAD), revid)
  952. pub = self.WasPublished(branch.name, all_refs)
  953. if pub:
  954. not_merged = self._revlist(not_rev(revid), pub)
  955. if not_merged:
  956. if upstream_gain:
  957. # The user has published this branch and some of those
  958. # commits are not yet merged upstream. We do not want
  959. # to rewrite the published commits so we punt.
  960. #
  961. syncbuf.fail(self,
  962. "branch %s is published (but not merged) and is now %d commits behind"
  963. % (branch.name, len(upstream_gain)))
  964. return
  965. elif pub == head:
  966. # All published commits are merged, and thus we are a
  967. # strict subset. We can fast-forward safely.
  968. #
  969. syncbuf.later1(self, _doff)
  970. return
  971. # Examine the local commits not in the remote. Find the
  972. # last one attributed to this user, if any.
  973. #
  974. local_changes = self._revlist(not_rev(revid), HEAD, format='%H %ce')
  975. last_mine = None
  976. cnt_mine = 0
  977. for commit in local_changes:
  978. commit_id, committer_email = commit.split(' ', 1)
  979. if committer_email == self.UserEmail:
  980. last_mine = commit_id
  981. cnt_mine += 1
  982. if not upstream_gain and cnt_mine == len(local_changes):
  983. return
  984. if self.IsDirty(consider_untracked=False):
  985. syncbuf.fail(self, _DirtyError())
  986. return
  987. # If the upstream switched on us, warn the user.
  988. #
  989. if branch.merge != self.revisionExpr:
  990. if branch.merge and self.revisionExpr:
  991. syncbuf.info(self,
  992. 'manifest switched %s...%s',
  993. branch.merge,
  994. self.revisionExpr)
  995. elif branch.merge:
  996. syncbuf.info(self,
  997. 'manifest no longer tracks %s',
  998. branch.merge)
  999. if cnt_mine < len(local_changes):
  1000. # Upstream rebased. Not everything in HEAD
  1001. # was created by this user.
  1002. #
  1003. syncbuf.info(self,
  1004. "discarding %d commits removed from upstream",
  1005. len(local_changes) - cnt_mine)
  1006. branch.remote = self.GetRemote(self.remote.name)
  1007. if not ID_RE.match(self.revisionExpr):
  1008. # in case of manifest sync the revisionExpr might be a SHA1
  1009. branch.merge = self.revisionExpr
  1010. branch.Save()
  1011. if cnt_mine > 0 and self.rebase:
  1012. def _dorebase():
  1013. self._Rebase(upstream = '%s^1' % last_mine, onto = revid)
  1014. self._CopyFiles()
  1015. syncbuf.later2(self, _dorebase)
  1016. elif local_changes:
  1017. try:
  1018. self._ResetHard(revid)
  1019. self._CopyFiles()
  1020. except GitError as e:
  1021. syncbuf.fail(self, e)
  1022. return
  1023. else:
  1024. syncbuf.later1(self, _doff)
  1025. def AddCopyFile(self, src, dest, absdest):
  1026. # dest should already be an absolute path, but src is project relative
  1027. # make src an absolute path
  1028. abssrc = os.path.join(self.worktree, src)
  1029. self.copyfiles.append(_CopyFile(src, dest, abssrc, absdest))
  1030. def AddAnnotation(self, name, value, keep):
  1031. self.annotations.append(_Annotation(name, value, keep))
  1032. def DownloadPatchSet(self, change_id, patch_id):
  1033. """Download a single patch set of a single change to FETCH_HEAD.
  1034. """
  1035. remote = self.GetRemote(self.remote.name)
  1036. cmd = ['fetch', remote.name]
  1037. cmd.append('refs/changes/%2.2d/%d/%d' \
  1038. % (change_id % 100, change_id, patch_id))
  1039. cmd.extend(map(str, remote.fetch))
  1040. if GitCommand(self, cmd, bare=True).Wait() != 0:
  1041. return None
  1042. return DownloadedChange(self,
  1043. self.GetRevisionId(),
  1044. change_id,
  1045. patch_id,
  1046. self.bare_git.rev_parse('FETCH_HEAD'))
  1047. ## Branch Management ##
  1048. def StartBranch(self, name):
  1049. """Create a new branch off the manifest's revision.
  1050. """
  1051. head = self.work_git.GetHead()
  1052. if head == (R_HEADS + name):
  1053. return True
  1054. all_refs = self.bare_ref.all
  1055. if (R_HEADS + name) in all_refs:
  1056. return GitCommand(self,
  1057. ['checkout', name, '--'],
  1058. capture_stdout = True,
  1059. capture_stderr = True).Wait() == 0
  1060. branch = self.GetBranch(name)
  1061. branch.remote = self.GetRemote(self.remote.name)
  1062. branch.merge = self.revisionExpr
  1063. revid = self.GetRevisionId(all_refs)
  1064. if head.startswith(R_HEADS):
  1065. try:
  1066. head = all_refs[head]
  1067. except KeyError:
  1068. head = None
  1069. if revid and head and revid == head:
  1070. ref = os.path.join(self.gitdir, R_HEADS + name)
  1071. try:
  1072. os.makedirs(os.path.dirname(ref))
  1073. except OSError:
  1074. pass
  1075. _lwrite(ref, '%s\n' % revid)
  1076. _lwrite(os.path.join(self.worktree, '.git', HEAD),
  1077. 'ref: %s%s\n' % (R_HEADS, name))
  1078. branch.Save()
  1079. return True
  1080. if GitCommand(self,
  1081. ['checkout', '-b', branch.name, revid],
  1082. capture_stdout = True,
  1083. capture_stderr = True).Wait() == 0:
  1084. branch.Save()
  1085. return True
  1086. return False
  1087. def CheckoutBranch(self, name):
  1088. """Checkout a local topic branch.
  1089. Args:
  1090. name: The name of the branch to checkout.
  1091. Returns:
  1092. True if the checkout succeeded; False if it didn't; None if the branch
  1093. didn't exist.
  1094. """
  1095. rev = R_HEADS + name
  1096. head = self.work_git.GetHead()
  1097. if head == rev:
  1098. # Already on the branch
  1099. #
  1100. return True
  1101. all_refs = self.bare_ref.all
  1102. try:
  1103. revid = all_refs[rev]
  1104. except KeyError:
  1105. # Branch does not exist in this project
  1106. #
  1107. return None
  1108. if head.startswith(R_HEADS):
  1109. try:
  1110. head = all_refs[head]
  1111. except KeyError:
  1112. head = None
  1113. if head == revid:
  1114. # Same revision; just update HEAD to point to the new
  1115. # target branch, but otherwise take no other action.
  1116. #
  1117. _lwrite(os.path.join(self.worktree, '.git', HEAD),
  1118. 'ref: %s%s\n' % (R_HEADS, name))
  1119. return True
  1120. return GitCommand(self,
  1121. ['checkout', name, '--'],
  1122. capture_stdout = True,
  1123. capture_stderr = True).Wait() == 0
  1124. def AbandonBranch(self, name):
  1125. """Destroy a local topic branch.
  1126. Args:
  1127. name: The name of the branch to abandon.
  1128. Returns:
  1129. True if the abandon succeeded; False if it didn't; None if the branch
  1130. didn't exist.
  1131. """
  1132. rev = R_HEADS + name
  1133. all_refs = self.bare_ref.all
  1134. if rev not in all_refs:
  1135. # Doesn't exist
  1136. return None
  1137. head = self.work_git.GetHead()
  1138. if head == rev:
  1139. # We can't destroy the branch while we are sitting
  1140. # on it. Switch to a detached HEAD.
  1141. #
  1142. head = all_refs[head]
  1143. revid = self.GetRevisionId(all_refs)
  1144. if head == revid:
  1145. _lwrite(os.path.join(self.worktree, '.git', HEAD),
  1146. '%s\n' % revid)
  1147. else:
  1148. self._Checkout(revid, quiet=True)
  1149. return GitCommand(self,
  1150. ['branch', '-D', name],
  1151. capture_stdout = True,
  1152. capture_stderr = True).Wait() == 0
  1153. def PruneHeads(self):
  1154. """Prune any topic branches already merged into upstream.
  1155. """
  1156. cb = self.CurrentBranch
  1157. kill = []
  1158. left = self._allrefs
  1159. for name in left.keys():
  1160. if name.startswith(R_HEADS):
  1161. name = name[len(R_HEADS):]
  1162. if cb is None or name != cb:
  1163. kill.append(name)
  1164. rev = self.GetRevisionId(left)
  1165. if cb is not None \
  1166. and not self._revlist(HEAD + '...' + rev) \
  1167. and not self.IsDirty(consider_untracked = False):
  1168. self.work_git.DetachHead(HEAD)
  1169. kill.append(cb)
  1170. if kill:
  1171. old = self.bare_git.GetHead()
  1172. if old is None:
  1173. old = 'refs/heads/please_never_use_this_as_a_branch_name'
  1174. try:
  1175. self.bare_git.DetachHead(rev)
  1176. b = ['branch', '-d']
  1177. b.extend(kill)
  1178. b = GitCommand(self, b, bare=True,
  1179. capture_stdout=True,
  1180. capture_stderr=True)
  1181. b.Wait()
  1182. finally:
  1183. self.bare_git.SetHead(old)
  1184. left = self._allrefs
  1185. for branch in kill:
  1186. if (R_HEADS + branch) not in left:
  1187. self.CleanPublishedCache()
  1188. break
  1189. if cb and cb not in kill:
  1190. kill.append(cb)
  1191. kill.sort()
  1192. kept = []
  1193. for branch in kill:
  1194. if (R_HEADS + branch) in left:
  1195. branch = self.GetBranch(branch)
  1196. base = branch.LocalMerge
  1197. if not base:
  1198. base = rev
  1199. kept.append(ReviewableBranch(self, branch, base))
  1200. return kept
  1201. ## Submodule Management ##
  1202. def GetRegisteredSubprojects(self):
  1203. result = []
  1204. def rec(subprojects):
  1205. if not subprojects:
  1206. return
  1207. result.extend(subprojects)
  1208. for p in subprojects:
  1209. rec(p.subprojects)
  1210. rec(self.subprojects)
  1211. return result
  1212. def _GetSubmodules(self):
  1213. # Unfortunately we cannot call `git submodule status --recursive` here
  1214. # because the working tree might not exist yet, and it cannot be used
  1215. # without a working tree in its current implementation.
  1216. def get_submodules(gitdir, rev):
  1217. # Parse .gitmodules for submodule sub_paths and sub_urls
  1218. sub_paths, sub_urls = parse_gitmodules(gitdir, rev)
  1219. if not sub_paths:
  1220. return []
  1221. # Run `git ls-tree` to read SHAs of submodule object, which happen to be
  1222. # revision of submodule repository
  1223. sub_revs = git_ls_tree(gitdir, rev, sub_paths)
  1224. submodules = []
  1225. for sub_path, sub_url in zip(sub_paths, sub_urls):
  1226. try:
  1227. sub_rev = sub_revs[sub_path]
  1228. except KeyError:
  1229. # Ignore non-exist submodules
  1230. continue
  1231. submodules.append((sub_rev, sub_path, sub_url))
  1232. return submodules
  1233. re_path = re.compile(r'^submodule\.([^.]+)\.path=(.*)$')
  1234. re_url = re.compile(r'^submodule\.([^.]+)\.url=(.*)$')
  1235. def parse_gitmodules(gitdir, rev):
  1236. cmd = ['cat-file', 'blob', '%s:.gitmodules' % rev]
  1237. try:
  1238. p = GitCommand(None, cmd, capture_stdout = True, capture_stderr = True,
  1239. bare = True, gitdir = gitdir)
  1240. except GitError:
  1241. return [], []
  1242. if p.Wait() != 0:
  1243. return [], []
  1244. gitmodules_lines = []
  1245. fd, temp_gitmodules_path = tempfile.mkstemp()
  1246. try:
  1247. os.write(fd, p.stdout)
  1248. os.close(fd)
  1249. cmd = ['config', '--file', temp_gitmodules_path, '--list']
  1250. p = GitCommand(None, cmd, capture_stdout = True, capture_stderr = True,
  1251. bare = True, gitdir = gitdir)
  1252. if p.Wait() != 0:
  1253. return [], []
  1254. gitmodules_lines = p.stdout.split('\n')
  1255. except GitError:
  1256. return [], []
  1257. finally:
  1258. os.remove(temp_gitmodules_path)
  1259. names = set()
  1260. paths = {}
  1261. urls = {}
  1262. for line in gitmodules_lines:
  1263. if not line:
  1264. continue
  1265. m = re_path.match(line)
  1266. if m:
  1267. names.add(m.group(1))
  1268. paths[m.group(1)] = m.group(2)
  1269. continue
  1270. m = re_url.match(line)
  1271. if m:
  1272. names.add(m.group(1))
  1273. urls[m.group(1)] = m.group(2)
  1274. continue
  1275. names = sorted(names)
  1276. return ([paths.get(name, '') for name in names],
  1277. [urls.get(name, '') for name in names])
  1278. def git_ls_tree(gitdir, rev, paths):
  1279. cmd = ['ls-tree', rev, '--']
  1280. cmd.extend(paths)
  1281. try:
  1282. p = GitCommand(None, cmd, capture_stdout = True, capture_stderr = True,
  1283. bare = True, gitdir = gitdir)
  1284. except GitError:
  1285. return []
  1286. if p.Wait() != 0:
  1287. return []
  1288. objects = {}
  1289. for line in p.stdout.split('\n'):
  1290. if not line.strip():
  1291. continue
  1292. object_rev, object_path = line.split()[2:4]
  1293. objects[object_path] = object_rev
  1294. return objects
  1295. try:
  1296. rev = self.GetRevisionId()
  1297. except GitError:
  1298. return []
  1299. return get_submodules(self.gitdir, rev)
  1300. def GetDerivedSubprojects(self):
  1301. result = []
  1302. if not self.Exists:
  1303. # If git repo does not exist yet, querying its submodules will
  1304. # mess up its states; so return here.
  1305. return result
  1306. for rev, path, url in self._GetSubmodules():
  1307. name = self.manifest.GetSubprojectName(self, path)
  1308. project = self.manifest.projects.get(name)
  1309. if project:
  1310. result.extend(project.GetDerivedSubprojects())
  1311. continue
  1312. relpath, worktree, gitdir = self.manifest.GetSubprojectPaths(self, path)
  1313. remote = RemoteSpec(self.remote.name,
  1314. url = url,
  1315. review = self.remote.review)
  1316. subproject = Project(manifest = self.manifest,
  1317. name = name,
  1318. remote = remote,
  1319. gitdir = gitdir,
  1320. worktree = worktree,
  1321. relpath = relpath,
  1322. revisionExpr = self.revisionExpr,
  1323. revisionId = rev,
  1324. rebase = self.rebase,
  1325. groups = self.groups,
  1326. sync_c = self.sync_c,
  1327. sync_s = self.sync_s,
  1328. parent = self,
  1329. is_derived = True)
  1330. result.append(subproject)
  1331. result.extend(subproject.GetDerivedSubprojects())
  1332. return result
  1333. ## Direct Git Commands ##
  1334. def _RemoteFetch(self, name=None,
  1335. current_branch_only=False,
  1336. initial=False,
  1337. quiet=False,
  1338. alt_dir=None,
  1339. no_tags=False):
  1340. is_sha1 = False
  1341. tag_name = None
  1342. def CheckForSha1():
  1343. try:
  1344. # if revision (sha or tag) is not present then following function
  1345. # throws an error.
  1346. self.bare_git.rev_parse('--verify', '%s^0' % self.revisionExpr)
  1347. return True
  1348. except GitError:
  1349. # There is no such persistent revision. We have to fetch it.
  1350. return False
  1351. if current_branch_only:
  1352. if ID_RE.match(self.revisionExpr) is not None:
  1353. is_sha1 = True
  1354. elif self.revisionExpr.startswith(R_TAGS):
  1355. # this is a tag and its sha1 value should never change
  1356. tag_name = self.revisionExpr[len(R_TAGS):]
  1357. if is_sha1 or tag_name is not None:
  1358. if CheckForSha1():
  1359. return True
  1360. if is_sha1 and (not self.upstream or ID_RE.match(self.upstream)):
  1361. current_branch_only = False
  1362. if not name:
  1363. name = self.remote.name
  1364. ssh_proxy = False
  1365. remote = self.GetRemote(name)
  1366. if remote.PreConnectFetch():
  1367. ssh_proxy = True
  1368. if initial:
  1369. if alt_dir and 'objects' == os.path.basename(alt_dir):
  1370. ref_dir = os.path.dirname(alt_dir)
  1371. packed_refs = os.path.join(self.gitdir, 'packed-refs')
  1372. remote = self.GetRemote(name)
  1373. all_refs = self.bare_ref.all
  1374. ids = set(all_refs.values())
  1375. tmp = set()
  1376. for r, ref_id in GitRefs(ref_dir).all.iteritems():
  1377. if r not in all_refs:
  1378. if r.startswith(R_TAGS) or remote.WritesTo(r):
  1379. all_refs[r] = ref_id
  1380. ids.add(ref_id)
  1381. continue
  1382. if ref_id in ids:
  1383. continue
  1384. r = 'refs/_alt/%s' % ref_id
  1385. all_refs[r] = ref_id
  1386. ids.add(ref_id)
  1387. tmp.add(r)
  1388. ref_names = list(all_refs.keys())
  1389. ref_names.sort()
  1390. tmp_packed = ''
  1391. old_packed = ''
  1392. for r in ref_names:
  1393. line = '%s %s\n' % (all_refs[r], r)
  1394. tmp_packed += line
  1395. if r not in tmp:
  1396. old_packed += line
  1397. _lwrite(packed_refs, tmp_packed)
  1398. else:
  1399. alt_dir = None
  1400. cmd = ['fetch']
  1401. # The --depth option only affects the initial fetch; after that we'll do
  1402. # full fetches of changes.
  1403. depth = self.manifest.manifestProject.config.GetString('repo.depth')
  1404. if depth and initial:
  1405. cmd.append('--depth=%s' % depth)
  1406. if quiet:
  1407. cmd.append('--quiet')
  1408. if not self.worktree:
  1409. cmd.append('--update-head-ok')
  1410. cmd.append(name)
  1411. if not current_branch_only:
  1412. # Fetch whole repo
  1413. if no_tags:
  1414. cmd.append('--no-tags')
  1415. else:
  1416. cmd.append('--tags')
  1417. cmd.append((u'+refs/heads/*:') + remote.ToLocal('refs/heads/*'))
  1418. elif tag_name is not None:
  1419. cmd.append('tag')
  1420. cmd.append(tag_name)
  1421. else:
  1422. branch = self.revisionExpr
  1423. if is_sha1:
  1424. branch = self.upstream
  1425. if branch.startswith(R_HEADS):
  1426. branch = branch[len(R_HEADS):]
  1427. cmd.append((u'+refs/heads/%s:' % branch) + remote.ToLocal('refs/heads/%s' % branch))
  1428. ok = False
  1429. for _i in range(2):
  1430. ret = GitCommand(self, cmd, bare=True, ssh_proxy=ssh_proxy).Wait()
  1431. if ret == 0:
  1432. ok = True
  1433. break
  1434. elif current_branch_only and is_sha1 and ret == 128:
  1435. # Exit code 128 means "couldn't find the ref you asked for"; if we're in sha1
  1436. # mode, we just tried sync'ing from the upstream field; it doesn't exist, thus
  1437. # abort the optimization attempt and do a full sync.
  1438. break
  1439. time.sleep(random.randint(30, 45))
  1440. if initial:
  1441. if alt_dir:
  1442. if old_packed != '':
  1443. _lwrite(packed_refs, old_packed)
  1444. else:
  1445. os.remove(packed_refs)
  1446. self.bare_git.pack_refs('--all', '--prune')
  1447. if is_sha1 and current_branch_only and self.upstream:
  1448. # We just synced the upstream given branch; verify we
  1449. # got what we wanted, else trigger a second run of all
  1450. # refs.
  1451. if not CheckForSha1():
  1452. return self._RemoteFetch(name=name, current_branch_only=False,
  1453. initial=False, quiet=quiet, alt_dir=alt_dir)
  1454. return ok
  1455. def _ApplyCloneBundle(self, initial=False, quiet=False):
  1456. if initial and self.manifest.manifestProject.config.GetString('repo.depth'):
  1457. return False
  1458. remote = self.GetRemote(self.remote.name)
  1459. bundle_url = remote.url + '/clone.bundle'
  1460. bundle_url = GitConfig.ForUser().UrlInsteadOf(bundle_url)
  1461. if GetSchemeFromUrl(bundle_url) in ('persistent-http', 'persistent-https'):
  1462. bundle_url = bundle_url[len('persistent-'):]
  1463. if GetSchemeFromUrl(bundle_url) not in ('http', 'https'):
  1464. return False
  1465. bundle_dst = os.path.join(self.gitdir, 'clone.bundle')
  1466. bundle_tmp = os.path.join(self.gitdir, 'clone.bundle.tmp')
  1467. exist_dst = os.path.exists(bundle_dst)
  1468. exist_tmp = os.path.exists(bundle_tmp)
  1469. if not initial and not exist_dst and not exist_tmp:
  1470. return False
  1471. if not exist_dst:
  1472. exist_dst = self._FetchBundle(bundle_url, bundle_tmp, bundle_dst, quiet)
  1473. if not exist_dst:
  1474. return False
  1475. cmd = ['fetch']
  1476. if quiet:
  1477. cmd.append('--quiet')
  1478. if not self.worktree:
  1479. cmd.append('--update-head-ok')
  1480. cmd.append(bundle_dst)
  1481. for f in remote.fetch:
  1482. cmd.append(str(f))
  1483. cmd.append('refs/tags/*:refs/tags/*')
  1484. ok = GitCommand(self, cmd, bare=True).Wait() == 0
  1485. if os.path.exists(bundle_dst):
  1486. os.remove(bundle_dst)
  1487. if os.path.exists(bundle_tmp):
  1488. os.remove(bundle_tmp)
  1489. return ok
  1490. def _FetchBundle(self, srcUrl, tmpPath, dstPath, quiet):
  1491. if os.path.exists(dstPath):
  1492. os.remove(dstPath)
  1493. cmd = ['curl', '--fail', '--output', tmpPath, '--netrc', '--location']
  1494. if quiet:
  1495. cmd += ['--silent']
  1496. if os.path.exists(tmpPath):
  1497. size = os.stat(tmpPath).st_size
  1498. if size >= 1024:
  1499. cmd += ['--continue-at', '%d' % (size,)]
  1500. else:
  1501. os.remove(tmpPath)
  1502. if 'http_proxy' in os.environ and 'darwin' == sys.platform:
  1503. cmd += ['--proxy', os.environ['http_proxy']]
  1504. cookiefile = GitConfig.ForUser().GetString('http.cookiefile')
  1505. if cookiefile:
  1506. cmd += ['--cookie', cookiefile]
  1507. cmd += [srcUrl]
  1508. if IsTrace():
  1509. Trace('%s', ' '.join(cmd))
  1510. try:
  1511. proc = subprocess.Popen(cmd)
  1512. except OSError:
  1513. return False
  1514. curlret = proc.wait()
  1515. if curlret == 22:
  1516. # From curl man page:
  1517. # 22: HTTP page not retrieved. The requested url was not found or
  1518. # returned another error with the HTTP error code being 400 or above.
  1519. # This return code only appears if -f, --fail is used.
  1520. if not quiet:
  1521. print("Server does not provide clone.bundle; ignoring.",
  1522. file=sys.stderr)
  1523. return False
  1524. if os.path.exists(tmpPath):
  1525. if curlret == 0 and os.stat(tmpPath).st_size > 16:
  1526. os.rename(tmpPath, dstPath)
  1527. return True
  1528. else:
  1529. os.remove(tmpPath)
  1530. return False
  1531. else:
  1532. return False
  1533. def _Checkout(self, rev, quiet=False):
  1534. cmd = ['checkout']
  1535. if quiet:
  1536. cmd.append('-q')
  1537. cmd.append(rev)
  1538. cmd.append('--')
  1539. if GitCommand(self, cmd).Wait() != 0:
  1540. if self._allrefs:
  1541. raise GitError('%s checkout %s ' % (self.name, rev))
  1542. def _CherryPick(self, rev, quiet=False):
  1543. cmd = ['cherry-pick']
  1544. cmd.append(rev)
  1545. cmd.append('--')
  1546. if GitCommand(self, cmd).Wait() != 0:
  1547. if self._allrefs:
  1548. raise GitError('%s cherry-pick %s ' % (self.name, rev))
  1549. def _Revert(self, rev, quiet=False):
  1550. cmd = ['revert']
  1551. cmd.append('--no-edit')
  1552. cmd.append(rev)
  1553. cmd.append('--')
  1554. if GitCommand(self, cmd).Wait() != 0:
  1555. if self._allrefs:
  1556. raise GitError('%s revert %s ' % (self.name, rev))
  1557. def _ResetHard(self, rev, quiet=True):
  1558. cmd = ['reset', '--hard']
  1559. if quiet:
  1560. cmd.append('-q')
  1561. cmd.append(rev)
  1562. if GitCommand(self, cmd).Wait() != 0:
  1563. raise GitError('%s reset --hard %s ' % (self.name, rev))
  1564. def _Rebase(self, upstream, onto = None):
  1565. cmd = ['rebase']
  1566. if onto is not None:
  1567. cmd.extend(['--onto', onto])
  1568. cmd.append(upstream)
  1569. if GitCommand(self, cmd).Wait() != 0:
  1570. raise GitError('%s rebase %s ' % (self.name, upstream))
  1571. def _FastForward(self, head, ffonly=False):
  1572. cmd = ['merge', head]
  1573. if ffonly:
  1574. cmd.append("--ff-only")
  1575. if GitCommand(self, cmd).Wait() != 0:
  1576. raise GitError('%s merge %s ' % (self.name, head))
  1577. def _InitGitDir(self):
  1578. if not os.path.exists(self.gitdir):
  1579. os.makedirs(self.gitdir)
  1580. self.bare_git.init()
  1581. mp = self.manifest.manifestProject
  1582. ref_dir = mp.config.GetString('repo.reference')
  1583. if ref_dir:
  1584. mirror_git = os.path.join(ref_dir, self.name + '.git')
  1585. repo_git = os.path.join(ref_dir, '.repo', 'projects',
  1586. self.relpath + '.git')
  1587. if os.path.exists(mirror_git):
  1588. ref_dir = mirror_git
  1589. elif os.path.exists(repo_git):
  1590. ref_dir = repo_git
  1591. else:
  1592. ref_dir = None
  1593. if ref_dir:
  1594. _lwrite(os.path.join(self.gitdir, 'objects/info/alternates'),
  1595. os.path.join(ref_dir, 'objects') + '\n')
  1596. self._UpdateHooks()
  1597. m = self.manifest.manifestProject.config
  1598. for key in ['user.name', 'user.email']:
  1599. if m.Has(key, include_defaults = False):
  1600. self.config.SetString(key, m.GetString(key))
  1601. if self.manifest.IsMirror:
  1602. self.config.SetString('core.bare', 'true')
  1603. else:
  1604. self.config.SetString('core.bare', None)
  1605. def _UpdateHooks(self):
  1606. if os.path.exists(self.gitdir):
  1607. # Always recreate hooks since they can have been changed
  1608. # since the latest update.
  1609. hooks = self._gitdir_path('hooks')
  1610. try:
  1611. to_rm = os.listdir(hooks)
  1612. except OSError:
  1613. to_rm = []
  1614. for old_hook in to_rm:
  1615. os.remove(os.path.join(hooks, old_hook))
  1616. self._InitHooks()
  1617. def _InitHooks(self):
  1618. hooks = self._gitdir_path('hooks')
  1619. if not os.path.exists(hooks):
  1620. os.makedirs(hooks)
  1621. for stock_hook in _ProjectHooks():
  1622. name = os.path.basename(stock_hook)
  1623. if name in ('commit-msg',) and not self.remote.review \
  1624. and not self is self.manifest.manifestProject:
  1625. # Don't install a Gerrit Code Review hook if this
  1626. # project does not appear to use it for reviews.
  1627. #
  1628. # Since the manifest project is one of those, but also
  1629. # managed through gerrit, it's excluded
  1630. continue
  1631. dst = os.path.join(hooks, name)
  1632. if os.path.islink(dst):
  1633. continue
  1634. if os.path.exists(dst):
  1635. if filecmp.cmp(stock_hook, dst, shallow=False):
  1636. os.remove(dst)
  1637. else:
  1638. _error("%s: Not replacing %s hook", self.relpath, name)
  1639. continue
  1640. try:
  1641. os.symlink(os.path.relpath(stock_hook, os.path.dirname(dst)), dst)
  1642. except OSError as e:
  1643. if e.errno == errno.EPERM:
  1644. raise GitError('filesystem must support symlinks')
  1645. else:
  1646. raise
  1647. def _InitRemote(self):
  1648. if self.remote.url:
  1649. remote = self.GetRemote(self.remote.name)
  1650. remote.url = self.remote.url
  1651. remote.review = self.remote.review
  1652. remote.projectname = self.name
  1653. if self.worktree:
  1654. remote.ResetFetch(mirror=False)
  1655. else:
  1656. remote.ResetFetch(mirror=True)
  1657. remote.Save()
  1658. def _InitMRef(self):
  1659. if self.manifest.branch:
  1660. self._InitAnyMRef(R_M + self.manifest.branch)
  1661. def _InitMirrorHead(self):
  1662. self._InitAnyMRef(HEAD)
  1663. def _InitAnyMRef(self, ref):
  1664. cur = self.bare_ref.symref(ref)
  1665. if self.revisionId:
  1666. if cur != '' or self.bare_ref.get(ref) != self.revisionId:
  1667. msg = 'manifest set to %s' % self.revisionId
  1668. dst = self.revisionId + '^0'
  1669. self.bare_git.UpdateRef(ref, dst, message = msg, detach = True)
  1670. else:
  1671. remote = self.GetRemote(self.remote.name)
  1672. dst = remote.ToLocal(self.revisionExpr)
  1673. if cur != dst:
  1674. msg = 'manifest set to %s' % self.revisionExpr
  1675. self.bare_git.symbolic_ref('-m', msg, ref, dst)
  1676. def _InitWorkTree(self):
  1677. dotgit = os.path.join(self.worktree, '.git')
  1678. if not os.path.exists(dotgit):
  1679. os.makedirs(dotgit)
  1680. for name in ['config',
  1681. 'description',
  1682. 'hooks',
  1683. 'info',
  1684. 'logs',
  1685. 'objects',
  1686. 'packed-refs',
  1687. 'refs',
  1688. 'rr-cache',
  1689. 'svn']:
  1690. try:
  1691. src = os.path.join(self.gitdir, name)
  1692. dst = os.path.join(dotgit, name)
  1693. if os.path.islink(dst) or not os.path.exists(dst):
  1694. os.symlink(os.path.relpath(src, os.path.dirname(dst)), dst)
  1695. else:
  1696. raise GitError('cannot overwrite a local work tree')
  1697. except OSError as e:
  1698. if e.errno == errno.EPERM:
  1699. raise GitError('filesystem must support symlinks')
  1700. else:
  1701. raise
  1702. _lwrite(os.path.join(dotgit, HEAD), '%s\n' % self.GetRevisionId())
  1703. cmd = ['read-tree', '--reset', '-u']
  1704. cmd.append('-v')
  1705. cmd.append(HEAD)
  1706. if GitCommand(self, cmd).Wait() != 0:
  1707. raise GitError("cannot initialize work tree")
  1708. rr_cache = os.path.join(self.gitdir, 'rr-cache')
  1709. if not os.path.exists(rr_cache):
  1710. os.makedirs(rr_cache)
  1711. self._CopyFiles()
  1712. def _gitdir_path(self, path):
  1713. return os.path.join(self.gitdir, path)
  1714. def _revlist(self, *args, **kw):
  1715. a = []
  1716. a.extend(args)
  1717. a.append('--')
  1718. return self.work_git.rev_list(*a, **kw)
  1719. @property
  1720. def _allrefs(self):
  1721. return self.bare_ref.all
  1722. class _GitGetByExec(object):
  1723. def __init__(self, project, bare):
  1724. self._project = project
  1725. self._bare = bare
  1726. def LsOthers(self):
  1727. p = GitCommand(self._project,
  1728. ['ls-files',
  1729. '-z',
  1730. '--others',
  1731. '--exclude-standard'],
  1732. bare = False,
  1733. capture_stdout = True,
  1734. capture_stderr = True)
  1735. if p.Wait() == 0:
  1736. out = p.stdout
  1737. if out:
  1738. return out[:-1].split('\0') # pylint: disable=W1401
  1739. # Backslash is not anomalous
  1740. return []
  1741. def DiffZ(self, name, *args):
  1742. cmd = [name]
  1743. cmd.append('-z')
  1744. cmd.extend(args)
  1745. p = GitCommand(self._project,
  1746. cmd,
  1747. bare = False,
  1748. capture_stdout = True,
  1749. capture_stderr = True)
  1750. try:
  1751. out = p.process.stdout.read()
  1752. r = {}
  1753. if out:
  1754. out = iter(out[:-1].split('\0')) # pylint: disable=W1401
  1755. while out:
  1756. try:
  1757. info = out.next()
  1758. path = out.next()
  1759. except StopIteration:
  1760. break
  1761. class _Info(object):
  1762. def __init__(self, path, omode, nmode, oid, nid, state):
  1763. self.path = path
  1764. self.src_path = None
  1765. self.old_mode = omode
  1766. self.new_mode = nmode
  1767. self.old_id = oid
  1768. self.new_id = nid
  1769. if len(state) == 1:
  1770. self.status = state
  1771. self.level = None
  1772. else:
  1773. self.status = state[:1]
  1774. self.level = state[1:]
  1775. while self.level.startswith('0'):
  1776. self.level = self.level[1:]
  1777. info = info[1:].split(' ')
  1778. info = _Info(path, *info)
  1779. if info.status in ('R', 'C'):
  1780. info.src_path = info.path
  1781. info.path = out.next()
  1782. r[info.path] = info
  1783. return r
  1784. finally:
  1785. p.Wait()
  1786. def GetHead(self):
  1787. if self._bare:
  1788. path = os.path.join(self._project.gitdir, HEAD)
  1789. else:
  1790. path = os.path.join(self._project.worktree, '.git', HEAD)
  1791. try:
  1792. fd = open(path, 'rb')
  1793. except IOError:
  1794. raise NoManifestException(path)
  1795. try:
  1796. line = fd.read()
  1797. finally:
  1798. fd.close()
  1799. if line.startswith('ref: '):
  1800. return line[5:-1]
  1801. return line[:-1]
  1802. def SetHead(self, ref, message=None):
  1803. cmdv = []
  1804. if message is not None:
  1805. cmdv.extend(['-m', message])
  1806. cmdv.append(HEAD)
  1807. cmdv.append(ref)
  1808. self.symbolic_ref(*cmdv)
  1809. def DetachHead(self, new, message=None):
  1810. cmdv = ['--no-deref']
  1811. if message is not None:
  1812. cmdv.extend(['-m', message])
  1813. cmdv.append(HEAD)
  1814. cmdv.append(new)
  1815. self.update_ref(*cmdv)
  1816. def UpdateRef(self, name, new, old=None,
  1817. message=None,
  1818. detach=False):
  1819. cmdv = []
  1820. if message is not None:
  1821. cmdv.extend(['-m', message])
  1822. if detach:
  1823. cmdv.append('--no-deref')
  1824. cmdv.append(name)
  1825. cmdv.append(new)
  1826. if old is not None:
  1827. cmdv.append(old)
  1828. self.update_ref(*cmdv)
  1829. def DeleteRef(self, name, old=None):
  1830. if not old:
  1831. old = self.rev_parse(name)
  1832. self.update_ref('-d', name, old)
  1833. self._project.bare_ref.deleted(name)
  1834. def rev_list(self, *args, **kw):
  1835. if 'format' in kw:
  1836. cmdv = ['log', '--pretty=format:%s' % kw['format']]
  1837. else:
  1838. cmdv = ['rev-list']
  1839. cmdv.extend(args)
  1840. p = GitCommand(self._project,
  1841. cmdv,
  1842. bare = self._bare,
  1843. capture_stdout = True,
  1844. capture_stderr = True)
  1845. r = []
  1846. for line in p.process.stdout:
  1847. if line[-1] == '\n':
  1848. line = line[:-1]
  1849. r.append(line)
  1850. if p.Wait() != 0:
  1851. raise GitError('%s rev-list %s: %s' % (
  1852. self._project.name,
  1853. str(args),
  1854. p.stderr))
  1855. return r
  1856. def __getattr__(self, name):
  1857. """Allow arbitrary git commands using pythonic syntax.
  1858. This allows you to do things like:
  1859. git_obj.rev_parse('HEAD')
  1860. Since we don't have a 'rev_parse' method defined, the __getattr__ will
  1861. run. We'll replace the '_' with a '-' and try to run a git command.
  1862. Any other positional arguments will be passed to the git command, and the
  1863. following keyword arguments are supported:
  1864. config: An optional dict of git config options to be passed with '-c'.
  1865. Args:
  1866. name: The name of the git command to call. Any '_' characters will
  1867. be replaced with '-'.
  1868. Returns:
  1869. A callable object that will try to call git with the named command.
  1870. """
  1871. name = name.replace('_', '-')
  1872. def runner(*args, **kwargs):
  1873. cmdv = []
  1874. config = kwargs.pop('config', None)
  1875. for k in kwargs:
  1876. raise TypeError('%s() got an unexpected keyword argument %r'
  1877. % (name, k))
  1878. if config is not None:
  1879. if not git_require((1, 7, 2)):
  1880. raise ValueError('cannot set config on command line for %s()'
  1881. % name)
  1882. for k, v in config.iteritems():
  1883. cmdv.append('-c')
  1884. cmdv.append('%s=%s' % (k, v))
  1885. cmdv.append(name)
  1886. cmdv.extend(args)
  1887. p = GitCommand(self._project,
  1888. cmdv,
  1889. bare = self._bare,
  1890. capture_stdout = True,
  1891. capture_stderr = True)
  1892. if p.Wait() != 0:
  1893. raise GitError('%s %s: %s' % (
  1894. self._project.name,
  1895. name,
  1896. p.stderr))
  1897. r = p.stdout
  1898. if r.endswith('\n') and r.index('\n') == len(r) - 1:
  1899. return r[:-1]
  1900. return r
  1901. return runner
  1902. class _PriorSyncFailedError(Exception):
  1903. def __str__(self):
  1904. return 'prior sync failed; rebase still in progress'
  1905. class _DirtyError(Exception):
  1906. def __str__(self):
  1907. return 'contains uncommitted changes'
  1908. class _InfoMessage(object):
  1909. def __init__(self, project, text):
  1910. self.project = project
  1911. self.text = text
  1912. def Print(self, syncbuf):
  1913. syncbuf.out.info('%s/: %s', self.project.relpath, self.text)
  1914. syncbuf.out.nl()
  1915. class _Failure(object):
  1916. def __init__(self, project, why):
  1917. self.project = project
  1918. self.why = why
  1919. def Print(self, syncbuf):
  1920. syncbuf.out.fail('error: %s/: %s',
  1921. self.project.relpath,
  1922. str(self.why))
  1923. syncbuf.out.nl()
  1924. class _Later(object):
  1925. def __init__(self, project, action):
  1926. self.project = project
  1927. self.action = action
  1928. def Run(self, syncbuf):
  1929. out = syncbuf.out
  1930. out.project('project %s/', self.project.relpath)
  1931. out.nl()
  1932. try:
  1933. self.action()
  1934. out.nl()
  1935. return True
  1936. except GitError:
  1937. out.nl()
  1938. return False
  1939. class _SyncColoring(Coloring):
  1940. def __init__(self, config):
  1941. Coloring.__init__(self, config, 'reposync')
  1942. self.project = self.printer('header', attr = 'bold')
  1943. self.info = self.printer('info')
  1944. self.fail = self.printer('fail', fg='red')
  1945. class SyncBuffer(object):
  1946. def __init__(self, config, detach_head=False):
  1947. self._messages = []
  1948. self._failures = []
  1949. self._later_queue1 = []
  1950. self._later_queue2 = []
  1951. self.out = _SyncColoring(config)
  1952. self.out.redirect(sys.stderr)
  1953. self.detach_head = detach_head
  1954. self.clean = True
  1955. def info(self, project, fmt, *args):
  1956. self._messages.append(_InfoMessage(project, fmt % args))
  1957. def fail(self, project, err=None):
  1958. self._failures.append(_Failure(project, err))
  1959. self.clean = False
  1960. def later1(self, project, what):
  1961. self._later_queue1.append(_Later(project, what))
  1962. def later2(self, project, what):
  1963. self._later_queue2.append(_Later(project, what))
  1964. def Finish(self):
  1965. self._PrintMessages()
  1966. self._RunLater()
  1967. self._PrintMessages()
  1968. return self.clean
  1969. def _RunLater(self):
  1970. for q in ['_later_queue1', '_later_queue2']:
  1971. if not self._RunQueue(q):
  1972. return
  1973. def _RunQueue(self, queue):
  1974. for m in getattr(self, queue):
  1975. if not m.Run(self):
  1976. self.clean = False
  1977. return False
  1978. setattr(self, queue, [])
  1979. return True
  1980. def _PrintMessages(self):
  1981. for m in self._messages:
  1982. m.Print(self)
  1983. for m in self._failures:
  1984. m.Print(self)
  1985. self._messages = []
  1986. self._failures = []
  1987. class MetaProject(Project):
  1988. """A special project housed under .repo.
  1989. """
  1990. def __init__(self, manifest, name, gitdir, worktree):
  1991. Project.__init__(self,
  1992. manifest = manifest,
  1993. name = name,
  1994. gitdir = gitdir,
  1995. worktree = worktree,
  1996. remote = RemoteSpec('origin'),
  1997. relpath = '.repo/%s' % name,
  1998. revisionExpr = 'refs/heads/master',
  1999. revisionId = None,
  2000. groups = None)
  2001. def PreSync(self):
  2002. if self.Exists:
  2003. cb = self.CurrentBranch
  2004. if cb:
  2005. base = self.GetBranch(cb).merge
  2006. if base:
  2007. self.revisionExpr = base
  2008. self.revisionId = None
  2009. def MetaBranchSwitch(self, target):
  2010. """ Prepare MetaProject for manifest branch switch
  2011. """
  2012. # detach and delete manifest branch, allowing a new
  2013. # branch to take over
  2014. syncbuf = SyncBuffer(self.config, detach_head = True)
  2015. self.Sync_LocalHalf(syncbuf)
  2016. syncbuf.Finish()
  2017. return GitCommand(self,
  2018. ['update-ref', '-d', 'refs/heads/default'],
  2019. capture_stdout = True,
  2020. capture_stderr = True).Wait() == 0
  2021. @property
  2022. def LastFetch(self):
  2023. try:
  2024. fh = os.path.join(self.gitdir, 'FETCH_HEAD')
  2025. return os.path.getmtime(fh)
  2026. except OSError:
  2027. return 0
  2028. @property
  2029. def HasChanges(self):
  2030. """Has the remote received new commits not yet checked out?
  2031. """
  2032. if not self.remote or not self.revisionExpr:
  2033. return False
  2034. all_refs = self.bare_ref.all
  2035. revid = self.GetRevisionId(all_refs)
  2036. head = self.work_git.GetHead()
  2037. if head.startswith(R_HEADS):
  2038. try:
  2039. head = all_refs[head]
  2040. except KeyError:
  2041. head = None
  2042. if revid == head:
  2043. return False
  2044. elif self._revlist(not_rev(HEAD), revid):
  2045. return True
  2046. return False