project.py 88 KB

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