project.py 70 KB

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