project.py 85 KB

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