project.py 89 KB

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