project.py 87 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838
  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, ID_RE
  32. from error import GitError, HookError, UploadError, DownloadError
  33. from error import ManifestInvalidRevisionError
  34. from error import NoManifestException
  35. from trace import IsTrace, Trace
  36. from git_refs import GitRefs, HEAD, R_HEADS, R_TAGS, R_PUB, R_M
  37. from pyversion import is_python3
  38. if not is_python3():
  39. # pylint:disable=W0622
  40. input = raw_input
  41. # pylint:enable=W0622
  42. def _lwrite(path, content):
  43. lock = '%s.lock' % path
  44. fd = open(lock, 'w')
  45. try:
  46. fd.write(content)
  47. finally:
  48. fd.close()
  49. try:
  50. os.rename(lock, path)
  51. except OSError:
  52. os.remove(lock)
  53. raise
  54. def _error(fmt, *args):
  55. msg = fmt % args
  56. print('error: %s' % msg, file=sys.stderr)
  57. def _warn(fmt, *args):
  58. msg = fmt % args
  59. print('warn: %s' % msg, file=sys.stderr)
  60. def not_rev(r):
  61. return '^' + r
  62. def sq(r):
  63. return "'" + r.replace("'", "'\''") + "'"
  64. _project_hook_list = None
  65. def _ProjectHooks():
  66. """List the hooks present in the 'hooks' directory.
  67. These hooks are project hooks and are copied to the '.git/hooks' directory
  68. of all subprojects.
  69. This function caches the list of hooks (based on the contents of the
  70. 'repo/hooks' directory) on the first call.
  71. Returns:
  72. A list of absolute paths to all of the files in the hooks directory.
  73. """
  74. global _project_hook_list
  75. if _project_hook_list is None:
  76. d = os.path.realpath(os.path.abspath(os.path.dirname(__file__)))
  77. d = os.path.join(d, 'hooks')
  78. _project_hook_list = [os.path.join(d, x) for x in os.listdir(d)]
  79. return _project_hook_list
  80. class DownloadedChange(object):
  81. _commit_cache = None
  82. def __init__(self, project, base, change_id, ps_id, commit):
  83. self.project = project
  84. self.base = base
  85. self.change_id = change_id
  86. self.ps_id = ps_id
  87. self.commit = commit
  88. @property
  89. def commits(self):
  90. if self._commit_cache is None:
  91. self._commit_cache = self.project.bare_git.rev_list(
  92. '--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(
  114. '--abbrev=8',
  115. '--abbrev-commit',
  116. '--pretty=oneline',
  117. '--reverse',
  118. '--date-order',
  119. not_rev(self.base),
  120. R_HEADS + self.name,
  121. '--')
  122. return self._commit_cache
  123. @property
  124. def unabbrev_commits(self):
  125. r = dict()
  126. for commit in self.project.bare_git.rev_list(
  127. not_rev(self.base),
  128. R_HEADS + self.name,
  129. '--'):
  130. r[commit[0:8]] = commit
  131. return r
  132. @property
  133. def date(self):
  134. return self.project.bare_git.log(
  135. '--pretty=format:%cd',
  136. '-n', '1',
  137. R_HEADS + self.name,
  138. '--')
  139. def UploadForReview(self, people, auto_topic=False, draft=False, 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)? ') % (
  371. self._GetMustVerb(), 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.' % (
  433. traceback.format_exc(), 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
  454. (self._hook_type not in 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(
  548. gitdir=self.gitdir,
  549. defaults=self.manifest.globalConfig)
  550. if self.worktree:
  551. self.work_git = self._GitGetByExec(self, bare=False, gitdir=gitdir)
  552. else:
  553. self.work_git = None
  554. self.bare_git = self._GitGetByExec(self, bare=True, gitdir=gitdir)
  555. self.bare_ref = GitRefs(gitdir)
  556. self.bare_objdir = self._GitGetByExec(self, bare=True, gitdir=objdir)
  557. self.dest_branch = dest_branch
  558. self.old_revision = old_revision
  559. # This will be filled in if a project is later identified to be the
  560. # project containing repo hooks.
  561. self.enabled_repo_hooks = []
  562. @property
  563. def Derived(self):
  564. return self.is_derived
  565. @property
  566. def Exists(self):
  567. return os.path.isdir(self.gitdir) and os.path.isdir(self.objdir)
  568. @property
  569. def CurrentBranch(self):
  570. """Obtain the name of the currently checked out branch.
  571. The branch name omits the 'refs/heads/' prefix.
  572. None is returned if the project is on a detached HEAD.
  573. """
  574. b = self.work_git.GetHead()
  575. if b.startswith(R_HEADS):
  576. return b[len(R_HEADS):]
  577. return None
  578. def IsRebaseInProgress(self):
  579. w = self.worktree
  580. g = os.path.join(w, '.git')
  581. return os.path.exists(os.path.join(g, 'rebase-apply')) \
  582. or os.path.exists(os.path.join(g, 'rebase-merge')) \
  583. or os.path.exists(os.path.join(w, '.dotest'))
  584. def IsDirty(self, consider_untracked=True):
  585. """Is the working directory modified in some way?
  586. """
  587. self.work_git.update_index('-q',
  588. '--unmerged',
  589. '--ignore-missing',
  590. '--refresh')
  591. if self.work_git.DiffZ('diff-index', '-M', '--cached', HEAD):
  592. return True
  593. if self.work_git.DiffZ('diff-files'):
  594. return True
  595. if consider_untracked and self.work_git.LsOthers():
  596. return True
  597. return False
  598. _userident_name = None
  599. _userident_email = None
  600. @property
  601. def UserName(self):
  602. """Obtain the user's personal name.
  603. """
  604. if self._userident_name is None:
  605. self._LoadUserIdentity()
  606. return self._userident_name
  607. @property
  608. def UserEmail(self):
  609. """Obtain the user's email address. This is very likely
  610. to be their Gerrit login.
  611. """
  612. if self._userident_email is None:
  613. self._LoadUserIdentity()
  614. return self._userident_email
  615. def _LoadUserIdentity(self):
  616. u = self.bare_git.var('GIT_COMMITTER_IDENT')
  617. m = re.compile("^(.*) <([^>]*)> ").match(u)
  618. if m:
  619. self._userident_name = m.group(1)
  620. self._userident_email = m.group(2)
  621. else:
  622. self._userident_name = ''
  623. self._userident_email = ''
  624. def GetRemote(self, name):
  625. """Get the configuration for a single remote.
  626. """
  627. return self.config.GetRemote(name)
  628. def GetBranch(self, name):
  629. """Get the configuration for a single branch.
  630. """
  631. return self.config.GetBranch(name)
  632. def GetBranches(self):
  633. """Get all existing local branches.
  634. """
  635. current = self.CurrentBranch
  636. all_refs = self._allrefs
  637. heads = {}
  638. for name, ref_id in all_refs.items():
  639. if name.startswith(R_HEADS):
  640. name = name[len(R_HEADS):]
  641. b = self.GetBranch(name)
  642. b.current = name == current
  643. b.published = None
  644. b.revision = ref_id
  645. heads[name] = b
  646. for name, ref_id in all_refs.items():
  647. if name.startswith(R_PUB):
  648. name = name[len(R_PUB):]
  649. b = heads.get(name)
  650. if b:
  651. b.published = ref_id
  652. return heads
  653. def MatchesGroups(self, manifest_groups):
  654. """Returns true if the manifest groups specified at init should cause
  655. this project to be synced.
  656. Prefixing a manifest group with "-" inverts the meaning of a group.
  657. All projects are implicitly labelled with "all".
  658. labels are resolved in order. In the example case of
  659. project_groups: "all,group1,group2"
  660. manifest_groups: "-group1,group2"
  661. the project will be matched.
  662. The special manifest group "default" will match any project that
  663. does not have the special project group "notdefault"
  664. """
  665. expanded_manifest_groups = manifest_groups or ['default']
  666. expanded_project_groups = ['all'] + (self.groups or [])
  667. if not 'notdefault' in expanded_project_groups:
  668. expanded_project_groups += ['default']
  669. matched = False
  670. for group in expanded_manifest_groups:
  671. if group.startswith('-') and group[1:] in expanded_project_groups:
  672. matched = False
  673. elif group in expanded_project_groups:
  674. matched = True
  675. return matched
  676. ## Status Display ##
  677. def UncommitedFiles(self, get_all=True):
  678. """Returns a list of strings, uncommitted files in the git tree.
  679. Args:
  680. get_all: a boolean, if True - get information about all different
  681. uncommitted files. If False - return as soon as any kind of
  682. uncommitted files is detected.
  683. """
  684. details = []
  685. self.work_git.update_index('-q',
  686. '--unmerged',
  687. '--ignore-missing',
  688. '--refresh')
  689. if self.IsRebaseInProgress():
  690. details.append("rebase in progress")
  691. if not get_all:
  692. return details
  693. changes = self.work_git.DiffZ('diff-index', '--cached', HEAD).keys()
  694. if changes:
  695. details.extend(changes)
  696. if not get_all:
  697. return details
  698. changes = self.work_git.DiffZ('diff-files').keys()
  699. if changes:
  700. details.extend(changes)
  701. if not get_all:
  702. return details
  703. changes = self.work_git.LsOthers()
  704. if changes:
  705. details.extend(changes)
  706. return details
  707. def HasChanges(self):
  708. """Returns true if there are uncommitted changes.
  709. """
  710. if self.UncommitedFiles(get_all=False):
  711. return True
  712. else:
  713. return False
  714. def PrintWorkTreeStatus(self, output_redir=None):
  715. """Prints the status of the repository to stdout.
  716. Args:
  717. output: If specified, redirect the output to this object.
  718. """
  719. if not os.path.isdir(self.worktree):
  720. if output_redir == None:
  721. output_redir = sys.stdout
  722. print(file=output_redir)
  723. print('project %s/' % self.relpath, file=output_redir)
  724. print(' missing (run "repo sync")', file=output_redir)
  725. return
  726. self.work_git.update_index('-q',
  727. '--unmerged',
  728. '--ignore-missing',
  729. '--refresh')
  730. rb = self.IsRebaseInProgress()
  731. di = self.work_git.DiffZ('diff-index', '-M', '--cached', HEAD)
  732. df = self.work_git.DiffZ('diff-files')
  733. do = self.work_git.LsOthers()
  734. if not rb and not di and not df and not do and not self.CurrentBranch:
  735. return 'CLEAN'
  736. out = StatusColoring(self.config)
  737. if not output_redir == None:
  738. out.redirect(output_redir)
  739. out.project('project %-40s', self.relpath + '/ ')
  740. branch = self.CurrentBranch
  741. if branch is None:
  742. out.nobranch('(*** NO BRANCH ***)')
  743. else:
  744. out.branch('branch %s', branch)
  745. out.nl()
  746. if rb:
  747. out.important('prior sync failed; rebase still in progress')
  748. out.nl()
  749. paths = list()
  750. paths.extend(di.keys())
  751. paths.extend(df.keys())
  752. paths.extend(do)
  753. for p in sorted(set(paths)):
  754. try:
  755. i = di[p]
  756. except KeyError:
  757. i = None
  758. try:
  759. f = df[p]
  760. except KeyError:
  761. f = None
  762. if i:
  763. i_status = i.status.upper()
  764. else:
  765. i_status = '-'
  766. if f:
  767. f_status = f.status.lower()
  768. else:
  769. f_status = '-'
  770. if i and i.src_path:
  771. line = ' %s%s\t%s => %s (%s%%)' % (i_status, f_status,
  772. i.src_path, p, i.level)
  773. else:
  774. line = ' %s%s\t%s' % (i_status, f_status, p)
  775. if i and not f:
  776. out.added('%s', line)
  777. elif (i and f) or (not i and f):
  778. out.changed('%s', line)
  779. elif not i and not f:
  780. out.untracked('%s', line)
  781. else:
  782. out.write('%s', line)
  783. out.nl()
  784. return 'DIRTY'
  785. def PrintWorkTreeDiff(self, absolute_paths=False):
  786. """Prints the status of the repository to stdout.
  787. """
  788. out = DiffColoring(self.config)
  789. cmd = ['diff']
  790. if out.is_on:
  791. cmd.append('--color')
  792. cmd.append(HEAD)
  793. if absolute_paths:
  794. cmd.append('--src-prefix=a/%s/' % self.relpath)
  795. cmd.append('--dst-prefix=b/%s/' % self.relpath)
  796. cmd.append('--')
  797. p = GitCommand(self,
  798. cmd,
  799. capture_stdout=True,
  800. capture_stderr=True)
  801. has_diff = False
  802. for line in p.process.stdout:
  803. if not has_diff:
  804. out.nl()
  805. out.project('project %s/' % self.relpath)
  806. out.nl()
  807. has_diff = True
  808. print(line[:-1])
  809. p.Wait()
  810. ## Publish / Upload ##
  811. def WasPublished(self, branch, all_refs=None):
  812. """Was the branch published (uploaded) for code review?
  813. If so, returns the SHA-1 hash of the last published
  814. state for the branch.
  815. """
  816. key = R_PUB + branch
  817. if all_refs is None:
  818. try:
  819. return self.bare_git.rev_parse(key)
  820. except GitError:
  821. return None
  822. else:
  823. try:
  824. return all_refs[key]
  825. except KeyError:
  826. return None
  827. def CleanPublishedCache(self, all_refs=None):
  828. """Prunes any stale published refs.
  829. """
  830. if all_refs is None:
  831. all_refs = self._allrefs
  832. heads = set()
  833. canrm = {}
  834. for name, ref_id in all_refs.items():
  835. if name.startswith(R_HEADS):
  836. heads.add(name)
  837. elif name.startswith(R_PUB):
  838. canrm[name] = ref_id
  839. for name, ref_id in canrm.items():
  840. n = name[len(R_PUB):]
  841. if R_HEADS + n not in heads:
  842. self.bare_git.DeleteRef(name, ref_id)
  843. def GetUploadableBranches(self, selected_branch=None):
  844. """List any branches which can be uploaded for review.
  845. """
  846. heads = {}
  847. pubed = {}
  848. for name, ref_id in self._allrefs.items():
  849. if name.startswith(R_HEADS):
  850. heads[name[len(R_HEADS):]] = ref_id
  851. elif name.startswith(R_PUB):
  852. pubed[name[len(R_PUB):]] = ref_id
  853. ready = []
  854. for branch, ref_id in heads.items():
  855. if branch in pubed and pubed[branch] == ref_id:
  856. continue
  857. if selected_branch and branch != selected_branch:
  858. continue
  859. rb = self.GetUploadableBranch(branch)
  860. if rb:
  861. ready.append(rb)
  862. return ready
  863. def GetUploadableBranch(self, branch_name):
  864. """Get a single uploadable branch, or None.
  865. """
  866. branch = self.GetBranch(branch_name)
  867. base = branch.LocalMerge
  868. if branch.LocalMerge:
  869. rb = ReviewableBranch(self, branch, base)
  870. if rb.commits:
  871. return rb
  872. return None
  873. def UploadForReview(self, branch=None,
  874. people=([], []),
  875. auto_topic=False,
  876. draft=False,
  877. dest_branch=None):
  878. """Uploads the named branch for code review.
  879. """
  880. if branch is None:
  881. branch = self.CurrentBranch
  882. if branch is None:
  883. raise GitError('not currently on a branch')
  884. branch = self.GetBranch(branch)
  885. if not branch.LocalMerge:
  886. raise GitError('branch %s does not track a remote' % branch.name)
  887. if not branch.remote.review:
  888. raise GitError('remote %s has no review url' % branch.remote.name)
  889. if dest_branch is None:
  890. dest_branch = self.dest_branch
  891. if dest_branch is None:
  892. dest_branch = branch.merge
  893. if not dest_branch.startswith(R_HEADS):
  894. dest_branch = R_HEADS + dest_branch
  895. if not branch.remote.projectname:
  896. branch.remote.projectname = self.name
  897. branch.remote.Save()
  898. url = branch.remote.ReviewUrl(self.UserEmail)
  899. if url is None:
  900. raise UploadError('review not configured')
  901. cmd = ['push']
  902. if url.startswith('ssh://'):
  903. rp = ['gerrit receive-pack']
  904. for e in people[0]:
  905. rp.append('--reviewer=%s' % sq(e))
  906. for e in people[1]:
  907. rp.append('--cc=%s' % sq(e))
  908. cmd.append('--receive-pack=%s' % " ".join(rp))
  909. cmd.append(url)
  910. if dest_branch.startswith(R_HEADS):
  911. dest_branch = dest_branch[len(R_HEADS):]
  912. upload_type = 'for'
  913. if draft:
  914. upload_type = 'drafts'
  915. ref_spec = '%s:refs/%s/%s' % (R_HEADS + branch.name, upload_type,
  916. dest_branch)
  917. if auto_topic:
  918. ref_spec = ref_spec + '/' + branch.name
  919. if not url.startswith('ssh://'):
  920. rp = ['r=%s' % p for p in people[0]] + \
  921. ['cc=%s' % p for p in people[1]]
  922. if rp:
  923. ref_spec = ref_spec + '%' + ','.join(rp)
  924. cmd.append(ref_spec)
  925. if GitCommand(self, cmd, bare=True).Wait() != 0:
  926. raise UploadError('Upload failed')
  927. msg = "posted to %s for %s" % (branch.remote.review, dest_branch)
  928. self.bare_git.UpdateRef(R_PUB + branch.name,
  929. R_HEADS + branch.name,
  930. message=msg)
  931. ## Sync ##
  932. def _ExtractArchive(self, tarpath, path=None):
  933. """Extract the given tar on its current location
  934. Args:
  935. - tarpath: The path to the actual tar file
  936. """
  937. try:
  938. with tarfile.open(tarpath, 'r') as tar:
  939. tar.extractall(path=path)
  940. return True
  941. except (IOError, tarfile.TarError) as e:
  942. _error("Cannot extract archive %s: %s", tarpath, str(e))
  943. return False
  944. def Sync_NetworkHalf(self,
  945. quiet=False,
  946. is_new=None,
  947. current_branch_only=False,
  948. force_sync=False,
  949. clone_bundle=True,
  950. no_tags=False,
  951. archive=False,
  952. optimized_fetch=False,
  953. prune=False):
  954. """Perform only the network IO portion of the sync process.
  955. Local working directory/branch state is not affected.
  956. """
  957. if archive and not isinstance(self, MetaProject):
  958. if self.remote.url.startswith(('http://', 'https://')):
  959. _error("%s: Cannot fetch archives from http/https remotes.", self.name)
  960. return False
  961. name = self.relpath.replace('\\', '/')
  962. name = name.replace('/', '_')
  963. tarpath = '%s.tar' % name
  964. topdir = self.manifest.topdir
  965. try:
  966. self._FetchArchive(tarpath, cwd=topdir)
  967. except GitError as e:
  968. _error('%s', e)
  969. return False
  970. # From now on, we only need absolute tarpath
  971. tarpath = os.path.join(topdir, tarpath)
  972. if not self._ExtractArchive(tarpath, path=topdir):
  973. return False
  974. try:
  975. os.remove(tarpath)
  976. except OSError as e:
  977. _warn("Cannot remove archive %s: %s", tarpath, str(e))
  978. self._CopyAndLinkFiles()
  979. return True
  980. if is_new is None:
  981. is_new = not self.Exists
  982. if is_new:
  983. self._InitGitDir(force_sync=force_sync)
  984. else:
  985. self._UpdateHooks()
  986. self._InitRemote()
  987. if is_new:
  988. alt = os.path.join(self.gitdir, 'objects/info/alternates')
  989. try:
  990. fd = open(alt, 'rb')
  991. try:
  992. alt_dir = fd.readline().rstrip()
  993. finally:
  994. fd.close()
  995. except IOError:
  996. alt_dir = None
  997. else:
  998. alt_dir = None
  999. if clone_bundle \
  1000. and alt_dir is None \
  1001. and self._ApplyCloneBundle(initial=is_new, quiet=quiet):
  1002. is_new = False
  1003. if not current_branch_only:
  1004. if self.sync_c:
  1005. current_branch_only = True
  1006. elif not self.manifest._loaded:
  1007. # Manifest cannot check defaults until it syncs.
  1008. current_branch_only = False
  1009. elif self.manifest.default.sync_c:
  1010. current_branch_only = True
  1011. need_to_fetch = not (optimized_fetch and \
  1012. (ID_RE.match(self.revisionExpr) and self._CheckForSha1()))
  1013. if (need_to_fetch
  1014. and 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(
  1047. 'revision %s in %s not found' % (self.revisionExpr,
  1048. self.name))
  1049. def GetRevisionId(self, all_refs=None):
  1050. if self.revisionId:
  1051. return self.revisionId
  1052. rem = self.GetRemote(self.remote.name)
  1053. rev = rem.ToLocal(self.revisionExpr)
  1054. if all_refs is not None and rev in all_refs:
  1055. return all_refs[rev]
  1056. try:
  1057. return self.bare_git.rev_parse('--verify', '%s^0' % rev)
  1058. except GitError:
  1059. raise ManifestInvalidRevisionError(
  1060. 'revision %s in %s not found' % (self.revisionExpr,
  1061. self.name))
  1062. def Sync_LocalHalf(self, syncbuf, force_sync=False):
  1063. """Perform only the local IO portion of the sync process.
  1064. Network access is not required.
  1065. """
  1066. self._InitWorkTree(force_sync=force_sync)
  1067. all_refs = self.bare_ref.all
  1068. self.CleanPublishedCache(all_refs)
  1069. revid = self.GetRevisionId(all_refs)
  1070. def _doff():
  1071. self._FastForward(revid)
  1072. self._CopyAndLinkFiles()
  1073. head = self.work_git.GetHead()
  1074. if head.startswith(R_HEADS):
  1075. branch = head[len(R_HEADS):]
  1076. try:
  1077. head = all_refs[head]
  1078. except KeyError:
  1079. head = None
  1080. else:
  1081. branch = None
  1082. if branch is None or syncbuf.detach_head:
  1083. # Currently on a detached HEAD. The user is assumed to
  1084. # not have any local modifications worth worrying about.
  1085. #
  1086. if self.IsRebaseInProgress():
  1087. syncbuf.fail(self, _PriorSyncFailedError())
  1088. return
  1089. if head == revid:
  1090. # No changes; don't do anything further.
  1091. # Except if the head needs to be detached
  1092. #
  1093. if not syncbuf.detach_head:
  1094. # The copy/linkfile config may have changed.
  1095. self._CopyAndLinkFiles()
  1096. return
  1097. else:
  1098. lost = self._revlist(not_rev(revid), HEAD)
  1099. if lost:
  1100. syncbuf.info(self, "discarding %d commits", len(lost))
  1101. try:
  1102. self._Checkout(revid, quiet=True)
  1103. except GitError as e:
  1104. syncbuf.fail(self, e)
  1105. return
  1106. self._CopyAndLinkFiles()
  1107. return
  1108. if head == revid:
  1109. # No changes; don't do anything further.
  1110. #
  1111. # The copy/linkfile config may have changed.
  1112. self._CopyAndLinkFiles()
  1113. return
  1114. branch = self.GetBranch(branch)
  1115. if not branch.LocalMerge:
  1116. # The current branch has no tracking configuration.
  1117. # Jump off it to a detached HEAD.
  1118. #
  1119. syncbuf.info(self,
  1120. "leaving %s; does not track upstream",
  1121. branch.name)
  1122. try:
  1123. self._Checkout(revid, quiet=True)
  1124. except GitError as e:
  1125. syncbuf.fail(self, e)
  1126. return
  1127. self._CopyAndLinkFiles()
  1128. return
  1129. upstream_gain = self._revlist(not_rev(HEAD), revid)
  1130. pub = self.WasPublished(branch.name, all_refs)
  1131. if pub:
  1132. not_merged = self._revlist(not_rev(revid), pub)
  1133. if not_merged:
  1134. if upstream_gain:
  1135. # The user has published this branch and some of those
  1136. # commits are not yet merged upstream. We do not want
  1137. # to rewrite the published commits so we punt.
  1138. #
  1139. syncbuf.fail(self,
  1140. "branch %s is published (but not merged) and is now %d commits behind"
  1141. % (branch.name, len(upstream_gain)))
  1142. return
  1143. elif pub == head:
  1144. # All published commits are merged, and thus we are a
  1145. # strict subset. We can fast-forward safely.
  1146. #
  1147. syncbuf.later1(self, _doff)
  1148. return
  1149. # Examine the local commits not in the remote. Find the
  1150. # last one attributed to this user, if any.
  1151. #
  1152. local_changes = self._revlist(not_rev(revid), HEAD, format='%H %ce')
  1153. last_mine = None
  1154. cnt_mine = 0
  1155. for commit in local_changes:
  1156. commit_id, committer_email = commit.decode('utf-8').split(' ', 1)
  1157. if committer_email == self.UserEmail:
  1158. last_mine = commit_id
  1159. cnt_mine += 1
  1160. if not upstream_gain and cnt_mine == len(local_changes):
  1161. return
  1162. if self.IsDirty(consider_untracked=False):
  1163. syncbuf.fail(self, _DirtyError())
  1164. return
  1165. # If the upstream switched on us, warn the user.
  1166. #
  1167. if branch.merge != self.revisionExpr:
  1168. if branch.merge and self.revisionExpr:
  1169. syncbuf.info(self,
  1170. 'manifest switched %s...%s',
  1171. branch.merge,
  1172. self.revisionExpr)
  1173. elif branch.merge:
  1174. syncbuf.info(self,
  1175. 'manifest no longer tracks %s',
  1176. branch.merge)
  1177. if cnt_mine < len(local_changes):
  1178. # Upstream rebased. Not everything in HEAD
  1179. # was created by this user.
  1180. #
  1181. syncbuf.info(self,
  1182. "discarding %d commits removed from upstream",
  1183. len(local_changes) - cnt_mine)
  1184. branch.remote = self.GetRemote(self.remote.name)
  1185. if not ID_RE.match(self.revisionExpr):
  1186. # in case of manifest sync the revisionExpr might be a SHA1
  1187. branch.merge = self.revisionExpr
  1188. if not branch.merge.startswith('refs/'):
  1189. branch.merge = R_HEADS + branch.merge
  1190. branch.Save()
  1191. if cnt_mine > 0 and self.rebase:
  1192. def _dorebase():
  1193. self._Rebase(upstream='%s^1' % last_mine, onto=revid)
  1194. self._CopyAndLinkFiles()
  1195. syncbuf.later2(self, _dorebase)
  1196. elif local_changes:
  1197. try:
  1198. self._ResetHard(revid)
  1199. self._CopyAndLinkFiles()
  1200. except GitError as e:
  1201. syncbuf.fail(self, e)
  1202. return
  1203. else:
  1204. syncbuf.later1(self, _doff)
  1205. def AddCopyFile(self, src, dest, absdest):
  1206. # dest should already be an absolute path, but src is project relative
  1207. # make src an absolute path
  1208. abssrc = os.path.join(self.worktree, src)
  1209. self.copyfiles.append(_CopyFile(src, dest, abssrc, absdest))
  1210. def AddLinkFile(self, src, dest, absdest):
  1211. # dest should already be an absolute path, but src is project relative
  1212. # make src relative path to dest
  1213. absdestdir = os.path.dirname(absdest)
  1214. relsrc = os.path.relpath(os.path.join(self.worktree, src), absdestdir)
  1215. self.linkfiles.append(_LinkFile(self.worktree, src, dest, relsrc, absdest))
  1216. def AddAnnotation(self, name, value, keep):
  1217. self.annotations.append(_Annotation(name, value, keep))
  1218. def DownloadPatchSet(self, change_id, patch_id):
  1219. """Download a single patch set of a single change to FETCH_HEAD.
  1220. """
  1221. remote = self.GetRemote(self.remote.name)
  1222. cmd = ['fetch', remote.name]
  1223. cmd.append('refs/changes/%2.2d/%d/%d' \
  1224. % (change_id % 100, change_id, patch_id))
  1225. if GitCommand(self, cmd, bare=True).Wait() != 0:
  1226. return None
  1227. return DownloadedChange(self,
  1228. self.GetRevisionId(),
  1229. change_id,
  1230. patch_id,
  1231. self.bare_git.rev_parse('FETCH_HEAD'))
  1232. ## Branch Management ##
  1233. def StartBranch(self, name, branch_merge=''):
  1234. """Create a new branch off the manifest's revision.
  1235. """
  1236. if not branch_merge:
  1237. branch_merge = self.revisionExpr
  1238. head = self.work_git.GetHead()
  1239. if head == (R_HEADS + name):
  1240. return True
  1241. all_refs = self.bare_ref.all
  1242. if R_HEADS + name in all_refs:
  1243. return GitCommand(self,
  1244. ['checkout', name, '--'],
  1245. capture_stdout=True,
  1246. capture_stderr=True).Wait() == 0
  1247. branch = self.GetBranch(name)
  1248. branch.remote = self.GetRemote(self.remote.name)
  1249. branch.merge = branch_merge
  1250. if not branch.merge.startswith('refs/') and not ID_RE.match(branch_merge):
  1251. branch.merge = R_HEADS + branch_merge
  1252. revid = self.GetRevisionId(all_refs)
  1253. if head.startswith(R_HEADS):
  1254. try:
  1255. head = all_refs[head]
  1256. except KeyError:
  1257. head = None
  1258. if revid and head and revid == head:
  1259. ref = os.path.join(self.gitdir, R_HEADS + name)
  1260. try:
  1261. os.makedirs(os.path.dirname(ref))
  1262. except OSError:
  1263. pass
  1264. _lwrite(ref, '%s\n' % revid)
  1265. _lwrite(os.path.join(self.worktree, '.git', HEAD),
  1266. 'ref: %s%s\n' % (R_HEADS, name))
  1267. branch.Save()
  1268. return True
  1269. if GitCommand(self,
  1270. ['checkout', '-b', branch.name, revid],
  1271. capture_stdout=True,
  1272. capture_stderr=True).Wait() == 0:
  1273. branch.Save()
  1274. return True
  1275. return False
  1276. def CheckoutBranch(self, name):
  1277. """Checkout a local topic branch.
  1278. Args:
  1279. name: The name of the branch to checkout.
  1280. Returns:
  1281. True if the checkout succeeded; False if it didn't; None if the branch
  1282. didn't exist.
  1283. """
  1284. rev = R_HEADS + name
  1285. head = self.work_git.GetHead()
  1286. if head == rev:
  1287. # Already on the branch
  1288. #
  1289. return True
  1290. all_refs = self.bare_ref.all
  1291. try:
  1292. revid = all_refs[rev]
  1293. except KeyError:
  1294. # Branch does not exist in this project
  1295. #
  1296. return None
  1297. if head.startswith(R_HEADS):
  1298. try:
  1299. head = all_refs[head]
  1300. except KeyError:
  1301. head = None
  1302. if head == revid:
  1303. # Same revision; just update HEAD to point to the new
  1304. # target branch, but otherwise take no other action.
  1305. #
  1306. _lwrite(os.path.join(self.worktree, '.git', HEAD),
  1307. 'ref: %s%s\n' % (R_HEADS, name))
  1308. return True
  1309. return GitCommand(self,
  1310. ['checkout', name, '--'],
  1311. capture_stdout=True,
  1312. capture_stderr=True).Wait() == 0
  1313. def AbandonBranch(self, name):
  1314. """Destroy a local topic branch.
  1315. Args:
  1316. name: The name of the branch to abandon.
  1317. Returns:
  1318. True if the abandon succeeded; False if it didn't; None if the branch
  1319. didn't exist.
  1320. """
  1321. rev = R_HEADS + name
  1322. all_refs = self.bare_ref.all
  1323. if rev not in all_refs:
  1324. # Doesn't exist
  1325. return None
  1326. head = self.work_git.GetHead()
  1327. if head == rev:
  1328. # We can't destroy the branch while we are sitting
  1329. # on it. Switch to a detached HEAD.
  1330. #
  1331. head = all_refs[head]
  1332. revid = self.GetRevisionId(all_refs)
  1333. if head == revid:
  1334. _lwrite(os.path.join(self.worktree, '.git', HEAD),
  1335. '%s\n' % revid)
  1336. else:
  1337. self._Checkout(revid, quiet=True)
  1338. return GitCommand(self,
  1339. ['branch', '-D', name],
  1340. capture_stdout=True,
  1341. capture_stderr=True).Wait() == 0
  1342. def PruneHeads(self):
  1343. """Prune any topic branches already merged into upstream.
  1344. """
  1345. cb = self.CurrentBranch
  1346. kill = []
  1347. left = self._allrefs
  1348. for name in left.keys():
  1349. if name.startswith(R_HEADS):
  1350. name = name[len(R_HEADS):]
  1351. if cb is None or name != cb:
  1352. kill.append(name)
  1353. rev = self.GetRevisionId(left)
  1354. if cb is not None \
  1355. and not self._revlist(HEAD + '...' + rev) \
  1356. and not self.IsDirty(consider_untracked=False):
  1357. self.work_git.DetachHead(HEAD)
  1358. kill.append(cb)
  1359. if kill:
  1360. old = self.bare_git.GetHead()
  1361. try:
  1362. self.bare_git.DetachHead(rev)
  1363. b = ['branch', '-d']
  1364. b.extend(kill)
  1365. b = GitCommand(self, b, bare=True,
  1366. capture_stdout=True,
  1367. capture_stderr=True)
  1368. b.Wait()
  1369. finally:
  1370. if ID_RE.match(old):
  1371. self.bare_git.DetachHead(old)
  1372. else:
  1373. self.bare_git.SetHead(old)
  1374. left = self._allrefs
  1375. for branch in kill:
  1376. if (R_HEADS + branch) not in left:
  1377. self.CleanPublishedCache()
  1378. break
  1379. if cb and cb not in kill:
  1380. kill.append(cb)
  1381. kill.sort()
  1382. kept = []
  1383. for branch in kill:
  1384. if R_HEADS + branch in left:
  1385. branch = self.GetBranch(branch)
  1386. base = branch.LocalMerge
  1387. if not base:
  1388. base = rev
  1389. kept.append(ReviewableBranch(self, branch, base))
  1390. return kept
  1391. ## Submodule Management ##
  1392. def GetRegisteredSubprojects(self):
  1393. result = []
  1394. def rec(subprojects):
  1395. if not subprojects:
  1396. return
  1397. result.extend(subprojects)
  1398. for p in subprojects:
  1399. rec(p.subprojects)
  1400. rec(self.subprojects)
  1401. return result
  1402. def _GetSubmodules(self):
  1403. # Unfortunately we cannot call `git submodule status --recursive` here
  1404. # because the working tree might not exist yet, and it cannot be used
  1405. # without a working tree in its current implementation.
  1406. def get_submodules(gitdir, rev):
  1407. # Parse .gitmodules for submodule sub_paths and sub_urls
  1408. sub_paths, sub_urls = parse_gitmodules(gitdir, rev)
  1409. if not sub_paths:
  1410. return []
  1411. # Run `git ls-tree` to read SHAs of submodule object, which happen to be
  1412. # revision of submodule repository
  1413. sub_revs = git_ls_tree(gitdir, rev, sub_paths)
  1414. submodules = []
  1415. for sub_path, sub_url in zip(sub_paths, sub_urls):
  1416. try:
  1417. sub_rev = sub_revs[sub_path]
  1418. except KeyError:
  1419. # Ignore non-exist submodules
  1420. continue
  1421. submodules.append((sub_rev, sub_path, sub_url))
  1422. return submodules
  1423. re_path = re.compile(r'^submodule\.([^.]+)\.path=(.*)$')
  1424. re_url = re.compile(r'^submodule\.([^.]+)\.url=(.*)$')
  1425. def parse_gitmodules(gitdir, rev):
  1426. cmd = ['cat-file', 'blob', '%s:.gitmodules' % rev]
  1427. try:
  1428. p = GitCommand(None, cmd, capture_stdout=True, capture_stderr=True,
  1429. bare=True, gitdir=gitdir)
  1430. except GitError:
  1431. return [], []
  1432. if p.Wait() != 0:
  1433. return [], []
  1434. gitmodules_lines = []
  1435. fd, temp_gitmodules_path = tempfile.mkstemp()
  1436. try:
  1437. os.write(fd, p.stdout)
  1438. os.close(fd)
  1439. cmd = ['config', '--file', temp_gitmodules_path, '--list']
  1440. p = GitCommand(None, cmd, capture_stdout=True, capture_stderr=True,
  1441. bare=True, gitdir=gitdir)
  1442. if p.Wait() != 0:
  1443. return [], []
  1444. gitmodules_lines = p.stdout.split('\n')
  1445. except GitError:
  1446. return [], []
  1447. finally:
  1448. os.remove(temp_gitmodules_path)
  1449. names = set()
  1450. paths = {}
  1451. urls = {}
  1452. for line in gitmodules_lines:
  1453. if not line:
  1454. continue
  1455. m = re_path.match(line)
  1456. if m:
  1457. names.add(m.group(1))
  1458. paths[m.group(1)] = m.group(2)
  1459. continue
  1460. m = re_url.match(line)
  1461. if m:
  1462. names.add(m.group(1))
  1463. urls[m.group(1)] = m.group(2)
  1464. continue
  1465. names = sorted(names)
  1466. return ([paths.get(name, '') for name in names],
  1467. [urls.get(name, '') for name in names])
  1468. def git_ls_tree(gitdir, rev, paths):
  1469. cmd = ['ls-tree', rev, '--']
  1470. cmd.extend(paths)
  1471. try:
  1472. p = GitCommand(None, cmd, capture_stdout=True, capture_stderr=True,
  1473. bare=True, gitdir=gitdir)
  1474. except GitError:
  1475. return []
  1476. if p.Wait() != 0:
  1477. return []
  1478. objects = {}
  1479. for line in p.stdout.split('\n'):
  1480. if not line.strip():
  1481. continue
  1482. object_rev, object_path = line.split()[2:4]
  1483. objects[object_path] = object_rev
  1484. return objects
  1485. try:
  1486. rev = self.GetRevisionId()
  1487. except GitError:
  1488. return []
  1489. return get_submodules(self.gitdir, rev)
  1490. def GetDerivedSubprojects(self):
  1491. result = []
  1492. if not self.Exists:
  1493. # If git repo does not exist yet, querying its submodules will
  1494. # mess up its states; so return here.
  1495. return result
  1496. for rev, path, url in self._GetSubmodules():
  1497. name = self.manifest.GetSubprojectName(self, path)
  1498. relpath, worktree, gitdir, objdir = \
  1499. self.manifest.GetSubprojectPaths(self, name, path)
  1500. project = self.manifest.paths.get(relpath)
  1501. if project:
  1502. result.extend(project.GetDerivedSubprojects())
  1503. continue
  1504. remote = RemoteSpec(self.remote.name,
  1505. url=url,
  1506. review=self.remote.review,
  1507. revision=self.remote.revision)
  1508. subproject = Project(manifest=self.manifest,
  1509. name=name,
  1510. remote=remote,
  1511. gitdir=gitdir,
  1512. objdir=objdir,
  1513. worktree=worktree,
  1514. relpath=relpath,
  1515. revisionExpr=self.revisionExpr,
  1516. revisionId=rev,
  1517. rebase=self.rebase,
  1518. groups=self.groups,
  1519. sync_c=self.sync_c,
  1520. sync_s=self.sync_s,
  1521. parent=self,
  1522. is_derived=True)
  1523. result.append(subproject)
  1524. result.extend(subproject.GetDerivedSubprojects())
  1525. return result
  1526. ## Direct Git Commands ##
  1527. def _CheckForSha1(self):
  1528. try:
  1529. # if revision (sha or tag) is not present then following function
  1530. # throws an error.
  1531. self.bare_git.rev_parse('--verify', '%s^0' % self.revisionExpr)
  1532. return True
  1533. except GitError:
  1534. # There is no such persistent revision. We have to fetch it.
  1535. return False
  1536. def _FetchArchive(self, tarpath, cwd=None):
  1537. cmd = ['archive', '-v', '-o', tarpath]
  1538. cmd.append('--remote=%s' % self.remote.url)
  1539. cmd.append('--prefix=%s/' % self.relpath)
  1540. cmd.append(self.revisionExpr)
  1541. command = GitCommand(self, cmd, cwd=cwd,
  1542. capture_stdout=True,
  1543. capture_stderr=True)
  1544. if command.Wait() != 0:
  1545. raise GitError('git archive %s: %s' % (self.name, command.stderr))
  1546. def _RemoteFetch(self, name=None,
  1547. current_branch_only=False,
  1548. initial=False,
  1549. quiet=False,
  1550. alt_dir=None,
  1551. no_tags=False,
  1552. prune=False):
  1553. is_sha1 = False
  1554. tag_name = None
  1555. depth = None
  1556. # The depth should not be used when fetching to a mirror because
  1557. # it will result in a shallow repository that cannot be cloned or
  1558. # fetched from.
  1559. if not self.manifest.IsMirror:
  1560. if self.clone_depth:
  1561. depth = self.clone_depth
  1562. else:
  1563. depth = self.manifest.manifestProject.config.GetString('repo.depth')
  1564. # The repo project should never be synced with partial depth
  1565. if self.relpath == '.repo/repo':
  1566. depth = None
  1567. if depth:
  1568. current_branch_only = True
  1569. if ID_RE.match(self.revisionExpr) is not None:
  1570. is_sha1 = True
  1571. if current_branch_only:
  1572. if self.revisionExpr.startswith(R_TAGS):
  1573. # this is a tag and its sha1 value should never change
  1574. tag_name = self.revisionExpr[len(R_TAGS):]
  1575. if is_sha1 or tag_name is not None:
  1576. if self._CheckForSha1():
  1577. return True
  1578. if is_sha1 and not depth:
  1579. # When syncing a specific commit and --depth is not set:
  1580. # * if upstream is explicitly specified and is not a sha1, fetch only
  1581. # upstream as users expect only upstream to be fetch.
  1582. # Note: The commit might not be in upstream in which case the sync
  1583. # will fail.
  1584. # * otherwise, fetch all branches to make sure we end up with the
  1585. # specific commit.
  1586. current_branch_only = self.upstream and not ID_RE.match(self.upstream)
  1587. if not name:
  1588. name = self.remote.name
  1589. ssh_proxy = False
  1590. remote = self.GetRemote(name)
  1591. if remote.PreConnectFetch():
  1592. ssh_proxy = True
  1593. if initial:
  1594. if alt_dir and 'objects' == os.path.basename(alt_dir):
  1595. ref_dir = os.path.dirname(alt_dir)
  1596. packed_refs = os.path.join(self.gitdir, 'packed-refs')
  1597. remote = self.GetRemote(name)
  1598. all_refs = self.bare_ref.all
  1599. ids = set(all_refs.values())
  1600. tmp = set()
  1601. for r, ref_id in GitRefs(ref_dir).all.items():
  1602. if r not in all_refs:
  1603. if r.startswith(R_TAGS) or remote.WritesTo(r):
  1604. all_refs[r] = ref_id
  1605. ids.add(ref_id)
  1606. continue
  1607. if ref_id in ids:
  1608. continue
  1609. r = 'refs/_alt/%s' % ref_id
  1610. all_refs[r] = ref_id
  1611. ids.add(ref_id)
  1612. tmp.add(r)
  1613. tmp_packed = ''
  1614. old_packed = ''
  1615. for r in sorted(all_refs):
  1616. line = '%s %s\n' % (all_refs[r], r)
  1617. tmp_packed += line
  1618. if r not in tmp:
  1619. old_packed += line
  1620. _lwrite(packed_refs, tmp_packed)
  1621. else:
  1622. alt_dir = None
  1623. cmd = ['fetch']
  1624. if depth:
  1625. cmd.append('--depth=%s' % depth)
  1626. else:
  1627. # If this repo has shallow objects, then we don't know which refs have
  1628. # shallow objects or not. Tell git to unshallow all fetched refs. Don't
  1629. # do this with projects that don't have shallow objects, since it is less
  1630. # efficient.
  1631. if os.path.exists(os.path.join(self.gitdir, 'shallow')):
  1632. cmd.append('--depth=2147483647')
  1633. if quiet:
  1634. cmd.append('--quiet')
  1635. if not self.worktree:
  1636. cmd.append('--update-head-ok')
  1637. cmd.append(name)
  1638. # If using depth then we should not get all the tags since they may
  1639. # be outside of the depth.
  1640. if no_tags or depth:
  1641. cmd.append('--no-tags')
  1642. else:
  1643. cmd.append('--tags')
  1644. if prune:
  1645. cmd.append('--prune')
  1646. spec = []
  1647. if not current_branch_only:
  1648. # Fetch whole repo
  1649. spec.append(str((u'+refs/heads/*:') + remote.ToLocal('refs/heads/*')))
  1650. elif tag_name is not None:
  1651. spec.append('tag')
  1652. spec.append(tag_name)
  1653. if not self.manifest.IsMirror:
  1654. branch = self.revisionExpr
  1655. if is_sha1 and depth and git_require((1, 8, 3)):
  1656. # Shallow checkout of a specific commit, fetch from that commit and not
  1657. # the heads only as the commit might be deeper in the history.
  1658. spec.append(branch)
  1659. else:
  1660. if is_sha1:
  1661. branch = self.upstream
  1662. if branch is not None and branch.strip():
  1663. if not branch.startswith('refs/'):
  1664. branch = R_HEADS + branch
  1665. spec.append(str((u'+%s:' % branch) + remote.ToLocal(branch)))
  1666. cmd.extend(spec)
  1667. ok = False
  1668. for _i in range(2):
  1669. gitcmd = GitCommand(self, cmd, bare=True, ssh_proxy=ssh_proxy)
  1670. ret = gitcmd.Wait()
  1671. if ret == 0:
  1672. ok = True
  1673. break
  1674. # If needed, run the 'git remote prune' the first time through the loop
  1675. elif (not _i and
  1676. "error:" in gitcmd.stderr and
  1677. "git remote prune" in gitcmd.stderr):
  1678. prunecmd = GitCommand(self, ['remote', 'prune', name], bare=True,
  1679. ssh_proxy=ssh_proxy)
  1680. ret = prunecmd.Wait()
  1681. if ret:
  1682. break
  1683. continue
  1684. elif current_branch_only and is_sha1 and ret == 128:
  1685. # Exit code 128 means "couldn't find the ref you asked for"; if we're in sha1
  1686. # mode, we just tried sync'ing from the upstream field; it doesn't exist, thus
  1687. # abort the optimization attempt and do a full sync.
  1688. break
  1689. elif ret < 0:
  1690. # Git died with a signal, exit immediately
  1691. break
  1692. time.sleep(random.randint(30, 45))
  1693. if initial:
  1694. if alt_dir:
  1695. if old_packed != '':
  1696. _lwrite(packed_refs, old_packed)
  1697. else:
  1698. os.remove(packed_refs)
  1699. self.bare_git.pack_refs('--all', '--prune')
  1700. if is_sha1 and current_branch_only and self.upstream:
  1701. # We just synced the upstream given branch; verify we
  1702. # got what we wanted, else trigger a second run of all
  1703. # refs.
  1704. if not self._CheckForSha1():
  1705. if not depth:
  1706. # Avoid infinite recursion when depth is True (since depth implies
  1707. # current_branch_only)
  1708. return self._RemoteFetch(name=name, current_branch_only=False,
  1709. initial=False, quiet=quiet, alt_dir=alt_dir)
  1710. if self.clone_depth:
  1711. self.clone_depth = None
  1712. return self._RemoteFetch(name=name, current_branch_only=current_branch_only,
  1713. initial=False, quiet=quiet, alt_dir=alt_dir)
  1714. return ok
  1715. def _ApplyCloneBundle(self, initial=False, quiet=False):
  1716. if initial and (self.manifest.manifestProject.config.GetString('repo.depth') or self.clone_depth):
  1717. return False
  1718. remote = self.GetRemote(self.remote.name)
  1719. bundle_url = remote.url + '/clone.bundle'
  1720. bundle_url = GitConfig.ForUser().UrlInsteadOf(bundle_url)
  1721. if GetSchemeFromUrl(bundle_url) not in (
  1722. 'http', 'https', 'persistent-http', 'persistent-https'):
  1723. return False
  1724. bundle_dst = os.path.join(self.gitdir, 'clone.bundle')
  1725. bundle_tmp = os.path.join(self.gitdir, 'clone.bundle.tmp')
  1726. exist_dst = os.path.exists(bundle_dst)
  1727. exist_tmp = os.path.exists(bundle_tmp)
  1728. if not initial and not exist_dst and not exist_tmp:
  1729. return False
  1730. if not exist_dst:
  1731. exist_dst = self._FetchBundle(bundle_url, bundle_tmp, bundle_dst, quiet)
  1732. if not exist_dst:
  1733. return False
  1734. cmd = ['fetch']
  1735. if quiet:
  1736. cmd.append('--quiet')
  1737. if not self.worktree:
  1738. cmd.append('--update-head-ok')
  1739. cmd.append(bundle_dst)
  1740. for f in remote.fetch:
  1741. cmd.append(str(f))
  1742. cmd.append('refs/tags/*:refs/tags/*')
  1743. ok = GitCommand(self, cmd, bare=True).Wait() == 0
  1744. if os.path.exists(bundle_dst):
  1745. os.remove(bundle_dst)
  1746. if os.path.exists(bundle_tmp):
  1747. os.remove(bundle_tmp)
  1748. return ok
  1749. def _FetchBundle(self, srcUrl, tmpPath, dstPath, quiet):
  1750. if os.path.exists(dstPath):
  1751. os.remove(dstPath)
  1752. cmd = ['curl', '--fail', '--output', tmpPath, '--netrc', '--location']
  1753. if quiet:
  1754. cmd += ['--silent']
  1755. if os.path.exists(tmpPath):
  1756. size = os.stat(tmpPath).st_size
  1757. if size >= 1024:
  1758. cmd += ['--continue-at', '%d' % (size,)]
  1759. else:
  1760. os.remove(tmpPath)
  1761. if 'http_proxy' in os.environ and 'darwin' == sys.platform:
  1762. cmd += ['--proxy', os.environ['http_proxy']]
  1763. with GetUrlCookieFile(srcUrl, quiet) as (cookiefile, proxy):
  1764. if cookiefile:
  1765. cmd += ['--cookie', cookiefile, '--cookie-jar', cookiefile]
  1766. if srcUrl.startswith('persistent-'):
  1767. srcUrl = srcUrl[len('persistent-'):]
  1768. cmd += [srcUrl]
  1769. if IsTrace():
  1770. Trace('%s', ' '.join(cmd))
  1771. try:
  1772. proc = subprocess.Popen(cmd)
  1773. except OSError:
  1774. return False
  1775. curlret = proc.wait()
  1776. if curlret == 22:
  1777. # From curl man page:
  1778. # 22: HTTP page not retrieved. The requested url was not found or
  1779. # returned another error with the HTTP error code being 400 or above.
  1780. # This return code only appears if -f, --fail is used.
  1781. if not quiet:
  1782. print("Server does not provide clone.bundle; ignoring.",
  1783. file=sys.stderr)
  1784. return False
  1785. if os.path.exists(tmpPath):
  1786. if curlret == 0 and self._IsValidBundle(tmpPath, quiet):
  1787. os.rename(tmpPath, dstPath)
  1788. return True
  1789. else:
  1790. os.remove(tmpPath)
  1791. return False
  1792. else:
  1793. return False
  1794. def _IsValidBundle(self, path, quiet):
  1795. try:
  1796. with open(path) as f:
  1797. if f.read(16) == '# v2 git bundle\n':
  1798. return True
  1799. else:
  1800. if not quiet:
  1801. print("Invalid clone.bundle file; ignoring.", file=sys.stderr)
  1802. return False
  1803. except OSError:
  1804. return False
  1805. def _Checkout(self, rev, quiet=False):
  1806. cmd = ['checkout']
  1807. if quiet:
  1808. cmd.append('-q')
  1809. cmd.append(rev)
  1810. cmd.append('--')
  1811. if GitCommand(self, cmd).Wait() != 0:
  1812. if self._allrefs:
  1813. raise GitError('%s checkout %s ' % (self.name, rev))
  1814. def _CherryPick(self, rev):
  1815. cmd = ['cherry-pick']
  1816. cmd.append(rev)
  1817. cmd.append('--')
  1818. if GitCommand(self, cmd).Wait() != 0:
  1819. if self._allrefs:
  1820. raise GitError('%s cherry-pick %s ' % (self.name, rev))
  1821. def _Revert(self, rev):
  1822. cmd = ['revert']
  1823. cmd.append('--no-edit')
  1824. cmd.append(rev)
  1825. cmd.append('--')
  1826. if GitCommand(self, cmd).Wait() != 0:
  1827. if self._allrefs:
  1828. raise GitError('%s revert %s ' % (self.name, rev))
  1829. def _ResetHard(self, rev, quiet=True):
  1830. cmd = ['reset', '--hard']
  1831. if quiet:
  1832. cmd.append('-q')
  1833. cmd.append(rev)
  1834. if GitCommand(self, cmd).Wait() != 0:
  1835. raise GitError('%s reset --hard %s ' % (self.name, rev))
  1836. def _Rebase(self, upstream, onto=None):
  1837. cmd = ['rebase']
  1838. if onto is not None:
  1839. cmd.extend(['--onto', onto])
  1840. cmd.append(upstream)
  1841. if GitCommand(self, cmd).Wait() != 0:
  1842. raise GitError('%s rebase %s ' % (self.name, upstream))
  1843. def _FastForward(self, head, ffonly=False):
  1844. cmd = ['merge', head]
  1845. if ffonly:
  1846. cmd.append("--ff-only")
  1847. if GitCommand(self, cmd).Wait() != 0:
  1848. raise GitError('%s merge %s ' % (self.name, head))
  1849. def _InitGitDir(self, mirror_git=None, force_sync=False):
  1850. init_git_dir = not os.path.exists(self.gitdir)
  1851. init_obj_dir = not os.path.exists(self.objdir)
  1852. try:
  1853. # Initialize the bare repository, which contains all of the objects.
  1854. if init_obj_dir:
  1855. os.makedirs(self.objdir)
  1856. self.bare_objdir.init()
  1857. # If we have a separate directory to hold refs, initialize it as well.
  1858. if self.objdir != self.gitdir:
  1859. if init_git_dir:
  1860. os.makedirs(self.gitdir)
  1861. if init_obj_dir or init_git_dir:
  1862. self._ReferenceGitDir(self.objdir, self.gitdir, share_refs=False,
  1863. copy_all=True)
  1864. try:
  1865. self._CheckDirReference(self.objdir, self.gitdir, share_refs=False)
  1866. except GitError as e:
  1867. if force_sync:
  1868. print("Retrying clone after deleting %s" % self.gitdir, file=sys.stderr)
  1869. try:
  1870. shutil.rmtree(os.path.realpath(self.gitdir))
  1871. if self.worktree and os.path.exists(
  1872. os.path.realpath(self.worktree)):
  1873. shutil.rmtree(os.path.realpath(self.worktree))
  1874. return self._InitGitDir(mirror_git=mirror_git, force_sync=False)
  1875. except:
  1876. raise e
  1877. raise e
  1878. if init_git_dir:
  1879. mp = self.manifest.manifestProject
  1880. ref_dir = mp.config.GetString('repo.reference') or ''
  1881. if ref_dir or mirror_git:
  1882. if not mirror_git:
  1883. mirror_git = os.path.join(ref_dir, self.name + '.git')
  1884. repo_git = os.path.join(ref_dir, '.repo', 'projects',
  1885. self.relpath + '.git')
  1886. if os.path.exists(mirror_git):
  1887. ref_dir = mirror_git
  1888. elif os.path.exists(repo_git):
  1889. ref_dir = repo_git
  1890. else:
  1891. ref_dir = None
  1892. if ref_dir:
  1893. _lwrite(os.path.join(self.gitdir, 'objects/info/alternates'),
  1894. os.path.join(ref_dir, 'objects') + '\n')
  1895. self._UpdateHooks()
  1896. m = self.manifest.manifestProject.config
  1897. for key in ['user.name', 'user.email']:
  1898. if m.Has(key, include_defaults=False):
  1899. self.config.SetString(key, m.GetString(key))
  1900. if self.manifest.IsMirror:
  1901. self.config.SetString('core.bare', 'true')
  1902. else:
  1903. self.config.SetString('core.bare', None)
  1904. except Exception:
  1905. if init_obj_dir and os.path.exists(self.objdir):
  1906. shutil.rmtree(self.objdir)
  1907. if init_git_dir and os.path.exists(self.gitdir):
  1908. shutil.rmtree(self.gitdir)
  1909. raise
  1910. def _UpdateHooks(self):
  1911. if os.path.exists(self.gitdir):
  1912. self._InitHooks()
  1913. def _InitHooks(self):
  1914. hooks = os.path.realpath(self._gitdir_path('hooks'))
  1915. if not os.path.exists(hooks):
  1916. os.makedirs(hooks)
  1917. for stock_hook in _ProjectHooks():
  1918. name = os.path.basename(stock_hook)
  1919. if name in ('commit-msg',) and not self.remote.review \
  1920. and not self is self.manifest.manifestProject:
  1921. # Don't install a Gerrit Code Review hook if this
  1922. # project does not appear to use it for reviews.
  1923. #
  1924. # Since the manifest project is one of those, but also
  1925. # managed through gerrit, it's excluded
  1926. continue
  1927. dst = os.path.join(hooks, name)
  1928. if os.path.islink(dst):
  1929. continue
  1930. if os.path.exists(dst):
  1931. if filecmp.cmp(stock_hook, dst, shallow=False):
  1932. os.remove(dst)
  1933. else:
  1934. _warn("%s: Not replacing locally modified %s hook", self.relpath, name)
  1935. continue
  1936. try:
  1937. os.symlink(os.path.relpath(stock_hook, os.path.dirname(dst)), dst)
  1938. except OSError as e:
  1939. if e.errno == errno.EPERM:
  1940. raise GitError('filesystem must support symlinks')
  1941. else:
  1942. raise
  1943. def _InitRemote(self):
  1944. if self.remote.url:
  1945. remote = self.GetRemote(self.remote.name)
  1946. remote.url = self.remote.url
  1947. remote.review = self.remote.review
  1948. remote.projectname = self.name
  1949. if self.worktree:
  1950. remote.ResetFetch(mirror=False)
  1951. else:
  1952. remote.ResetFetch(mirror=True)
  1953. remote.Save()
  1954. def _InitMRef(self):
  1955. if self.manifest.branch:
  1956. self._InitAnyMRef(R_M + self.manifest.branch)
  1957. def _InitMirrorHead(self):
  1958. self._InitAnyMRef(HEAD)
  1959. def _InitAnyMRef(self, ref):
  1960. cur = self.bare_ref.symref(ref)
  1961. if self.revisionId:
  1962. if cur != '' or self.bare_ref.get(ref) != self.revisionId:
  1963. msg = 'manifest set to %s' % self.revisionId
  1964. dst = self.revisionId + '^0'
  1965. self.bare_git.UpdateRef(ref, dst, message=msg, detach=True)
  1966. else:
  1967. remote = self.GetRemote(self.remote.name)
  1968. dst = remote.ToLocal(self.revisionExpr)
  1969. if cur != dst:
  1970. msg = 'manifest set to %s' % self.revisionExpr
  1971. self.bare_git.symbolic_ref('-m', msg, ref, dst)
  1972. def _CheckDirReference(self, srcdir, destdir, share_refs):
  1973. symlink_files = self.shareable_files
  1974. symlink_dirs = self.shareable_dirs
  1975. if share_refs:
  1976. symlink_files += self.working_tree_files
  1977. symlink_dirs += self.working_tree_dirs
  1978. to_symlink = symlink_files + symlink_dirs
  1979. for name in set(to_symlink):
  1980. dst = os.path.realpath(os.path.join(destdir, name))
  1981. if os.path.lexists(dst):
  1982. src = os.path.realpath(os.path.join(srcdir, name))
  1983. # Fail if the links are pointing to the wrong place
  1984. if src != dst:
  1985. raise GitError('--force-sync not enabled; cannot overwrite a local '
  1986. 'work tree. If you\'re comfortable with the '
  1987. 'possibility of losing the work tree\'s git metadata,'
  1988. ' use `repo sync --force-sync {0}` to '
  1989. 'proceed.'.format(self.relpath))
  1990. def _ReferenceGitDir(self, gitdir, dotgit, share_refs, copy_all):
  1991. """Update |dotgit| to reference |gitdir|, using symlinks where possible.
  1992. Args:
  1993. gitdir: The bare git repository. Must already be initialized.
  1994. dotgit: The repository you would like to initialize.
  1995. share_refs: If true, |dotgit| will store its refs under |gitdir|.
  1996. Only one work tree can store refs under a given |gitdir|.
  1997. copy_all: If true, copy all remaining files from |gitdir| -> |dotgit|.
  1998. This saves you the effort of initializing |dotgit| yourself.
  1999. """
  2000. symlink_files = self.shareable_files
  2001. symlink_dirs = self.shareable_dirs
  2002. if share_refs:
  2003. symlink_files += self.working_tree_files
  2004. symlink_dirs += self.working_tree_dirs
  2005. to_symlink = symlink_files + symlink_dirs
  2006. to_copy = []
  2007. if copy_all:
  2008. to_copy = os.listdir(gitdir)
  2009. dotgit = os.path.realpath(dotgit)
  2010. for name in set(to_copy).union(to_symlink):
  2011. try:
  2012. src = os.path.realpath(os.path.join(gitdir, name))
  2013. dst = os.path.join(dotgit, name)
  2014. if os.path.lexists(dst):
  2015. continue
  2016. # If the source dir doesn't exist, create an empty dir.
  2017. if name in symlink_dirs and not os.path.lexists(src):
  2018. os.makedirs(src)
  2019. # If the source file doesn't exist, ensure the destination
  2020. # file doesn't either.
  2021. if name in symlink_files and not os.path.lexists(src):
  2022. try:
  2023. os.remove(dst)
  2024. except OSError:
  2025. pass
  2026. if name in to_symlink:
  2027. os.symlink(os.path.relpath(src, os.path.dirname(dst)), dst)
  2028. elif copy_all and not os.path.islink(dst):
  2029. if os.path.isdir(src):
  2030. shutil.copytree(src, dst)
  2031. elif os.path.isfile(src):
  2032. shutil.copy(src, dst)
  2033. except OSError as e:
  2034. if e.errno == errno.EPERM:
  2035. raise DownloadError('filesystem must support symlinks')
  2036. else:
  2037. raise
  2038. def _InitWorkTree(self, force_sync=False):
  2039. dotgit = os.path.join(self.worktree, '.git')
  2040. init_dotgit = not os.path.exists(dotgit)
  2041. try:
  2042. if init_dotgit:
  2043. os.makedirs(dotgit)
  2044. self._ReferenceGitDir(self.gitdir, dotgit, share_refs=True,
  2045. copy_all=False)
  2046. try:
  2047. self._CheckDirReference(self.gitdir, dotgit, share_refs=True)
  2048. except GitError as e:
  2049. if force_sync:
  2050. try:
  2051. shutil.rmtree(dotgit)
  2052. return self._InitWorkTree(force_sync=False)
  2053. except:
  2054. raise e
  2055. raise e
  2056. if init_dotgit:
  2057. _lwrite(os.path.join(dotgit, HEAD), '%s\n' % self.GetRevisionId())
  2058. cmd = ['read-tree', '--reset', '-u']
  2059. cmd.append('-v')
  2060. cmd.append(HEAD)
  2061. if GitCommand(self, cmd).Wait() != 0:
  2062. raise GitError("cannot initialize work tree")
  2063. self._CopyAndLinkFiles()
  2064. except Exception:
  2065. if init_dotgit:
  2066. shutil.rmtree(dotgit)
  2067. raise
  2068. def _gitdir_path(self, path):
  2069. return os.path.realpath(os.path.join(self.gitdir, path))
  2070. def _revlist(self, *args, **kw):
  2071. a = []
  2072. a.extend(args)
  2073. a.append('--')
  2074. return self.work_git.rev_list(*a, **kw)
  2075. @property
  2076. def _allrefs(self):
  2077. return self.bare_ref.all
  2078. def _getLogs(self, rev1, rev2, oneline=False, color=True):
  2079. """Get logs between two revisions of this project."""
  2080. comp = '..'
  2081. if rev1:
  2082. revs = [rev1]
  2083. if rev2:
  2084. revs.extend([comp, rev2])
  2085. cmd = ['log', ''.join(revs)]
  2086. out = DiffColoring(self.config)
  2087. if out.is_on and color:
  2088. cmd.append('--color')
  2089. if oneline:
  2090. cmd.append('--oneline')
  2091. try:
  2092. log = GitCommand(self, cmd, capture_stdout=True, capture_stderr=True)
  2093. if log.Wait() == 0:
  2094. return log.stdout
  2095. except GitError:
  2096. # worktree may not exist if groups changed for example. In that case,
  2097. # try in gitdir instead.
  2098. if not os.path.exists(self.worktree):
  2099. return self.bare_git.log(*cmd[1:])
  2100. else:
  2101. raise
  2102. return None
  2103. def getAddedAndRemovedLogs(self, toProject, oneline=False, color=True):
  2104. """Get the list of logs from this revision to given revisionId"""
  2105. logs = {}
  2106. selfId = self.GetRevisionId(self._allrefs)
  2107. toId = toProject.GetRevisionId(toProject._allrefs)
  2108. logs['added'] = self._getLogs(selfId, toId, oneline=oneline, color=color)
  2109. logs['removed'] = self._getLogs(toId, selfId, oneline=oneline, color=color)
  2110. return logs
  2111. class _GitGetByExec(object):
  2112. def __init__(self, project, bare, gitdir):
  2113. self._project = project
  2114. self._bare = bare
  2115. self._gitdir = gitdir
  2116. def LsOthers(self):
  2117. p = GitCommand(self._project,
  2118. ['ls-files',
  2119. '-z',
  2120. '--others',
  2121. '--exclude-standard'],
  2122. bare=False,
  2123. gitdir=self._gitdir,
  2124. capture_stdout=True,
  2125. capture_stderr=True)
  2126. if p.Wait() == 0:
  2127. out = p.stdout
  2128. if out:
  2129. return out[:-1].split('\0') # pylint: disable=W1401
  2130. # Backslash is not anomalous
  2131. return []
  2132. def DiffZ(self, name, *args):
  2133. cmd = [name]
  2134. cmd.append('-z')
  2135. cmd.extend(args)
  2136. p = GitCommand(self._project,
  2137. cmd,
  2138. gitdir=self._gitdir,
  2139. bare=False,
  2140. capture_stdout=True,
  2141. capture_stderr=True)
  2142. try:
  2143. out = p.process.stdout.read()
  2144. r = {}
  2145. if out:
  2146. out = iter(out[:-1].split('\0')) # pylint: disable=W1401
  2147. while out:
  2148. try:
  2149. info = next(out)
  2150. path = next(out)
  2151. except StopIteration:
  2152. break
  2153. class _Info(object):
  2154. def __init__(self, path, omode, nmode, oid, nid, state):
  2155. self.path = path
  2156. self.src_path = None
  2157. self.old_mode = omode
  2158. self.new_mode = nmode
  2159. self.old_id = oid
  2160. self.new_id = nid
  2161. if len(state) == 1:
  2162. self.status = state
  2163. self.level = None
  2164. else:
  2165. self.status = state[:1]
  2166. self.level = state[1:]
  2167. while self.level.startswith('0'):
  2168. self.level = self.level[1:]
  2169. info = info[1:].split(' ')
  2170. info = _Info(path, *info)
  2171. if info.status in ('R', 'C'):
  2172. info.src_path = info.path
  2173. info.path = next(out)
  2174. r[info.path] = info
  2175. return r
  2176. finally:
  2177. p.Wait()
  2178. def GetHead(self):
  2179. if self._bare:
  2180. path = os.path.join(self._project.gitdir, HEAD)
  2181. else:
  2182. path = os.path.join(self._project.worktree, '.git', HEAD)
  2183. try:
  2184. fd = open(path, 'rb')
  2185. except IOError as e:
  2186. raise NoManifestException(path, str(e))
  2187. try:
  2188. line = fd.read()
  2189. finally:
  2190. fd.close()
  2191. try:
  2192. line = line.decode()
  2193. except AttributeError:
  2194. pass
  2195. if line.startswith('ref: '):
  2196. return line[5:-1]
  2197. return line[:-1]
  2198. def SetHead(self, ref, message=None):
  2199. cmdv = []
  2200. if message is not None:
  2201. cmdv.extend(['-m', message])
  2202. cmdv.append(HEAD)
  2203. cmdv.append(ref)
  2204. self.symbolic_ref(*cmdv)
  2205. def DetachHead(self, new, message=None):
  2206. cmdv = ['--no-deref']
  2207. if message is not None:
  2208. cmdv.extend(['-m', message])
  2209. cmdv.append(HEAD)
  2210. cmdv.append(new)
  2211. self.update_ref(*cmdv)
  2212. def UpdateRef(self, name, new, old=None,
  2213. message=None,
  2214. detach=False):
  2215. cmdv = []
  2216. if message is not None:
  2217. cmdv.extend(['-m', message])
  2218. if detach:
  2219. cmdv.append('--no-deref')
  2220. cmdv.append(name)
  2221. cmdv.append(new)
  2222. if old is not None:
  2223. cmdv.append(old)
  2224. self.update_ref(*cmdv)
  2225. def DeleteRef(self, name, old=None):
  2226. if not old:
  2227. old = self.rev_parse(name)
  2228. self.update_ref('-d', name, old)
  2229. self._project.bare_ref.deleted(name)
  2230. def rev_list(self, *args, **kw):
  2231. if 'format' in kw:
  2232. cmdv = ['log', '--pretty=format:%s' % kw['format']]
  2233. else:
  2234. cmdv = ['rev-list']
  2235. cmdv.extend(args)
  2236. p = GitCommand(self._project,
  2237. cmdv,
  2238. bare=self._bare,
  2239. gitdir=self._gitdir,
  2240. capture_stdout=True,
  2241. capture_stderr=True)
  2242. r = []
  2243. for line in p.process.stdout:
  2244. if line[-1] == '\n':
  2245. line = line[:-1]
  2246. r.append(line)
  2247. if p.Wait() != 0:
  2248. raise GitError('%s rev-list %s: %s' % (
  2249. self._project.name,
  2250. str(args),
  2251. p.stderr))
  2252. return r
  2253. def __getattr__(self, name):
  2254. """Allow arbitrary git commands using pythonic syntax.
  2255. This allows you to do things like:
  2256. git_obj.rev_parse('HEAD')
  2257. Since we don't have a 'rev_parse' method defined, the __getattr__ will
  2258. run. We'll replace the '_' with a '-' and try to run a git command.
  2259. Any other positional arguments will be passed to the git command, and the
  2260. following keyword arguments are supported:
  2261. config: An optional dict of git config options to be passed with '-c'.
  2262. Args:
  2263. name: The name of the git command to call. Any '_' characters will
  2264. be replaced with '-'.
  2265. Returns:
  2266. A callable object that will try to call git with the named command.
  2267. """
  2268. name = name.replace('_', '-')
  2269. def runner(*args, **kwargs):
  2270. cmdv = []
  2271. config = kwargs.pop('config', None)
  2272. for k in kwargs:
  2273. raise TypeError('%s() got an unexpected keyword argument %r'
  2274. % (name, k))
  2275. if config is not None:
  2276. if not git_require((1, 7, 2)):
  2277. raise ValueError('cannot set config on command line for %s()'
  2278. % name)
  2279. for k, v in config.items():
  2280. cmdv.append('-c')
  2281. cmdv.append('%s=%s' % (k, v))
  2282. cmdv.append(name)
  2283. cmdv.extend(args)
  2284. p = GitCommand(self._project,
  2285. cmdv,
  2286. bare=self._bare,
  2287. gitdir=self._gitdir,
  2288. capture_stdout=True,
  2289. capture_stderr=True)
  2290. if p.Wait() != 0:
  2291. raise GitError('%s %s: %s' % (
  2292. self._project.name,
  2293. name,
  2294. 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