project.py 71 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395
  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. clone_depth = None,
  414. upstream = None,
  415. parent = None,
  416. is_derived = False):
  417. """Init a Project object.
  418. Args:
  419. manifest: The XmlManifest object.
  420. name: The `name` attribute of manifest.xml's project element.
  421. remote: RemoteSpec object specifying its remote's properties.
  422. gitdir: Absolute path of git directory.
  423. worktree: Absolute path of git working tree.
  424. relpath: Relative path of git working tree to repo's top directory.
  425. revisionExpr: The `revision` attribute of manifest.xml's project element.
  426. revisionId: git commit id for checking out.
  427. rebase: The `rebase` attribute of manifest.xml's project element.
  428. groups: The `groups` attribute of manifest.xml's project element.
  429. sync_c: The `sync-c` attribute of manifest.xml's project element.
  430. sync_s: The `sync-s` attribute of manifest.xml's project element.
  431. upstream: The `upstream` attribute of manifest.xml's project element.
  432. parent: The parent Project object.
  433. is_derived: False if the project was explicitly defined in the manifest;
  434. True if the project is a discovered submodule.
  435. """
  436. self.manifest = manifest
  437. self.name = name
  438. self.remote = remote
  439. self.gitdir = gitdir.replace('\\', '/')
  440. if worktree:
  441. self.worktree = worktree.replace('\\', '/')
  442. else:
  443. self.worktree = None
  444. self.relpath = relpath
  445. self.revisionExpr = revisionExpr
  446. if revisionId is None \
  447. and revisionExpr \
  448. and IsId(revisionExpr):
  449. self.revisionId = revisionExpr
  450. else:
  451. self.revisionId = revisionId
  452. self.rebase = rebase
  453. self.groups = groups
  454. self.sync_c = sync_c
  455. self.sync_s = sync_s
  456. self.clone_depth = clone_depth
  457. self.upstream = upstream
  458. self.parent = parent
  459. self.is_derived = is_derived
  460. self.subprojects = []
  461. self.snapshots = {}
  462. self.copyfiles = []
  463. self.annotations = []
  464. self.config = GitConfig.ForRepository(
  465. gitdir = self.gitdir,
  466. defaults = self.manifest.globalConfig)
  467. if self.worktree:
  468. self.work_git = self._GitGetByExec(self, bare=False)
  469. else:
  470. self.work_git = None
  471. self.bare_git = self._GitGetByExec(self, bare=True)
  472. self.bare_ref = GitRefs(gitdir)
  473. # This will be filled in if a project is later identified to be the
  474. # project containing repo hooks.
  475. self.enabled_repo_hooks = []
  476. @property
  477. def Derived(self):
  478. return self.is_derived
  479. @property
  480. def Exists(self):
  481. return os.path.isdir(self.gitdir)
  482. @property
  483. def CurrentBranch(self):
  484. """Obtain the name of the currently checked out branch.
  485. The branch name omits the 'refs/heads/' prefix.
  486. None is returned if the project is on a detached HEAD.
  487. """
  488. b = self.work_git.GetHead()
  489. if b.startswith(R_HEADS):
  490. return b[len(R_HEADS):]
  491. return None
  492. def IsRebaseInProgress(self):
  493. w = self.worktree
  494. g = os.path.join(w, '.git')
  495. return os.path.exists(os.path.join(g, 'rebase-apply')) \
  496. or os.path.exists(os.path.join(g, 'rebase-merge')) \
  497. or os.path.exists(os.path.join(w, '.dotest'))
  498. def IsDirty(self, consider_untracked=True):
  499. """Is the working directory modified in some way?
  500. """
  501. self.work_git.update_index('-q',
  502. '--unmerged',
  503. '--ignore-missing',
  504. '--refresh')
  505. if self.work_git.DiffZ('diff-index', '-M', '--cached', HEAD):
  506. return True
  507. if self.work_git.DiffZ('diff-files'):
  508. return True
  509. if consider_untracked and self.work_git.LsOthers():
  510. return True
  511. return False
  512. _userident_name = None
  513. _userident_email = None
  514. @property
  515. def UserName(self):
  516. """Obtain the user's personal name.
  517. """
  518. if self._userident_name is None:
  519. self._LoadUserIdentity()
  520. return self._userident_name
  521. @property
  522. def UserEmail(self):
  523. """Obtain the user's email address. This is very likely
  524. to be their Gerrit login.
  525. """
  526. if self._userident_email is None:
  527. self._LoadUserIdentity()
  528. return self._userident_email
  529. def _LoadUserIdentity(self):
  530. u = self.bare_git.var('GIT_COMMITTER_IDENT')
  531. m = re.compile("^(.*) <([^>]*)> ").match(u)
  532. if m:
  533. self._userident_name = m.group(1)
  534. self._userident_email = m.group(2)
  535. else:
  536. self._userident_name = ''
  537. self._userident_email = ''
  538. def GetRemote(self, name):
  539. """Get the configuration for a single remote.
  540. """
  541. return self.config.GetRemote(name)
  542. def GetBranch(self, name):
  543. """Get the configuration for a single branch.
  544. """
  545. return self.config.GetBranch(name)
  546. def GetBranches(self):
  547. """Get all existing local branches.
  548. """
  549. current = self.CurrentBranch
  550. all_refs = self._allrefs
  551. heads = {}
  552. for name, ref_id in all_refs.iteritems():
  553. if name.startswith(R_HEADS):
  554. name = name[len(R_HEADS):]
  555. b = self.GetBranch(name)
  556. b.current = name == current
  557. b.published = None
  558. b.revision = ref_id
  559. heads[name] = b
  560. for name, ref_id in all_refs.iteritems():
  561. if name.startswith(R_PUB):
  562. name = name[len(R_PUB):]
  563. b = heads.get(name)
  564. if b:
  565. b.published = ref_id
  566. return heads
  567. def MatchesGroups(self, manifest_groups):
  568. """Returns true if the manifest groups specified at init should cause
  569. this project to be synced.
  570. Prefixing a manifest group with "-" inverts the meaning of a group.
  571. All projects are implicitly labelled with "all".
  572. labels are resolved in order. In the example case of
  573. project_groups: "all,group1,group2"
  574. manifest_groups: "-group1,group2"
  575. the project will be matched.
  576. The special manifest group "default" will match any project that
  577. does not have the special project group "notdefault"
  578. """
  579. expanded_manifest_groups = manifest_groups or ['default']
  580. expanded_project_groups = ['all'] + (self.groups or [])
  581. if not 'notdefault' in expanded_project_groups:
  582. expanded_project_groups += ['default']
  583. matched = False
  584. for group in expanded_manifest_groups:
  585. if group.startswith('-') and group[1:] in expanded_project_groups:
  586. matched = False
  587. elif group in expanded_project_groups:
  588. matched = True
  589. return matched
  590. ## Status Display ##
  591. def HasChanges(self):
  592. """Returns true if there are uncommitted changes.
  593. """
  594. self.work_git.update_index('-q',
  595. '--unmerged',
  596. '--ignore-missing',
  597. '--refresh')
  598. if self.IsRebaseInProgress():
  599. return True
  600. if self.work_git.DiffZ('diff-index', '--cached', HEAD):
  601. return True
  602. if self.work_git.DiffZ('diff-files'):
  603. return True
  604. if self.work_git.LsOthers():
  605. return True
  606. return False
  607. def PrintWorkTreeStatus(self, output_redir=None):
  608. """Prints the status of the repository to stdout.
  609. Args:
  610. output: If specified, redirect the output to this object.
  611. """
  612. if not os.path.isdir(self.worktree):
  613. if output_redir == None:
  614. output_redir = sys.stdout
  615. print(file=output_redir)
  616. print('project %s/' % self.relpath, file=output_redir)
  617. print(' missing (run "repo sync")', file=output_redir)
  618. return
  619. self.work_git.update_index('-q',
  620. '--unmerged',
  621. '--ignore-missing',
  622. '--refresh')
  623. rb = self.IsRebaseInProgress()
  624. di = self.work_git.DiffZ('diff-index', '-M', '--cached', HEAD)
  625. df = self.work_git.DiffZ('diff-files')
  626. do = self.work_git.LsOthers()
  627. if not rb and not di and not df and not do and not self.CurrentBranch:
  628. return 'CLEAN'
  629. out = StatusColoring(self.config)
  630. if not output_redir == None:
  631. out.redirect(output_redir)
  632. out.project('project %-40s', self.relpath + '/')
  633. branch = self.CurrentBranch
  634. if branch is None:
  635. out.nobranch('(*** NO BRANCH ***)')
  636. else:
  637. out.branch('branch %s', branch)
  638. out.nl()
  639. if rb:
  640. out.important('prior sync failed; rebase still in progress')
  641. out.nl()
  642. paths = list()
  643. paths.extend(di.keys())
  644. paths.extend(df.keys())
  645. paths.extend(do)
  646. paths = list(set(paths))
  647. paths.sort()
  648. for p in paths:
  649. try:
  650. i = di[p]
  651. except KeyError:
  652. i = None
  653. try:
  654. f = df[p]
  655. except KeyError:
  656. f = None
  657. if i:
  658. i_status = i.status.upper()
  659. else:
  660. i_status = '-'
  661. if f:
  662. f_status = f.status.lower()
  663. else:
  664. f_status = '-'
  665. if i and i.src_path:
  666. line = ' %s%s\t%s => %s (%s%%)' % (i_status, f_status,
  667. i.src_path, p, i.level)
  668. else:
  669. line = ' %s%s\t%s' % (i_status, f_status, p)
  670. if i and not f:
  671. out.added('%s', line)
  672. elif (i and f) or (not i and f):
  673. out.changed('%s', line)
  674. elif not i and not f:
  675. out.untracked('%s', line)
  676. else:
  677. out.write('%s', line)
  678. out.nl()
  679. return 'DIRTY'
  680. def PrintWorkTreeDiff(self, absolute_paths=False):
  681. """Prints the status of the repository to stdout.
  682. """
  683. out = DiffColoring(self.config)
  684. cmd = ['diff']
  685. if out.is_on:
  686. cmd.append('--color')
  687. cmd.append(HEAD)
  688. if absolute_paths:
  689. cmd.append('--src-prefix=a/%s/' % self.relpath)
  690. cmd.append('--dst-prefix=b/%s/' % self.relpath)
  691. cmd.append('--')
  692. p = GitCommand(self,
  693. cmd,
  694. capture_stdout = True,
  695. capture_stderr = True)
  696. has_diff = False
  697. for line in p.process.stdout:
  698. if not has_diff:
  699. out.nl()
  700. out.project('project %s/' % self.relpath)
  701. out.nl()
  702. has_diff = True
  703. print(line[:-1])
  704. p.Wait()
  705. ## Publish / Upload ##
  706. def WasPublished(self, branch, all_refs=None):
  707. """Was the branch published (uploaded) for code review?
  708. If so, returns the SHA-1 hash of the last published
  709. state for the branch.
  710. """
  711. key = R_PUB + branch
  712. if all_refs is None:
  713. try:
  714. return self.bare_git.rev_parse(key)
  715. except GitError:
  716. return None
  717. else:
  718. try:
  719. return all_refs[key]
  720. except KeyError:
  721. return None
  722. def CleanPublishedCache(self, all_refs=None):
  723. """Prunes any stale published refs.
  724. """
  725. if all_refs is None:
  726. all_refs = self._allrefs
  727. heads = set()
  728. canrm = {}
  729. for name, ref_id in all_refs.iteritems():
  730. if name.startswith(R_HEADS):
  731. heads.add(name)
  732. elif name.startswith(R_PUB):
  733. canrm[name] = ref_id
  734. for name, ref_id in canrm.iteritems():
  735. n = name[len(R_PUB):]
  736. if R_HEADS + n not in heads:
  737. self.bare_git.DeleteRef(name, ref_id)
  738. def GetUploadableBranches(self, selected_branch=None):
  739. """List any branches which can be uploaded for review.
  740. """
  741. heads = {}
  742. pubed = {}
  743. for name, ref_id in self._allrefs.iteritems():
  744. if name.startswith(R_HEADS):
  745. heads[name[len(R_HEADS):]] = ref_id
  746. elif name.startswith(R_PUB):
  747. pubed[name[len(R_PUB):]] = ref_id
  748. ready = []
  749. for branch, ref_id in heads.iteritems():
  750. if branch in pubed and pubed[branch] == ref_id:
  751. continue
  752. if selected_branch and branch != selected_branch:
  753. continue
  754. rb = self.GetUploadableBranch(branch)
  755. if rb:
  756. ready.append(rb)
  757. return ready
  758. def GetUploadableBranch(self, branch_name):
  759. """Get a single uploadable branch, or None.
  760. """
  761. branch = self.GetBranch(branch_name)
  762. base = branch.LocalMerge
  763. if branch.LocalMerge:
  764. rb = ReviewableBranch(self, branch, base)
  765. if rb.commits:
  766. return rb
  767. return None
  768. def UploadForReview(self, branch=None,
  769. people=([],[]),
  770. auto_topic=False,
  771. draft=False):
  772. """Uploads the named branch for code review.
  773. """
  774. if branch is None:
  775. branch = self.CurrentBranch
  776. if branch is None:
  777. raise GitError('not currently on a branch')
  778. branch = self.GetBranch(branch)
  779. if not branch.LocalMerge:
  780. raise GitError('branch %s does not track a remote' % branch.name)
  781. if not branch.remote.review:
  782. raise GitError('remote %s has no review url' % branch.remote.name)
  783. dest_branch = branch.merge
  784. if not dest_branch.startswith(R_HEADS):
  785. dest_branch = R_HEADS + dest_branch
  786. if not branch.remote.projectname:
  787. branch.remote.projectname = self.name
  788. branch.remote.Save()
  789. url = branch.remote.ReviewUrl(self.UserEmail)
  790. if url is None:
  791. raise UploadError('review not configured')
  792. cmd = ['push']
  793. if url.startswith('ssh://'):
  794. rp = ['gerrit receive-pack']
  795. for e in people[0]:
  796. rp.append('--reviewer=%s' % sq(e))
  797. for e in people[1]:
  798. rp.append('--cc=%s' % sq(e))
  799. cmd.append('--receive-pack=%s' % " ".join(rp))
  800. cmd.append(url)
  801. if dest_branch.startswith(R_HEADS):
  802. dest_branch = dest_branch[len(R_HEADS):]
  803. upload_type = 'for'
  804. if draft:
  805. upload_type = 'drafts'
  806. ref_spec = '%s:refs/%s/%s' % (R_HEADS + branch.name, upload_type,
  807. dest_branch)
  808. if auto_topic:
  809. ref_spec = ref_spec + '/' + branch.name
  810. if not url.startswith('ssh://'):
  811. rp = ['r=%s' % p for p in people[0]] + \
  812. ['cc=%s' % p for p in people[1]]
  813. if rp:
  814. ref_spec = ref_spec + '%' + ','.join(rp)
  815. cmd.append(ref_spec)
  816. if GitCommand(self, cmd, bare = True).Wait() != 0:
  817. raise UploadError('Upload failed')
  818. msg = "posted to %s for %s" % (branch.remote.review, dest_branch)
  819. self.bare_git.UpdateRef(R_PUB + branch.name,
  820. R_HEADS + branch.name,
  821. message = msg)
  822. ## Sync ##
  823. def Sync_NetworkHalf(self,
  824. quiet=False,
  825. is_new=None,
  826. current_branch_only=False,
  827. clone_bundle=True,
  828. no_tags=False):
  829. """Perform only the network IO portion of the sync process.
  830. Local working directory/branch state is not affected.
  831. """
  832. if is_new is None:
  833. is_new = not self.Exists
  834. if is_new:
  835. self._InitGitDir()
  836. self._InitRemote()
  837. if is_new:
  838. alt = os.path.join(self.gitdir, 'objects/info/alternates')
  839. try:
  840. fd = open(alt, 'rb')
  841. try:
  842. alt_dir = fd.readline().rstrip()
  843. finally:
  844. fd.close()
  845. except IOError:
  846. alt_dir = None
  847. else:
  848. alt_dir = None
  849. if clone_bundle \
  850. and alt_dir is None \
  851. and self._ApplyCloneBundle(initial=is_new, quiet=quiet):
  852. is_new = False
  853. if not current_branch_only:
  854. if self.sync_c:
  855. current_branch_only = True
  856. elif not self.manifest._loaded:
  857. # Manifest cannot check defaults until it syncs.
  858. current_branch_only = False
  859. elif self.manifest.default.sync_c:
  860. current_branch_only = True
  861. if not self._RemoteFetch(initial=is_new, quiet=quiet, alt_dir=alt_dir,
  862. current_branch_only=current_branch_only,
  863. no_tags=no_tags):
  864. return False
  865. if self.worktree:
  866. self._InitMRef()
  867. else:
  868. self._InitMirrorHead()
  869. try:
  870. os.remove(os.path.join(self.gitdir, 'FETCH_HEAD'))
  871. except OSError:
  872. pass
  873. return True
  874. def PostRepoUpgrade(self):
  875. self._InitHooks()
  876. def _CopyFiles(self):
  877. for copyfile in self.copyfiles:
  878. copyfile._Copy()
  879. def GetRevisionId(self, all_refs=None):
  880. if self.revisionId:
  881. return self.revisionId
  882. rem = self.GetRemote(self.remote.name)
  883. rev = rem.ToLocal(self.revisionExpr)
  884. if all_refs is not None and rev in all_refs:
  885. return all_refs[rev]
  886. try:
  887. return self.bare_git.rev_parse('--verify', '%s^0' % rev)
  888. except GitError:
  889. raise ManifestInvalidRevisionError(
  890. 'revision %s in %s not found' % (self.revisionExpr,
  891. self.name))
  892. def Sync_LocalHalf(self, syncbuf):
  893. """Perform only the local IO portion of the sync process.
  894. Network access is not required.
  895. """
  896. all_refs = self.bare_ref.all
  897. self.CleanPublishedCache(all_refs)
  898. revid = self.GetRevisionId(all_refs)
  899. def _doff():
  900. self._FastForward(revid)
  901. self._CopyFiles()
  902. self._InitWorkTree()
  903. head = self.work_git.GetHead()
  904. if head.startswith(R_HEADS):
  905. branch = head[len(R_HEADS):]
  906. try:
  907. head = all_refs[head]
  908. except KeyError:
  909. head = None
  910. else:
  911. branch = None
  912. if branch is None or syncbuf.detach_head:
  913. # Currently on a detached HEAD. The user is assumed to
  914. # not have any local modifications worth worrying about.
  915. #
  916. if self.IsRebaseInProgress():
  917. syncbuf.fail(self, _PriorSyncFailedError())
  918. return
  919. if head == revid:
  920. # No changes; don't do anything further.
  921. # Except if the head needs to be detached
  922. #
  923. if not syncbuf.detach_head:
  924. return
  925. else:
  926. lost = self._revlist(not_rev(revid), HEAD)
  927. if lost:
  928. syncbuf.info(self, "discarding %d commits", len(lost))
  929. try:
  930. self._Checkout(revid, quiet=True)
  931. except GitError as e:
  932. syncbuf.fail(self, e)
  933. return
  934. self._CopyFiles()
  935. return
  936. if head == revid:
  937. # No changes; don't do anything further.
  938. #
  939. return
  940. branch = self.GetBranch(branch)
  941. if not branch.LocalMerge:
  942. # The current branch has no tracking configuration.
  943. # Jump off it to a detached HEAD.
  944. #
  945. syncbuf.info(self,
  946. "leaving %s; does not track upstream",
  947. branch.name)
  948. try:
  949. self._Checkout(revid, quiet=True)
  950. except GitError as e:
  951. syncbuf.fail(self, e)
  952. return
  953. self._CopyFiles()
  954. return
  955. upstream_gain = self._revlist(not_rev(HEAD), revid)
  956. pub = self.WasPublished(branch.name, all_refs)
  957. if pub:
  958. not_merged = self._revlist(not_rev(revid), pub)
  959. if not_merged:
  960. if upstream_gain:
  961. # The user has published this branch and some of those
  962. # commits are not yet merged upstream. We do not want
  963. # to rewrite the published commits so we punt.
  964. #
  965. syncbuf.fail(self,
  966. "branch %s is published (but not merged) and is now %d commits behind"
  967. % (branch.name, len(upstream_gain)))
  968. return
  969. elif pub == head:
  970. # All published commits are merged, and thus we are a
  971. # strict subset. We can fast-forward safely.
  972. #
  973. syncbuf.later1(self, _doff)
  974. return
  975. # Examine the local commits not in the remote. Find the
  976. # last one attributed to this user, if any.
  977. #
  978. local_changes = self._revlist(not_rev(revid), HEAD, format='%H %ce')
  979. last_mine = None
  980. cnt_mine = 0
  981. for commit in local_changes:
  982. commit_id, committer_email = commit.split(' ', 1)
  983. if committer_email == self.UserEmail:
  984. last_mine = commit_id
  985. cnt_mine += 1
  986. if not upstream_gain and cnt_mine == len(local_changes):
  987. return
  988. if self.IsDirty(consider_untracked=False):
  989. syncbuf.fail(self, _DirtyError())
  990. return
  991. # If the upstream switched on us, warn the user.
  992. #
  993. if branch.merge != self.revisionExpr:
  994. if branch.merge and self.revisionExpr:
  995. syncbuf.info(self,
  996. 'manifest switched %s...%s',
  997. branch.merge,
  998. self.revisionExpr)
  999. elif branch.merge:
  1000. syncbuf.info(self,
  1001. 'manifest no longer tracks %s',
  1002. branch.merge)
  1003. if cnt_mine < len(local_changes):
  1004. # Upstream rebased. Not everything in HEAD
  1005. # was created by this user.
  1006. #
  1007. syncbuf.info(self,
  1008. "discarding %d commits removed from upstream",
  1009. len(local_changes) - cnt_mine)
  1010. branch.remote = self.GetRemote(self.remote.name)
  1011. if not ID_RE.match(self.revisionExpr):
  1012. # in case of manifest sync the revisionExpr might be a SHA1
  1013. branch.merge = self.revisionExpr
  1014. branch.Save()
  1015. if cnt_mine > 0 and self.rebase:
  1016. def _dorebase():
  1017. self._Rebase(upstream = '%s^1' % last_mine, onto = revid)
  1018. self._CopyFiles()
  1019. syncbuf.later2(self, _dorebase)
  1020. elif local_changes:
  1021. try:
  1022. self._ResetHard(revid)
  1023. self._CopyFiles()
  1024. except GitError as e:
  1025. syncbuf.fail(self, e)
  1026. return
  1027. else:
  1028. syncbuf.later1(self, _doff)
  1029. def AddCopyFile(self, src, dest, absdest):
  1030. # dest should already be an absolute path, but src is project relative
  1031. # make src an absolute path
  1032. abssrc = os.path.join(self.worktree, src)
  1033. self.copyfiles.append(_CopyFile(src, dest, abssrc, absdest))
  1034. def AddAnnotation(self, name, value, keep):
  1035. self.annotations.append(_Annotation(name, value, keep))
  1036. def DownloadPatchSet(self, change_id, patch_id):
  1037. """Download a single patch set of a single change to FETCH_HEAD.
  1038. """
  1039. remote = self.GetRemote(self.remote.name)
  1040. cmd = ['fetch', remote.name]
  1041. cmd.append('refs/changes/%2.2d/%d/%d' \
  1042. % (change_id % 100, change_id, patch_id))
  1043. cmd.extend(map(str, remote.fetch))
  1044. if GitCommand(self, cmd, bare=True).Wait() != 0:
  1045. return None
  1046. return DownloadedChange(self,
  1047. self.GetRevisionId(),
  1048. change_id,
  1049. patch_id,
  1050. self.bare_git.rev_parse('FETCH_HEAD'))
  1051. ## Branch Management ##
  1052. def StartBranch(self, name):
  1053. """Create a new branch off the manifest's revision.
  1054. """
  1055. head = self.work_git.GetHead()
  1056. if head == (R_HEADS + name):
  1057. return True
  1058. all_refs = self.bare_ref.all
  1059. if (R_HEADS + name) in all_refs:
  1060. return GitCommand(self,
  1061. ['checkout', name, '--'],
  1062. capture_stdout = True,
  1063. capture_stderr = True).Wait() == 0
  1064. branch = self.GetBranch(name)
  1065. branch.remote = self.GetRemote(self.remote.name)
  1066. branch.merge = self.revisionExpr
  1067. revid = self.GetRevisionId(all_refs)
  1068. if head.startswith(R_HEADS):
  1069. try:
  1070. head = all_refs[head]
  1071. except KeyError:
  1072. head = None
  1073. if revid and head and revid == head:
  1074. ref = os.path.join(self.gitdir, R_HEADS + name)
  1075. try:
  1076. os.makedirs(os.path.dirname(ref))
  1077. except OSError:
  1078. pass
  1079. _lwrite(ref, '%s\n' % revid)
  1080. _lwrite(os.path.join(self.worktree, '.git', HEAD),
  1081. 'ref: %s%s\n' % (R_HEADS, name))
  1082. branch.Save()
  1083. return True
  1084. if GitCommand(self,
  1085. ['checkout', '-b', branch.name, revid],
  1086. capture_stdout = True,
  1087. capture_stderr = True).Wait() == 0:
  1088. branch.Save()
  1089. return True
  1090. return False
  1091. def CheckoutBranch(self, name):
  1092. """Checkout a local topic branch.
  1093. Args:
  1094. name: The name of the branch to checkout.
  1095. Returns:
  1096. True if the checkout succeeded; False if it didn't; None if the branch
  1097. didn't exist.
  1098. """
  1099. rev = R_HEADS + name
  1100. head = self.work_git.GetHead()
  1101. if head == rev:
  1102. # Already on the branch
  1103. #
  1104. return True
  1105. all_refs = self.bare_ref.all
  1106. try:
  1107. revid = all_refs[rev]
  1108. except KeyError:
  1109. # Branch does not exist in this project
  1110. #
  1111. return None
  1112. if head.startswith(R_HEADS):
  1113. try:
  1114. head = all_refs[head]
  1115. except KeyError:
  1116. head = None
  1117. if head == revid:
  1118. # Same revision; just update HEAD to point to the new
  1119. # target branch, but otherwise take no other action.
  1120. #
  1121. _lwrite(os.path.join(self.worktree, '.git', HEAD),
  1122. 'ref: %s%s\n' % (R_HEADS, name))
  1123. return True
  1124. return GitCommand(self,
  1125. ['checkout', name, '--'],
  1126. capture_stdout = True,
  1127. capture_stderr = True).Wait() == 0
  1128. def AbandonBranch(self, name):
  1129. """Destroy a local topic branch.
  1130. Args:
  1131. name: The name of the branch to abandon.
  1132. Returns:
  1133. True if the abandon succeeded; False if it didn't; None if the branch
  1134. didn't exist.
  1135. """
  1136. rev = R_HEADS + name
  1137. all_refs = self.bare_ref.all
  1138. if rev not in all_refs:
  1139. # Doesn't exist
  1140. return None
  1141. head = self.work_git.GetHead()
  1142. if head == rev:
  1143. # We can't destroy the branch while we are sitting
  1144. # on it. Switch to a detached HEAD.
  1145. #
  1146. head = all_refs[head]
  1147. revid = self.GetRevisionId(all_refs)
  1148. if head == revid:
  1149. _lwrite(os.path.join(self.worktree, '.git', HEAD),
  1150. '%s\n' % revid)
  1151. else:
  1152. self._Checkout(revid, quiet=True)
  1153. return GitCommand(self,
  1154. ['branch', '-D', name],
  1155. capture_stdout = True,
  1156. capture_stderr = True).Wait() == 0
  1157. def PruneHeads(self):
  1158. """Prune any topic branches already merged into upstream.
  1159. """
  1160. cb = self.CurrentBranch
  1161. kill = []
  1162. left = self._allrefs
  1163. for name in left.keys():
  1164. if name.startswith(R_HEADS):
  1165. name = name[len(R_HEADS):]
  1166. if cb is None or name != cb:
  1167. kill.append(name)
  1168. rev = self.GetRevisionId(left)
  1169. if cb is not None \
  1170. and not self._revlist(HEAD + '...' + rev) \
  1171. and not self.IsDirty(consider_untracked = False):
  1172. self.work_git.DetachHead(HEAD)
  1173. kill.append(cb)
  1174. if kill:
  1175. old = self.bare_git.GetHead()
  1176. if old is None:
  1177. old = 'refs/heads/please_never_use_this_as_a_branch_name'
  1178. try:
  1179. self.bare_git.DetachHead(rev)
  1180. b = ['branch', '-d']
  1181. b.extend(kill)
  1182. b = GitCommand(self, b, bare=True,
  1183. capture_stdout=True,
  1184. capture_stderr=True)
  1185. b.Wait()
  1186. finally:
  1187. self.bare_git.SetHead(old)
  1188. left = self._allrefs
  1189. for branch in kill:
  1190. if (R_HEADS + branch) not in left:
  1191. self.CleanPublishedCache()
  1192. break
  1193. if cb and cb not in kill:
  1194. kill.append(cb)
  1195. kill.sort()
  1196. kept = []
  1197. for branch in kill:
  1198. if (R_HEADS + branch) in left:
  1199. branch = self.GetBranch(branch)
  1200. base = branch.LocalMerge
  1201. if not base:
  1202. base = rev
  1203. kept.append(ReviewableBranch(self, branch, base))
  1204. return kept
  1205. ## Submodule Management ##
  1206. def GetRegisteredSubprojects(self):
  1207. result = []
  1208. def rec(subprojects):
  1209. if not subprojects:
  1210. return
  1211. result.extend(subprojects)
  1212. for p in subprojects:
  1213. rec(p.subprojects)
  1214. rec(self.subprojects)
  1215. return result
  1216. def _GetSubmodules(self):
  1217. # Unfortunately we cannot call `git submodule status --recursive` here
  1218. # because the working tree might not exist yet, and it cannot be used
  1219. # without a working tree in its current implementation.
  1220. def get_submodules(gitdir, rev):
  1221. # Parse .gitmodules for submodule sub_paths and sub_urls
  1222. sub_paths, sub_urls = parse_gitmodules(gitdir, rev)
  1223. if not sub_paths:
  1224. return []
  1225. # Run `git ls-tree` to read SHAs of submodule object, which happen to be
  1226. # revision of submodule repository
  1227. sub_revs = git_ls_tree(gitdir, rev, sub_paths)
  1228. submodules = []
  1229. for sub_path, sub_url in zip(sub_paths, sub_urls):
  1230. try:
  1231. sub_rev = sub_revs[sub_path]
  1232. except KeyError:
  1233. # Ignore non-exist submodules
  1234. continue
  1235. submodules.append((sub_rev, sub_path, sub_url))
  1236. return submodules
  1237. re_path = re.compile(r'^submodule\.([^.]+)\.path=(.*)$')
  1238. re_url = re.compile(r'^submodule\.([^.]+)\.url=(.*)$')
  1239. def parse_gitmodules(gitdir, rev):
  1240. cmd = ['cat-file', 'blob', '%s:.gitmodules' % rev]
  1241. try:
  1242. p = GitCommand(None, cmd, capture_stdout = True, capture_stderr = True,
  1243. bare = True, gitdir = gitdir)
  1244. except GitError:
  1245. return [], []
  1246. if p.Wait() != 0:
  1247. return [], []
  1248. gitmodules_lines = []
  1249. fd, temp_gitmodules_path = tempfile.mkstemp()
  1250. try:
  1251. os.write(fd, p.stdout)
  1252. os.close(fd)
  1253. cmd = ['config', '--file', temp_gitmodules_path, '--list']
  1254. p = GitCommand(None, cmd, capture_stdout = True, capture_stderr = True,
  1255. bare = True, gitdir = gitdir)
  1256. if p.Wait() != 0:
  1257. return [], []
  1258. gitmodules_lines = p.stdout.split('\n')
  1259. except GitError:
  1260. return [], []
  1261. finally:
  1262. os.remove(temp_gitmodules_path)
  1263. names = set()
  1264. paths = {}
  1265. urls = {}
  1266. for line in gitmodules_lines:
  1267. if not line:
  1268. continue
  1269. m = re_path.match(line)
  1270. if m:
  1271. names.add(m.group(1))
  1272. paths[m.group(1)] = m.group(2)
  1273. continue
  1274. m = re_url.match(line)
  1275. if m:
  1276. names.add(m.group(1))
  1277. urls[m.group(1)] = m.group(2)
  1278. continue
  1279. names = sorted(names)
  1280. return ([paths.get(name, '') for name in names],
  1281. [urls.get(name, '') for name in names])
  1282. def git_ls_tree(gitdir, rev, paths):
  1283. cmd = ['ls-tree', rev, '--']
  1284. cmd.extend(paths)
  1285. try:
  1286. p = GitCommand(None, cmd, capture_stdout = True, capture_stderr = True,
  1287. bare = True, gitdir = gitdir)
  1288. except GitError:
  1289. return []
  1290. if p.Wait() != 0:
  1291. return []
  1292. objects = {}
  1293. for line in p.stdout.split('\n'):
  1294. if not line.strip():
  1295. continue
  1296. object_rev, object_path = line.split()[2:4]
  1297. objects[object_path] = object_rev
  1298. return objects
  1299. try:
  1300. rev = self.GetRevisionId()
  1301. except GitError:
  1302. return []
  1303. return get_submodules(self.gitdir, rev)
  1304. def GetDerivedSubprojects(self):
  1305. result = []
  1306. if not self.Exists:
  1307. # If git repo does not exist yet, querying its submodules will
  1308. # mess up its states; so return here.
  1309. return result
  1310. for rev, path, url in self._GetSubmodules():
  1311. name = self.manifest.GetSubprojectName(self, path)
  1312. project = self.manifest.projects.get(name)
  1313. if project:
  1314. result.extend(project.GetDerivedSubprojects())
  1315. continue
  1316. relpath, worktree, gitdir = self.manifest.GetSubprojectPaths(self, path)
  1317. remote = RemoteSpec(self.remote.name,
  1318. url = url,
  1319. review = self.remote.review)
  1320. subproject = Project(manifest = self.manifest,
  1321. name = name,
  1322. remote = remote,
  1323. gitdir = gitdir,
  1324. worktree = worktree,
  1325. relpath = relpath,
  1326. revisionExpr = self.revisionExpr,
  1327. revisionId = rev,
  1328. rebase = self.rebase,
  1329. groups = self.groups,
  1330. sync_c = self.sync_c,
  1331. sync_s = self.sync_s,
  1332. parent = self,
  1333. is_derived = True)
  1334. result.append(subproject)
  1335. result.extend(subproject.GetDerivedSubprojects())
  1336. return result
  1337. ## Direct Git Commands ##
  1338. def _RemoteFetch(self, name=None,
  1339. current_branch_only=False,
  1340. initial=False,
  1341. quiet=False,
  1342. alt_dir=None,
  1343. no_tags=False):
  1344. is_sha1 = False
  1345. tag_name = None
  1346. def CheckForSha1():
  1347. try:
  1348. # if revision (sha or tag) is not present then following function
  1349. # throws an error.
  1350. self.bare_git.rev_parse('--verify', '%s^0' % self.revisionExpr)
  1351. return True
  1352. except GitError:
  1353. # There is no such persistent revision. We have to fetch it.
  1354. return False
  1355. if current_branch_only:
  1356. if ID_RE.match(self.revisionExpr) is not None:
  1357. is_sha1 = True
  1358. elif self.revisionExpr.startswith(R_TAGS):
  1359. # this is a tag and its sha1 value should never change
  1360. tag_name = self.revisionExpr[len(R_TAGS):]
  1361. if is_sha1 or tag_name is not None:
  1362. if CheckForSha1():
  1363. return True
  1364. if is_sha1 and (not self.upstream or ID_RE.match(self.upstream)):
  1365. current_branch_only = False
  1366. if not name:
  1367. name = self.remote.name
  1368. ssh_proxy = False
  1369. remote = self.GetRemote(name)
  1370. if remote.PreConnectFetch():
  1371. ssh_proxy = True
  1372. if initial:
  1373. if alt_dir and 'objects' == os.path.basename(alt_dir):
  1374. ref_dir = os.path.dirname(alt_dir)
  1375. packed_refs = os.path.join(self.gitdir, 'packed-refs')
  1376. remote = self.GetRemote(name)
  1377. all_refs = self.bare_ref.all
  1378. ids = set(all_refs.values())
  1379. tmp = set()
  1380. for r, ref_id in GitRefs(ref_dir).all.iteritems():
  1381. if r not in all_refs:
  1382. if r.startswith(R_TAGS) or remote.WritesTo(r):
  1383. all_refs[r] = ref_id
  1384. ids.add(ref_id)
  1385. continue
  1386. if ref_id in ids:
  1387. continue
  1388. r = 'refs/_alt/%s' % ref_id
  1389. all_refs[r] = ref_id
  1390. ids.add(ref_id)
  1391. tmp.add(r)
  1392. ref_names = list(all_refs.keys())
  1393. ref_names.sort()
  1394. tmp_packed = ''
  1395. old_packed = ''
  1396. for r in ref_names:
  1397. line = '%s %s\n' % (all_refs[r], r)
  1398. tmp_packed += line
  1399. if r not in tmp:
  1400. old_packed += line
  1401. _lwrite(packed_refs, tmp_packed)
  1402. else:
  1403. alt_dir = None
  1404. cmd = ['fetch']
  1405. # The --depth option only affects the initial fetch; after that we'll do
  1406. # full fetches of changes.
  1407. if self.clone_depth:
  1408. depth = self.clone_depth
  1409. else:
  1410. depth = self.manifest.manifestProject.config.GetString('repo.depth')
  1411. if depth and initial:
  1412. cmd.append('--depth=%s' % depth)
  1413. if quiet:
  1414. cmd.append('--quiet')
  1415. if not self.worktree:
  1416. cmd.append('--update-head-ok')
  1417. cmd.append(name)
  1418. if not current_branch_only:
  1419. # Fetch whole repo
  1420. if no_tags:
  1421. cmd.append('--no-tags')
  1422. else:
  1423. cmd.append('--tags')
  1424. cmd.append((u'+refs/heads/*:') + remote.ToLocal('refs/heads/*'))
  1425. elif tag_name is not None:
  1426. cmd.append('tag')
  1427. cmd.append(tag_name)
  1428. else:
  1429. branch = self.revisionExpr
  1430. if is_sha1:
  1431. branch = self.upstream
  1432. if branch.startswith(R_HEADS):
  1433. branch = branch[len(R_HEADS):]
  1434. cmd.append((u'+refs/heads/%s:' % branch) + remote.ToLocal('refs/heads/%s' % branch))
  1435. ok = False
  1436. for _i in range(2):
  1437. ret = GitCommand(self, cmd, bare=True, ssh_proxy=ssh_proxy).Wait()
  1438. if ret == 0:
  1439. ok = True
  1440. break
  1441. elif current_branch_only and is_sha1 and ret == 128:
  1442. # Exit code 128 means "couldn't find the ref you asked for"; if we're in sha1
  1443. # mode, we just tried sync'ing from the upstream field; it doesn't exist, thus
  1444. # abort the optimization attempt and do a full sync.
  1445. break
  1446. time.sleep(random.randint(30, 45))
  1447. if initial:
  1448. if alt_dir:
  1449. if old_packed != '':
  1450. _lwrite(packed_refs, old_packed)
  1451. else:
  1452. os.remove(packed_refs)
  1453. self.bare_git.pack_refs('--all', '--prune')
  1454. if is_sha1 and current_branch_only and self.upstream:
  1455. # We just synced the upstream given branch; verify we
  1456. # got what we wanted, else trigger a second run of all
  1457. # refs.
  1458. if not CheckForSha1():
  1459. return self._RemoteFetch(name=name, current_branch_only=False,
  1460. initial=False, quiet=quiet, alt_dir=alt_dir)
  1461. return ok
  1462. def _ApplyCloneBundle(self, initial=False, quiet=False):
  1463. if initial and (self.manifest.manifestProject.config.GetString('repo.depth') or self.clone_depth):
  1464. return False
  1465. remote = self.GetRemote(self.remote.name)
  1466. bundle_url = remote.url + '/clone.bundle'
  1467. bundle_url = GitConfig.ForUser().UrlInsteadOf(bundle_url)
  1468. if GetSchemeFromUrl(bundle_url) in ('persistent-http', 'persistent-https'):
  1469. bundle_url = bundle_url[len('persistent-'):]
  1470. if GetSchemeFromUrl(bundle_url) not in ('http', 'https'):
  1471. return False
  1472. bundle_dst = os.path.join(self.gitdir, 'clone.bundle')
  1473. bundle_tmp = os.path.join(self.gitdir, 'clone.bundle.tmp')
  1474. exist_dst = os.path.exists(bundle_dst)
  1475. exist_tmp = os.path.exists(bundle_tmp)
  1476. if not initial and not exist_dst and not exist_tmp:
  1477. return False
  1478. if not exist_dst:
  1479. exist_dst = self._FetchBundle(bundle_url, bundle_tmp, bundle_dst, quiet)
  1480. if not exist_dst:
  1481. return False
  1482. cmd = ['fetch']
  1483. if quiet:
  1484. cmd.append('--quiet')
  1485. if not self.worktree:
  1486. cmd.append('--update-head-ok')
  1487. cmd.append(bundle_dst)
  1488. for f in remote.fetch:
  1489. cmd.append(str(f))
  1490. cmd.append('refs/tags/*:refs/tags/*')
  1491. ok = GitCommand(self, cmd, bare=True).Wait() == 0
  1492. if os.path.exists(bundle_dst):
  1493. os.remove(bundle_dst)
  1494. if os.path.exists(bundle_tmp):
  1495. os.remove(bundle_tmp)
  1496. return ok
  1497. def _FetchBundle(self, srcUrl, tmpPath, dstPath, quiet):
  1498. if os.path.exists(dstPath):
  1499. os.remove(dstPath)
  1500. cmd = ['curl', '--fail', '--output', tmpPath, '--netrc', '--location']
  1501. if quiet:
  1502. cmd += ['--silent']
  1503. if os.path.exists(tmpPath):
  1504. size = os.stat(tmpPath).st_size
  1505. if size >= 1024:
  1506. cmd += ['--continue-at', '%d' % (size,)]
  1507. else:
  1508. os.remove(tmpPath)
  1509. if 'http_proxy' in os.environ and 'darwin' == sys.platform:
  1510. cmd += ['--proxy', os.environ['http_proxy']]
  1511. cookiefile = GitConfig.ForUser().GetString('http.cookiefile')
  1512. if cookiefile:
  1513. cmd += ['--cookie', cookiefile]
  1514. cmd += [srcUrl]
  1515. if IsTrace():
  1516. Trace('%s', ' '.join(cmd))
  1517. try:
  1518. proc = subprocess.Popen(cmd)
  1519. except OSError:
  1520. return False
  1521. curlret = proc.wait()
  1522. if curlret == 22:
  1523. # From curl man page:
  1524. # 22: HTTP page not retrieved. The requested url was not found or
  1525. # returned another error with the HTTP error code being 400 or above.
  1526. # This return code only appears if -f, --fail is used.
  1527. if not quiet:
  1528. print("Server does not provide clone.bundle; ignoring.",
  1529. file=sys.stderr)
  1530. return False
  1531. if os.path.exists(tmpPath):
  1532. if curlret == 0 and os.stat(tmpPath).st_size > 16:
  1533. os.rename(tmpPath, dstPath)
  1534. return True
  1535. else:
  1536. os.remove(tmpPath)
  1537. return False
  1538. else:
  1539. return False
  1540. def _Checkout(self, rev, quiet=False):
  1541. cmd = ['checkout']
  1542. if quiet:
  1543. cmd.append('-q')
  1544. cmd.append(rev)
  1545. cmd.append('--')
  1546. if GitCommand(self, cmd).Wait() != 0:
  1547. if self._allrefs:
  1548. raise GitError('%s checkout %s ' % (self.name, rev))
  1549. def _CherryPick(self, rev, quiet=False):
  1550. cmd = ['cherry-pick']
  1551. cmd.append(rev)
  1552. cmd.append('--')
  1553. if GitCommand(self, cmd).Wait() != 0:
  1554. if self._allrefs:
  1555. raise GitError('%s cherry-pick %s ' % (self.name, rev))
  1556. def _Revert(self, rev, quiet=False):
  1557. cmd = ['revert']
  1558. cmd.append('--no-edit')
  1559. cmd.append(rev)
  1560. cmd.append('--')
  1561. if GitCommand(self, cmd).Wait() != 0:
  1562. if self._allrefs:
  1563. raise GitError('%s revert %s ' % (self.name, rev))
  1564. def _ResetHard(self, rev, quiet=True):
  1565. cmd = ['reset', '--hard']
  1566. if quiet:
  1567. cmd.append('-q')
  1568. cmd.append(rev)
  1569. if GitCommand(self, cmd).Wait() != 0:
  1570. raise GitError('%s reset --hard %s ' % (self.name, rev))
  1571. def _Rebase(self, upstream, onto = None):
  1572. cmd = ['rebase']
  1573. if onto is not None:
  1574. cmd.extend(['--onto', onto])
  1575. cmd.append(upstream)
  1576. if GitCommand(self, cmd).Wait() != 0:
  1577. raise GitError('%s rebase %s ' % (self.name, upstream))
  1578. def _FastForward(self, head, ffonly=False):
  1579. cmd = ['merge', head]
  1580. if ffonly:
  1581. cmd.append("--ff-only")
  1582. if GitCommand(self, cmd).Wait() != 0:
  1583. raise GitError('%s merge %s ' % (self.name, head))
  1584. def _InitGitDir(self):
  1585. if not os.path.exists(self.gitdir):
  1586. os.makedirs(self.gitdir)
  1587. self.bare_git.init()
  1588. mp = self.manifest.manifestProject
  1589. ref_dir = mp.config.GetString('repo.reference')
  1590. if ref_dir:
  1591. mirror_git = os.path.join(ref_dir, self.name + '.git')
  1592. repo_git = os.path.join(ref_dir, '.repo', 'projects',
  1593. self.relpath + '.git')
  1594. if os.path.exists(mirror_git):
  1595. ref_dir = mirror_git
  1596. elif os.path.exists(repo_git):
  1597. ref_dir = repo_git
  1598. else:
  1599. ref_dir = None
  1600. if ref_dir:
  1601. _lwrite(os.path.join(self.gitdir, 'objects/info/alternates'),
  1602. os.path.join(ref_dir, 'objects') + '\n')
  1603. if self.manifest.IsMirror:
  1604. self.config.SetString('core.bare', 'true')
  1605. else:
  1606. self.config.SetString('core.bare', None)
  1607. hooks = self._gitdir_path('hooks')
  1608. try:
  1609. to_rm = os.listdir(hooks)
  1610. except OSError:
  1611. to_rm = []
  1612. for old_hook in to_rm:
  1613. os.remove(os.path.join(hooks, old_hook))
  1614. self._InitHooks()
  1615. m = self.manifest.manifestProject.config
  1616. for key in ['user.name', 'user.email']:
  1617. if m.Has(key, include_defaults = False):
  1618. self.config.SetString(key, m.GetString(key))
  1619. def _InitHooks(self):
  1620. hooks = self._gitdir_path('hooks')
  1621. if not os.path.exists(hooks):
  1622. os.makedirs(hooks)
  1623. for stock_hook in _ProjectHooks():
  1624. name = os.path.basename(stock_hook)
  1625. if name in ('commit-msg',) and not self.remote.review \
  1626. and not self is self.manifest.manifestProject:
  1627. # Don't install a Gerrit Code Review hook if this
  1628. # project does not appear to use it for reviews.
  1629. #
  1630. # Since the manifest project is one of those, but also
  1631. # managed through gerrit, it's excluded
  1632. continue
  1633. dst = os.path.join(hooks, name)
  1634. if os.path.islink(dst):
  1635. continue
  1636. if os.path.exists(dst):
  1637. if filecmp.cmp(stock_hook, dst, shallow=False):
  1638. os.remove(dst)
  1639. else:
  1640. _error("%s: Not replacing %s hook", self.relpath, name)
  1641. continue
  1642. try:
  1643. os.symlink(os.path.relpath(stock_hook, os.path.dirname(dst)), dst)
  1644. except OSError as e:
  1645. if e.errno == errno.EPERM:
  1646. raise GitError('filesystem must support symlinks')
  1647. else:
  1648. raise
  1649. def _InitRemote(self):
  1650. if self.remote.url:
  1651. remote = self.GetRemote(self.remote.name)
  1652. remote.url = self.remote.url
  1653. remote.review = self.remote.review
  1654. remote.projectname = self.name
  1655. if self.worktree:
  1656. remote.ResetFetch(mirror=False)
  1657. else:
  1658. remote.ResetFetch(mirror=True)
  1659. remote.Save()
  1660. def _InitMRef(self):
  1661. if self.manifest.branch:
  1662. self._InitAnyMRef(R_M + self.manifest.branch)
  1663. def _InitMirrorHead(self):
  1664. self._InitAnyMRef(HEAD)
  1665. def _InitAnyMRef(self, ref):
  1666. cur = self.bare_ref.symref(ref)
  1667. if self.revisionId:
  1668. if cur != '' or self.bare_ref.get(ref) != self.revisionId:
  1669. msg = 'manifest set to %s' % self.revisionId
  1670. dst = self.revisionId + '^0'
  1671. self.bare_git.UpdateRef(ref, dst, message = msg, detach = True)
  1672. else:
  1673. remote = self.GetRemote(self.remote.name)
  1674. dst = remote.ToLocal(self.revisionExpr)
  1675. if cur != dst:
  1676. msg = 'manifest set to %s' % self.revisionExpr
  1677. self.bare_git.symbolic_ref('-m', msg, ref, dst)
  1678. def _InitWorkTree(self):
  1679. dotgit = os.path.join(self.worktree, '.git')
  1680. if not os.path.exists(dotgit):
  1681. os.makedirs(dotgit)
  1682. for name in ['config',
  1683. 'description',
  1684. 'hooks',
  1685. 'info',
  1686. 'logs',
  1687. 'objects',
  1688. 'packed-refs',
  1689. 'refs',
  1690. 'rr-cache',
  1691. 'svn']:
  1692. try:
  1693. src = os.path.join(self.gitdir, name)
  1694. dst = os.path.join(dotgit, name)
  1695. if os.path.islink(dst) or not os.path.exists(dst):
  1696. os.symlink(os.path.relpath(src, os.path.dirname(dst)), dst)
  1697. else:
  1698. raise GitError('cannot overwrite a local work tree')
  1699. except OSError as e:
  1700. if e.errno == errno.EPERM:
  1701. raise GitError('filesystem must support symlinks')
  1702. else:
  1703. raise
  1704. _lwrite(os.path.join(dotgit, HEAD), '%s\n' % self.GetRevisionId())
  1705. cmd = ['read-tree', '--reset', '-u']
  1706. cmd.append('-v')
  1707. cmd.append(HEAD)
  1708. if GitCommand(self, cmd).Wait() != 0:
  1709. raise GitError("cannot initialize work tree")
  1710. rr_cache = os.path.join(self.gitdir, 'rr-cache')
  1711. if not os.path.exists(rr_cache):
  1712. os.makedirs(rr_cache)
  1713. self._CopyFiles()
  1714. def _gitdir_path(self, path):
  1715. return os.path.join(self.gitdir, path)
  1716. def _revlist(self, *args, **kw):
  1717. a = []
  1718. a.extend(args)
  1719. a.append('--')
  1720. return self.work_git.rev_list(*a, **kw)
  1721. @property
  1722. def _allrefs(self):
  1723. return self.bare_ref.all
  1724. class _GitGetByExec(object):
  1725. def __init__(self, project, bare):
  1726. self._project = project
  1727. self._bare = bare
  1728. def LsOthers(self):
  1729. p = GitCommand(self._project,
  1730. ['ls-files',
  1731. '-z',
  1732. '--others',
  1733. '--exclude-standard'],
  1734. bare = False,
  1735. capture_stdout = True,
  1736. capture_stderr = True)
  1737. if p.Wait() == 0:
  1738. out = p.stdout
  1739. if out:
  1740. return out[:-1].split('\0') # pylint: disable=W1401
  1741. # Backslash is not anomalous
  1742. return []
  1743. def DiffZ(self, name, *args):
  1744. cmd = [name]
  1745. cmd.append('-z')
  1746. cmd.extend(args)
  1747. p = GitCommand(self._project,
  1748. cmd,
  1749. bare = False,
  1750. capture_stdout = True,
  1751. capture_stderr = True)
  1752. try:
  1753. out = p.process.stdout.read()
  1754. r = {}
  1755. if out:
  1756. out = iter(out[:-1].split('\0')) # pylint: disable=W1401
  1757. while out:
  1758. try:
  1759. info = out.next()
  1760. path = out.next()
  1761. except StopIteration:
  1762. break
  1763. class _Info(object):
  1764. def __init__(self, path, omode, nmode, oid, nid, state):
  1765. self.path = path
  1766. self.src_path = None
  1767. self.old_mode = omode
  1768. self.new_mode = nmode
  1769. self.old_id = oid
  1770. self.new_id = nid
  1771. if len(state) == 1:
  1772. self.status = state
  1773. self.level = None
  1774. else:
  1775. self.status = state[:1]
  1776. self.level = state[1:]
  1777. while self.level.startswith('0'):
  1778. self.level = self.level[1:]
  1779. info = info[1:].split(' ')
  1780. info = _Info(path, *info)
  1781. if info.status in ('R', 'C'):
  1782. info.src_path = info.path
  1783. info.path = out.next()
  1784. r[info.path] = info
  1785. return r
  1786. finally:
  1787. p.Wait()
  1788. def GetHead(self):
  1789. if self._bare:
  1790. path = os.path.join(self._project.gitdir, HEAD)
  1791. else:
  1792. path = os.path.join(self._project.worktree, '.git', HEAD)
  1793. try:
  1794. fd = open(path, 'rb')
  1795. except IOError:
  1796. raise NoManifestException(path)
  1797. try:
  1798. line = fd.read()
  1799. finally:
  1800. fd.close()
  1801. if line.startswith('ref: '):
  1802. return line[5:-1]
  1803. return line[:-1]
  1804. def SetHead(self, ref, message=None):
  1805. cmdv = []
  1806. if message is not None:
  1807. cmdv.extend(['-m', message])
  1808. cmdv.append(HEAD)
  1809. cmdv.append(ref)
  1810. self.symbolic_ref(*cmdv)
  1811. def DetachHead(self, new, message=None):
  1812. cmdv = ['--no-deref']
  1813. if message is not None:
  1814. cmdv.extend(['-m', message])
  1815. cmdv.append(HEAD)
  1816. cmdv.append(new)
  1817. self.update_ref(*cmdv)
  1818. def UpdateRef(self, name, new, old=None,
  1819. message=None,
  1820. detach=False):
  1821. cmdv = []
  1822. if message is not None:
  1823. cmdv.extend(['-m', message])
  1824. if detach:
  1825. cmdv.append('--no-deref')
  1826. cmdv.append(name)
  1827. cmdv.append(new)
  1828. if old is not None:
  1829. cmdv.append(old)
  1830. self.update_ref(*cmdv)
  1831. def DeleteRef(self, name, old=None):
  1832. if not old:
  1833. old = self.rev_parse(name)
  1834. self.update_ref('-d', name, old)
  1835. self._project.bare_ref.deleted(name)
  1836. def rev_list(self, *args, **kw):
  1837. if 'format' in kw:
  1838. cmdv = ['log', '--pretty=format:%s' % kw['format']]
  1839. else:
  1840. cmdv = ['rev-list']
  1841. cmdv.extend(args)
  1842. p = GitCommand(self._project,
  1843. cmdv,
  1844. bare = self._bare,
  1845. capture_stdout = True,
  1846. capture_stderr = True)
  1847. r = []
  1848. for line in p.process.stdout:
  1849. if line[-1] == '\n':
  1850. line = line[:-1]
  1851. r.append(line)
  1852. if p.Wait() != 0:
  1853. raise GitError('%s rev-list %s: %s' % (
  1854. self._project.name,
  1855. str(args),
  1856. p.stderr))
  1857. return r
  1858. def __getattr__(self, name):
  1859. """Allow arbitrary git commands using pythonic syntax.
  1860. This allows you to do things like:
  1861. git_obj.rev_parse('HEAD')
  1862. Since we don't have a 'rev_parse' method defined, the __getattr__ will
  1863. run. We'll replace the '_' with a '-' and try to run a git command.
  1864. Any other positional arguments will be passed to the git command, and the
  1865. following keyword arguments are supported:
  1866. config: An optional dict of git config options to be passed with '-c'.
  1867. Args:
  1868. name: The name of the git command to call. Any '_' characters will
  1869. be replaced with '-'.
  1870. Returns:
  1871. A callable object that will try to call git with the named command.
  1872. """
  1873. name = name.replace('_', '-')
  1874. def runner(*args, **kwargs):
  1875. cmdv = []
  1876. config = kwargs.pop('config', None)
  1877. for k in kwargs:
  1878. raise TypeError('%s() got an unexpected keyword argument %r'
  1879. % (name, k))
  1880. if config is not None:
  1881. if not git_require((1, 7, 2)):
  1882. raise ValueError('cannot set config on command line for %s()'
  1883. % name)
  1884. for k, v in config.iteritems():
  1885. cmdv.append('-c')
  1886. cmdv.append('%s=%s' % (k, v))
  1887. cmdv.append(name)
  1888. cmdv.extend(args)
  1889. p = GitCommand(self._project,
  1890. cmdv,
  1891. bare = self._bare,
  1892. capture_stdout = True,
  1893. capture_stderr = True)
  1894. if p.Wait() != 0:
  1895. raise GitError('%s %s: %s' % (
  1896. self._project.name,
  1897. name,
  1898. p.stderr))
  1899. r = p.stdout
  1900. if r.endswith('\n') and r.index('\n') == len(r) - 1:
  1901. return r[:-1]
  1902. return r
  1903. return runner
  1904. class _PriorSyncFailedError(Exception):
  1905. def __str__(self):
  1906. return 'prior sync failed; rebase still in progress'
  1907. class _DirtyError(Exception):
  1908. def __str__(self):
  1909. return 'contains uncommitted changes'
  1910. class _InfoMessage(object):
  1911. def __init__(self, project, text):
  1912. self.project = project
  1913. self.text = text
  1914. def Print(self, syncbuf):
  1915. syncbuf.out.info('%s/: %s', self.project.relpath, self.text)
  1916. syncbuf.out.nl()
  1917. class _Failure(object):
  1918. def __init__(self, project, why):
  1919. self.project = project
  1920. self.why = why
  1921. def Print(self, syncbuf):
  1922. syncbuf.out.fail('error: %s/: %s',
  1923. self.project.relpath,
  1924. str(self.why))
  1925. syncbuf.out.nl()
  1926. class _Later(object):
  1927. def __init__(self, project, action):
  1928. self.project = project
  1929. self.action = action
  1930. def Run(self, syncbuf):
  1931. out = syncbuf.out
  1932. out.project('project %s/', self.project.relpath)
  1933. out.nl()
  1934. try:
  1935. self.action()
  1936. out.nl()
  1937. return True
  1938. except GitError:
  1939. out.nl()
  1940. return False
  1941. class _SyncColoring(Coloring):
  1942. def __init__(self, config):
  1943. Coloring.__init__(self, config, 'reposync')
  1944. self.project = self.printer('header', attr = 'bold')
  1945. self.info = self.printer('info')
  1946. self.fail = self.printer('fail', fg='red')
  1947. class SyncBuffer(object):
  1948. def __init__(self, config, detach_head=False):
  1949. self._messages = []
  1950. self._failures = []
  1951. self._later_queue1 = []
  1952. self._later_queue2 = []
  1953. self.out = _SyncColoring(config)
  1954. self.out.redirect(sys.stderr)
  1955. self.detach_head = detach_head
  1956. self.clean = True
  1957. def info(self, project, fmt, *args):
  1958. self._messages.append(_InfoMessage(project, fmt % args))
  1959. def fail(self, project, err=None):
  1960. self._failures.append(_Failure(project, err))
  1961. self.clean = False
  1962. def later1(self, project, what):
  1963. self._later_queue1.append(_Later(project, what))
  1964. def later2(self, project, what):
  1965. self._later_queue2.append(_Later(project, what))
  1966. def Finish(self):
  1967. self._PrintMessages()
  1968. self._RunLater()
  1969. self._PrintMessages()
  1970. return self.clean
  1971. def _RunLater(self):
  1972. for q in ['_later_queue1', '_later_queue2']:
  1973. if not self._RunQueue(q):
  1974. return
  1975. def _RunQueue(self, queue):
  1976. for m in getattr(self, queue):
  1977. if not m.Run(self):
  1978. self.clean = False
  1979. return False
  1980. setattr(self, queue, [])
  1981. return True
  1982. def _PrintMessages(self):
  1983. for m in self._messages:
  1984. m.Print(self)
  1985. for m in self._failures:
  1986. m.Print(self)
  1987. self._messages = []
  1988. self._failures = []
  1989. class MetaProject(Project):
  1990. """A special project housed under .repo.
  1991. """
  1992. def __init__(self, manifest, name, gitdir, worktree):
  1993. Project.__init__(self,
  1994. manifest = manifest,
  1995. name = name,
  1996. gitdir = gitdir,
  1997. worktree = worktree,
  1998. remote = RemoteSpec('origin'),
  1999. relpath = '.repo/%s' % name,
  2000. revisionExpr = 'refs/heads/master',
  2001. revisionId = None,
  2002. groups = None)
  2003. def PreSync(self):
  2004. if self.Exists:
  2005. cb = self.CurrentBranch
  2006. if cb:
  2007. base = self.GetBranch(cb).merge
  2008. if base:
  2009. self.revisionExpr = base
  2010. self.revisionId = None
  2011. def MetaBranchSwitch(self, target):
  2012. """ Prepare MetaProject for manifest branch switch
  2013. """
  2014. # detach and delete manifest branch, allowing a new
  2015. # branch to take over
  2016. syncbuf = SyncBuffer(self.config, detach_head = True)
  2017. self.Sync_LocalHalf(syncbuf)
  2018. syncbuf.Finish()
  2019. return GitCommand(self,
  2020. ['update-ref', '-d', 'refs/heads/default'],
  2021. capture_stdout = True,
  2022. capture_stderr = True).Wait() == 0
  2023. @property
  2024. def LastFetch(self):
  2025. try:
  2026. fh = os.path.join(self.gitdir, 'FETCH_HEAD')
  2027. return os.path.getmtime(fh)
  2028. except OSError:
  2029. return 0
  2030. @property
  2031. def HasChanges(self):
  2032. """Has the remote received new commits not yet checked out?
  2033. """
  2034. if not self.remote or not self.revisionExpr:
  2035. return False
  2036. all_refs = self.bare_ref.all
  2037. revid = self.GetRevisionId(all_refs)
  2038. head = self.work_git.GetHead()
  2039. if head.startswith(R_HEADS):
  2040. try:
  2041. head = all_refs[head]
  2042. except KeyError:
  2043. head = None
  2044. if revid == head:
  2045. return False
  2046. elif self._revlist(not_rev(HEAD), revid):
  2047. return True
  2048. return False