project.py 87 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832
  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.exists(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 = {}
  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. """Perform only the network IO portion of the sync process.
  954. Local working directory/branch state is not affected.
  955. """
  956. if archive and not isinstance(self, MetaProject):
  957. if self.remote.url.startswith(('http://', 'https://')):
  958. _error("%s: Cannot fetch archives from http/https remotes.", self.name)
  959. return False
  960. name = self.relpath.replace('\\', '/')
  961. name = name.replace('/', '_')
  962. tarpath = '%s.tar' % name
  963. topdir = self.manifest.topdir
  964. try:
  965. self._FetchArchive(tarpath, cwd=topdir)
  966. except GitError as e:
  967. _error('%s', e)
  968. return False
  969. # From now on, we only need absolute tarpath
  970. tarpath = os.path.join(topdir, tarpath)
  971. if not self._ExtractArchive(tarpath, path=topdir):
  972. return False
  973. try:
  974. os.remove(tarpath)
  975. except OSError as e:
  976. _warn("Cannot remove archive %s: %s", tarpath, str(e))
  977. self._CopyAndLinkFiles()
  978. return True
  979. if is_new is None:
  980. is_new = not self.Exists
  981. if is_new:
  982. self._InitGitDir(force_sync=force_sync)
  983. else:
  984. self._UpdateHooks()
  985. self._InitRemote()
  986. if is_new:
  987. alt = os.path.join(self.gitdir, 'objects/info/alternates')
  988. try:
  989. fd = open(alt, 'rb')
  990. try:
  991. alt_dir = fd.readline().rstrip()
  992. finally:
  993. fd.close()
  994. except IOError:
  995. alt_dir = None
  996. else:
  997. alt_dir = None
  998. if clone_bundle \
  999. and alt_dir is None \
  1000. and self._ApplyCloneBundle(initial=is_new, quiet=quiet):
  1001. is_new = False
  1002. if not current_branch_only:
  1003. if self.sync_c:
  1004. current_branch_only = True
  1005. elif not self.manifest._loaded:
  1006. # Manifest cannot check defaults until it syncs.
  1007. current_branch_only = False
  1008. elif self.manifest.default.sync_c:
  1009. current_branch_only = True
  1010. need_to_fetch = not (optimized_fetch and \
  1011. (ID_RE.match(self.revisionExpr) and self._CheckForSha1()))
  1012. if (need_to_fetch
  1013. and not self._RemoteFetch(initial=is_new, quiet=quiet, alt_dir=alt_dir,
  1014. current_branch_only=current_branch_only,
  1015. no_tags=no_tags)):
  1016. return False
  1017. if self.worktree:
  1018. self._InitMRef()
  1019. else:
  1020. self._InitMirrorHead()
  1021. try:
  1022. os.remove(os.path.join(self.gitdir, 'FETCH_HEAD'))
  1023. except OSError:
  1024. pass
  1025. return True
  1026. def PostRepoUpgrade(self):
  1027. self._InitHooks()
  1028. def _CopyAndLinkFiles(self):
  1029. if self.manifest.isGitcClient:
  1030. return
  1031. for copyfile in self.copyfiles:
  1032. copyfile._Copy()
  1033. for linkfile in self.linkfiles:
  1034. linkfile._Link()
  1035. def GetCommitRevisionId(self):
  1036. """Get revisionId of a commit.
  1037. Use this method instead of GetRevisionId to get the id of the commit rather
  1038. than the id of the current git object (for example, a tag)
  1039. """
  1040. if not self.revisionExpr.startswith(R_TAGS):
  1041. return self.GetRevisionId(self._allrefs)
  1042. try:
  1043. return self.bare_git.rev_list(self.revisionExpr, '-1')[0]
  1044. except GitError:
  1045. raise ManifestInvalidRevisionError(
  1046. 'revision %s in %s not found' % (self.revisionExpr,
  1047. self.name))
  1048. def GetRevisionId(self, all_refs=None):
  1049. if self.revisionId:
  1050. return self.revisionId
  1051. rem = self.GetRemote(self.remote.name)
  1052. rev = rem.ToLocal(self.revisionExpr)
  1053. if all_refs is not None and rev in all_refs:
  1054. return all_refs[rev]
  1055. try:
  1056. return self.bare_git.rev_parse('--verify', '%s^0' % rev)
  1057. except GitError:
  1058. raise ManifestInvalidRevisionError(
  1059. 'revision %s in %s not found' % (self.revisionExpr,
  1060. self.name))
  1061. def Sync_LocalHalf(self, syncbuf, force_sync=False):
  1062. """Perform only the local IO portion of the sync process.
  1063. Network access is not required.
  1064. """
  1065. self._InitWorkTree(force_sync=force_sync)
  1066. all_refs = self.bare_ref.all
  1067. self.CleanPublishedCache(all_refs)
  1068. revid = self.GetRevisionId(all_refs)
  1069. def _doff():
  1070. self._FastForward(revid)
  1071. self._CopyAndLinkFiles()
  1072. head = self.work_git.GetHead()
  1073. if head.startswith(R_HEADS):
  1074. branch = head[len(R_HEADS):]
  1075. try:
  1076. head = all_refs[head]
  1077. except KeyError:
  1078. head = None
  1079. else:
  1080. branch = None
  1081. if branch is None or syncbuf.detach_head:
  1082. # Currently on a detached HEAD. The user is assumed to
  1083. # not have any local modifications worth worrying about.
  1084. #
  1085. if self.IsRebaseInProgress():
  1086. syncbuf.fail(self, _PriorSyncFailedError())
  1087. return
  1088. if head == revid:
  1089. # No changes; don't do anything further.
  1090. # Except if the head needs to be detached
  1091. #
  1092. if not syncbuf.detach_head:
  1093. # The copy/linkfile config may have changed.
  1094. self._CopyAndLinkFiles()
  1095. return
  1096. else:
  1097. lost = self._revlist(not_rev(revid), HEAD)
  1098. if lost:
  1099. syncbuf.info(self, "discarding %d commits", len(lost))
  1100. try:
  1101. self._Checkout(revid, quiet=True)
  1102. except GitError as e:
  1103. syncbuf.fail(self, e)
  1104. return
  1105. self._CopyAndLinkFiles()
  1106. return
  1107. if head == revid:
  1108. # No changes; don't do anything further.
  1109. #
  1110. # The copy/linkfile config may have changed.
  1111. self._CopyAndLinkFiles()
  1112. return
  1113. branch = self.GetBranch(branch)
  1114. if not branch.LocalMerge:
  1115. # The current branch has no tracking configuration.
  1116. # Jump off it to a detached HEAD.
  1117. #
  1118. syncbuf.info(self,
  1119. "leaving %s; does not track upstream",
  1120. branch.name)
  1121. try:
  1122. self._Checkout(revid, quiet=True)
  1123. except GitError as e:
  1124. syncbuf.fail(self, e)
  1125. return
  1126. self._CopyAndLinkFiles()
  1127. return
  1128. upstream_gain = self._revlist(not_rev(HEAD), revid)
  1129. pub = self.WasPublished(branch.name, all_refs)
  1130. if pub:
  1131. not_merged = self._revlist(not_rev(revid), pub)
  1132. if not_merged:
  1133. if upstream_gain:
  1134. # The user has published this branch and some of those
  1135. # commits are not yet merged upstream. We do not want
  1136. # to rewrite the published commits so we punt.
  1137. #
  1138. syncbuf.fail(self,
  1139. "branch %s is published (but not merged) and is now %d commits behind"
  1140. % (branch.name, len(upstream_gain)))
  1141. return
  1142. elif pub == head:
  1143. # All published commits are merged, and thus we are a
  1144. # strict subset. We can fast-forward safely.
  1145. #
  1146. syncbuf.later1(self, _doff)
  1147. return
  1148. # Examine the local commits not in the remote. Find the
  1149. # last one attributed to this user, if any.
  1150. #
  1151. local_changes = self._revlist(not_rev(revid), HEAD, format='%H %ce')
  1152. last_mine = None
  1153. cnt_mine = 0
  1154. for commit in local_changes:
  1155. commit_id, committer_email = commit.decode('utf-8').split(' ', 1)
  1156. if committer_email == self.UserEmail:
  1157. last_mine = commit_id
  1158. cnt_mine += 1
  1159. if not upstream_gain and cnt_mine == len(local_changes):
  1160. return
  1161. if self.IsDirty(consider_untracked=False):
  1162. syncbuf.fail(self, _DirtyError())
  1163. return
  1164. # If the upstream switched on us, warn the user.
  1165. #
  1166. if branch.merge != self.revisionExpr:
  1167. if branch.merge and self.revisionExpr:
  1168. syncbuf.info(self,
  1169. 'manifest switched %s...%s',
  1170. branch.merge,
  1171. self.revisionExpr)
  1172. elif branch.merge:
  1173. syncbuf.info(self,
  1174. 'manifest no longer tracks %s',
  1175. branch.merge)
  1176. if cnt_mine < len(local_changes):
  1177. # Upstream rebased. Not everything in HEAD
  1178. # was created by this user.
  1179. #
  1180. syncbuf.info(self,
  1181. "discarding %d commits removed from upstream",
  1182. len(local_changes) - cnt_mine)
  1183. branch.remote = self.GetRemote(self.remote.name)
  1184. if not ID_RE.match(self.revisionExpr):
  1185. # in case of manifest sync the revisionExpr might be a SHA1
  1186. branch.merge = self.revisionExpr
  1187. if not branch.merge.startswith('refs/'):
  1188. branch.merge = R_HEADS + branch.merge
  1189. branch.Save()
  1190. if cnt_mine > 0 and self.rebase:
  1191. def _dorebase():
  1192. self._Rebase(upstream='%s^1' % last_mine, onto=revid)
  1193. self._CopyAndLinkFiles()
  1194. syncbuf.later2(self, _dorebase)
  1195. elif local_changes:
  1196. try:
  1197. self._ResetHard(revid)
  1198. self._CopyAndLinkFiles()
  1199. except GitError as e:
  1200. syncbuf.fail(self, e)
  1201. return
  1202. else:
  1203. syncbuf.later1(self, _doff)
  1204. def AddCopyFile(self, src, dest, absdest):
  1205. # dest should already be an absolute path, but src is project relative
  1206. # make src an absolute path
  1207. abssrc = os.path.join(self.worktree, src)
  1208. self.copyfiles.append(_CopyFile(src, dest, abssrc, absdest))
  1209. def AddLinkFile(self, src, dest, absdest):
  1210. # dest should already be an absolute path, but src is project relative
  1211. # make src relative path to dest
  1212. absdestdir = os.path.dirname(absdest)
  1213. relsrc = os.path.relpath(os.path.join(self.worktree, src), absdestdir)
  1214. self.linkfiles.append(_LinkFile(self.worktree, src, dest, relsrc, absdest))
  1215. def AddAnnotation(self, name, value, keep):
  1216. self.annotations.append(_Annotation(name, value, keep))
  1217. def DownloadPatchSet(self, change_id, patch_id):
  1218. """Download a single patch set of a single change to FETCH_HEAD.
  1219. """
  1220. remote = self.GetRemote(self.remote.name)
  1221. cmd = ['fetch', remote.name]
  1222. cmd.append('refs/changes/%2.2d/%d/%d' \
  1223. % (change_id % 100, change_id, patch_id))
  1224. if GitCommand(self, cmd, bare=True).Wait() != 0:
  1225. return None
  1226. return DownloadedChange(self,
  1227. self.GetRevisionId(),
  1228. change_id,
  1229. patch_id,
  1230. self.bare_git.rev_parse('FETCH_HEAD'))
  1231. ## Branch Management ##
  1232. def StartBranch(self, name, branch_merge=''):
  1233. """Create a new branch off the manifest's revision.
  1234. """
  1235. if not branch_merge:
  1236. branch_merge = self.revisionExpr
  1237. head = self.work_git.GetHead()
  1238. if head == (R_HEADS + name):
  1239. return True
  1240. all_refs = self.bare_ref.all
  1241. if R_HEADS + name in all_refs:
  1242. return GitCommand(self,
  1243. ['checkout', name, '--'],
  1244. capture_stdout=True,
  1245. capture_stderr=True).Wait() == 0
  1246. branch = self.GetBranch(name)
  1247. branch.remote = self.GetRemote(self.remote.name)
  1248. branch.merge = branch_merge
  1249. if not branch.merge.startswith('refs/') and not ID_RE.match(branch_merge):
  1250. branch.merge = R_HEADS + branch_merge
  1251. revid = self.GetRevisionId(all_refs)
  1252. if head.startswith(R_HEADS):
  1253. try:
  1254. head = all_refs[head]
  1255. except KeyError:
  1256. head = None
  1257. if revid and head and revid == head:
  1258. ref = os.path.join(self.gitdir, R_HEADS + name)
  1259. try:
  1260. os.makedirs(os.path.dirname(ref))
  1261. except OSError:
  1262. pass
  1263. _lwrite(ref, '%s\n' % revid)
  1264. _lwrite(os.path.join(self.worktree, '.git', HEAD),
  1265. 'ref: %s%s\n' % (R_HEADS, name))
  1266. branch.Save()
  1267. return True
  1268. if GitCommand(self,
  1269. ['checkout', '-b', branch.name, revid],
  1270. capture_stdout=True,
  1271. capture_stderr=True).Wait() == 0:
  1272. branch.Save()
  1273. return True
  1274. return False
  1275. def CheckoutBranch(self, name):
  1276. """Checkout a local topic branch.
  1277. Args:
  1278. name: The name of the branch to checkout.
  1279. Returns:
  1280. True if the checkout succeeded; False if it didn't; None if the branch
  1281. didn't exist.
  1282. """
  1283. rev = R_HEADS + name
  1284. head = self.work_git.GetHead()
  1285. if head == rev:
  1286. # Already on the branch
  1287. #
  1288. return True
  1289. all_refs = self.bare_ref.all
  1290. try:
  1291. revid = all_refs[rev]
  1292. except KeyError:
  1293. # Branch does not exist in this project
  1294. #
  1295. return None
  1296. if head.startswith(R_HEADS):
  1297. try:
  1298. head = all_refs[head]
  1299. except KeyError:
  1300. head = None
  1301. if head == revid:
  1302. # Same revision; just update HEAD to point to the new
  1303. # target branch, but otherwise take no other action.
  1304. #
  1305. _lwrite(os.path.join(self.worktree, '.git', HEAD),
  1306. 'ref: %s%s\n' % (R_HEADS, name))
  1307. return True
  1308. return GitCommand(self,
  1309. ['checkout', name, '--'],
  1310. capture_stdout=True,
  1311. capture_stderr=True).Wait() == 0
  1312. def AbandonBranch(self, name):
  1313. """Destroy a local topic branch.
  1314. Args:
  1315. name: The name of the branch to abandon.
  1316. Returns:
  1317. True if the abandon succeeded; False if it didn't; None if the branch
  1318. didn't exist.
  1319. """
  1320. rev = R_HEADS + name
  1321. all_refs = self.bare_ref.all
  1322. if rev not in all_refs:
  1323. # Doesn't exist
  1324. return None
  1325. head = self.work_git.GetHead()
  1326. if head == rev:
  1327. # We can't destroy the branch while we are sitting
  1328. # on it. Switch to a detached HEAD.
  1329. #
  1330. head = all_refs[head]
  1331. revid = self.GetRevisionId(all_refs)
  1332. if head == revid:
  1333. _lwrite(os.path.join(self.worktree, '.git', HEAD),
  1334. '%s\n' % revid)
  1335. else:
  1336. self._Checkout(revid, quiet=True)
  1337. return GitCommand(self,
  1338. ['branch', '-D', name],
  1339. capture_stdout=True,
  1340. capture_stderr=True).Wait() == 0
  1341. def PruneHeads(self):
  1342. """Prune any topic branches already merged into upstream.
  1343. """
  1344. cb = self.CurrentBranch
  1345. kill = []
  1346. left = self._allrefs
  1347. for name in left.keys():
  1348. if name.startswith(R_HEADS):
  1349. name = name[len(R_HEADS):]
  1350. if cb is None or name != cb:
  1351. kill.append(name)
  1352. rev = self.GetRevisionId(left)
  1353. if cb is not None \
  1354. and not self._revlist(HEAD + '...' + rev) \
  1355. and not self.IsDirty(consider_untracked=False):
  1356. self.work_git.DetachHead(HEAD)
  1357. kill.append(cb)
  1358. if kill:
  1359. old = self.bare_git.GetHead()
  1360. if old is None:
  1361. old = 'refs/heads/please_never_use_this_as_a_branch_name'
  1362. try:
  1363. self.bare_git.DetachHead(rev)
  1364. b = ['branch', '-d']
  1365. b.extend(kill)
  1366. b = GitCommand(self, b, bare=True,
  1367. capture_stdout=True,
  1368. capture_stderr=True)
  1369. b.Wait()
  1370. finally:
  1371. self.bare_git.SetHead(old)
  1372. left = self._allrefs
  1373. for branch in kill:
  1374. if (R_HEADS + branch) not in left:
  1375. self.CleanPublishedCache()
  1376. break
  1377. if cb and cb not in kill:
  1378. kill.append(cb)
  1379. kill.sort()
  1380. kept = []
  1381. for branch in kill:
  1382. if R_HEADS + branch in left:
  1383. branch = self.GetBranch(branch)
  1384. base = branch.LocalMerge
  1385. if not base:
  1386. base = rev
  1387. kept.append(ReviewableBranch(self, branch, base))
  1388. return kept
  1389. ## Submodule Management ##
  1390. def GetRegisteredSubprojects(self):
  1391. result = []
  1392. def rec(subprojects):
  1393. if not subprojects:
  1394. return
  1395. result.extend(subprojects)
  1396. for p in subprojects:
  1397. rec(p.subprojects)
  1398. rec(self.subprojects)
  1399. return result
  1400. def _GetSubmodules(self):
  1401. # Unfortunately we cannot call `git submodule status --recursive` here
  1402. # because the working tree might not exist yet, and it cannot be used
  1403. # without a working tree in its current implementation.
  1404. def get_submodules(gitdir, rev):
  1405. # Parse .gitmodules for submodule sub_paths and sub_urls
  1406. sub_paths, sub_urls = parse_gitmodules(gitdir, rev)
  1407. if not sub_paths:
  1408. return []
  1409. # Run `git ls-tree` to read SHAs of submodule object, which happen to be
  1410. # revision of submodule repository
  1411. sub_revs = git_ls_tree(gitdir, rev, sub_paths)
  1412. submodules = []
  1413. for sub_path, sub_url in zip(sub_paths, sub_urls):
  1414. try:
  1415. sub_rev = sub_revs[sub_path]
  1416. except KeyError:
  1417. # Ignore non-exist submodules
  1418. continue
  1419. submodules.append((sub_rev, sub_path, sub_url))
  1420. return submodules
  1421. re_path = re.compile(r'^submodule\.([^.]+)\.path=(.*)$')
  1422. re_url = re.compile(r'^submodule\.([^.]+)\.url=(.*)$')
  1423. def parse_gitmodules(gitdir, rev):
  1424. cmd = ['cat-file', 'blob', '%s:.gitmodules' % rev]
  1425. try:
  1426. p = GitCommand(None, cmd, capture_stdout=True, capture_stderr=True,
  1427. bare=True, gitdir=gitdir)
  1428. except GitError:
  1429. return [], []
  1430. if p.Wait() != 0:
  1431. return [], []
  1432. gitmodules_lines = []
  1433. fd, temp_gitmodules_path = tempfile.mkstemp()
  1434. try:
  1435. os.write(fd, p.stdout)
  1436. os.close(fd)
  1437. cmd = ['config', '--file', temp_gitmodules_path, '--list']
  1438. p = GitCommand(None, cmd, capture_stdout=True, capture_stderr=True,
  1439. bare=True, gitdir=gitdir)
  1440. if p.Wait() != 0:
  1441. return [], []
  1442. gitmodules_lines = p.stdout.split('\n')
  1443. except GitError:
  1444. return [], []
  1445. finally:
  1446. os.remove(temp_gitmodules_path)
  1447. names = set()
  1448. paths = {}
  1449. urls = {}
  1450. for line in gitmodules_lines:
  1451. if not line:
  1452. continue
  1453. m = re_path.match(line)
  1454. if m:
  1455. names.add(m.group(1))
  1456. paths[m.group(1)] = m.group(2)
  1457. continue
  1458. m = re_url.match(line)
  1459. if m:
  1460. names.add(m.group(1))
  1461. urls[m.group(1)] = m.group(2)
  1462. continue
  1463. names = sorted(names)
  1464. return ([paths.get(name, '') for name in names],
  1465. [urls.get(name, '') for name in names])
  1466. def git_ls_tree(gitdir, rev, paths):
  1467. cmd = ['ls-tree', rev, '--']
  1468. cmd.extend(paths)
  1469. try:
  1470. p = GitCommand(None, cmd, capture_stdout=True, capture_stderr=True,
  1471. bare=True, gitdir=gitdir)
  1472. except GitError:
  1473. return []
  1474. if p.Wait() != 0:
  1475. return []
  1476. objects = {}
  1477. for line in p.stdout.split('\n'):
  1478. if not line.strip():
  1479. continue
  1480. object_rev, object_path = line.split()[2:4]
  1481. objects[object_path] = object_rev
  1482. return objects
  1483. try:
  1484. rev = self.GetRevisionId()
  1485. except GitError:
  1486. return []
  1487. return get_submodules(self.gitdir, rev)
  1488. def GetDerivedSubprojects(self):
  1489. result = []
  1490. if not self.Exists:
  1491. # If git repo does not exist yet, querying its submodules will
  1492. # mess up its states; so return here.
  1493. return result
  1494. for rev, path, url in self._GetSubmodules():
  1495. name = self.manifest.GetSubprojectName(self, path)
  1496. relpath, worktree, gitdir, objdir = \
  1497. self.manifest.GetSubprojectPaths(self, name, path)
  1498. project = self.manifest.paths.get(relpath)
  1499. if project:
  1500. result.extend(project.GetDerivedSubprojects())
  1501. continue
  1502. remote = RemoteSpec(self.remote.name,
  1503. url=url,
  1504. review=self.remote.review,
  1505. revision=self.remote.revision)
  1506. subproject = Project(manifest=self.manifest,
  1507. name=name,
  1508. remote=remote,
  1509. gitdir=gitdir,
  1510. objdir=objdir,
  1511. worktree=worktree,
  1512. relpath=relpath,
  1513. revisionExpr=self.revisionExpr,
  1514. revisionId=rev,
  1515. rebase=self.rebase,
  1516. groups=self.groups,
  1517. sync_c=self.sync_c,
  1518. sync_s=self.sync_s,
  1519. parent=self,
  1520. is_derived=True)
  1521. result.append(subproject)
  1522. result.extend(subproject.GetDerivedSubprojects())
  1523. return result
  1524. ## Direct Git Commands ##
  1525. def _CheckForSha1(self):
  1526. try:
  1527. # if revision (sha or tag) is not present then following function
  1528. # throws an error.
  1529. self.bare_git.rev_parse('--verify', '%s^0' % self.revisionExpr)
  1530. return True
  1531. except GitError:
  1532. # There is no such persistent revision. We have to fetch it.
  1533. return False
  1534. def _FetchArchive(self, tarpath, cwd=None):
  1535. cmd = ['archive', '-v', '-o', tarpath]
  1536. cmd.append('--remote=%s' % self.remote.url)
  1537. cmd.append('--prefix=%s/' % self.relpath)
  1538. cmd.append(self.revisionExpr)
  1539. command = GitCommand(self, cmd, cwd=cwd,
  1540. capture_stdout=True,
  1541. capture_stderr=True)
  1542. if command.Wait() != 0:
  1543. raise GitError('git archive %s: %s' % (self.name, command.stderr))
  1544. def _RemoteFetch(self, name=None,
  1545. current_branch_only=False,
  1546. initial=False,
  1547. quiet=False,
  1548. alt_dir=None,
  1549. no_tags=False):
  1550. is_sha1 = False
  1551. tag_name = None
  1552. depth = None
  1553. # The depth should not be used when fetching to a mirror because
  1554. # it will result in a shallow repository that cannot be cloned or
  1555. # fetched from.
  1556. if not self.manifest.IsMirror:
  1557. if self.clone_depth:
  1558. depth = self.clone_depth
  1559. else:
  1560. depth = self.manifest.manifestProject.config.GetString('repo.depth')
  1561. # The repo project should never be synced with partial depth
  1562. if self.relpath == '.repo/repo':
  1563. depth = None
  1564. if depth:
  1565. current_branch_only = True
  1566. if ID_RE.match(self.revisionExpr) is not None:
  1567. is_sha1 = True
  1568. if current_branch_only:
  1569. if self.revisionExpr.startswith(R_TAGS):
  1570. # this is a tag and its sha1 value should never change
  1571. tag_name = self.revisionExpr[len(R_TAGS):]
  1572. if is_sha1 or tag_name is not None:
  1573. if self._CheckForSha1():
  1574. return True
  1575. if is_sha1 and not depth:
  1576. # When syncing a specific commit and --depth is not set:
  1577. # * if upstream is explicitly specified and is not a sha1, fetch only
  1578. # upstream as users expect only upstream to be fetch.
  1579. # Note: The commit might not be in upstream in which case the sync
  1580. # will fail.
  1581. # * otherwise, fetch all branches to make sure we end up with the
  1582. # specific commit.
  1583. current_branch_only = self.upstream and not ID_RE.match(self.upstream)
  1584. if not name:
  1585. name = self.remote.name
  1586. ssh_proxy = False
  1587. remote = self.GetRemote(name)
  1588. if remote.PreConnectFetch():
  1589. ssh_proxy = True
  1590. if initial:
  1591. if alt_dir and 'objects' == os.path.basename(alt_dir):
  1592. ref_dir = os.path.dirname(alt_dir)
  1593. packed_refs = os.path.join(self.gitdir, 'packed-refs')
  1594. remote = self.GetRemote(name)
  1595. all_refs = self.bare_ref.all
  1596. ids = set(all_refs.values())
  1597. tmp = set()
  1598. for r, ref_id in GitRefs(ref_dir).all.items():
  1599. if r not in all_refs:
  1600. if r.startswith(R_TAGS) or remote.WritesTo(r):
  1601. all_refs[r] = ref_id
  1602. ids.add(ref_id)
  1603. continue
  1604. if ref_id in ids:
  1605. continue
  1606. r = 'refs/_alt/%s' % ref_id
  1607. all_refs[r] = ref_id
  1608. ids.add(ref_id)
  1609. tmp.add(r)
  1610. tmp_packed = ''
  1611. old_packed = ''
  1612. for r in sorted(all_refs):
  1613. line = '%s %s\n' % (all_refs[r], r)
  1614. tmp_packed += line
  1615. if r not in tmp:
  1616. old_packed += line
  1617. _lwrite(packed_refs, tmp_packed)
  1618. else:
  1619. alt_dir = None
  1620. cmd = ['fetch']
  1621. if depth:
  1622. cmd.append('--depth=%s' % depth)
  1623. else:
  1624. # If this repo has shallow objects, then we don't know which refs have
  1625. # shallow objects or not. Tell git to unshallow all fetched refs. Don't
  1626. # do this with projects that don't have shallow objects, since it is less
  1627. # efficient.
  1628. if os.path.exists(os.path.join(self.gitdir, 'shallow')):
  1629. cmd.append('--depth=2147483647')
  1630. if quiet:
  1631. cmd.append('--quiet')
  1632. if not self.worktree:
  1633. cmd.append('--update-head-ok')
  1634. cmd.append(name)
  1635. # If using depth then we should not get all the tags since they may
  1636. # be outside of the depth.
  1637. if no_tags or depth:
  1638. cmd.append('--no-tags')
  1639. else:
  1640. cmd.append('--tags')
  1641. spec = []
  1642. if not current_branch_only:
  1643. # Fetch whole repo
  1644. spec.append(str((u'+refs/heads/*:') + remote.ToLocal('refs/heads/*')))
  1645. elif tag_name is not None:
  1646. spec.append('tag')
  1647. spec.append(tag_name)
  1648. if not self.manifest.IsMirror:
  1649. branch = self.revisionExpr
  1650. if is_sha1 and depth and git_require((1, 8, 3)):
  1651. # Shallow checkout of a specific commit, fetch from that commit and not
  1652. # the heads only as the commit might be deeper in the history.
  1653. spec.append(branch)
  1654. else:
  1655. if is_sha1:
  1656. branch = self.upstream
  1657. if branch is not None and branch.strip():
  1658. if not branch.startswith('refs/'):
  1659. branch = R_HEADS + branch
  1660. spec.append(str((u'+%s:' % branch) + remote.ToLocal(branch)))
  1661. cmd.extend(spec)
  1662. ok = False
  1663. for _i in range(2):
  1664. gitcmd = GitCommand(self, cmd, bare=True, ssh_proxy=ssh_proxy)
  1665. ret = gitcmd.Wait()
  1666. if ret == 0:
  1667. ok = True
  1668. break
  1669. # If needed, run the 'git remote prune' the first time through the loop
  1670. elif (not _i and
  1671. "error:" in gitcmd.stderr and
  1672. "git remote prune" in gitcmd.stderr):
  1673. prunecmd = GitCommand(self, ['remote', 'prune', name], bare=True,
  1674. ssh_proxy=ssh_proxy)
  1675. ret = prunecmd.Wait()
  1676. if ret:
  1677. break
  1678. continue
  1679. elif current_branch_only and is_sha1 and ret == 128:
  1680. # Exit code 128 means "couldn't find the ref you asked for"; if we're in sha1
  1681. # mode, we just tried sync'ing from the upstream field; it doesn't exist, thus
  1682. # abort the optimization attempt and do a full sync.
  1683. break
  1684. elif ret < 0:
  1685. # Git died with a signal, exit immediately
  1686. break
  1687. time.sleep(random.randint(30, 45))
  1688. if initial:
  1689. if alt_dir:
  1690. if old_packed != '':
  1691. _lwrite(packed_refs, old_packed)
  1692. else:
  1693. os.remove(packed_refs)
  1694. self.bare_git.pack_refs('--all', '--prune')
  1695. if is_sha1 and current_branch_only and self.upstream:
  1696. # We just synced the upstream given branch; verify we
  1697. # got what we wanted, else trigger a second run of all
  1698. # refs.
  1699. if not self._CheckForSha1():
  1700. if not depth:
  1701. # Avoid infinite recursion when depth is True (since depth implies
  1702. # current_branch_only)
  1703. return self._RemoteFetch(name=name, current_branch_only=False,
  1704. initial=False, quiet=quiet, alt_dir=alt_dir)
  1705. if self.clone_depth:
  1706. self.clone_depth = None
  1707. return self._RemoteFetch(name=name, current_branch_only=current_branch_only,
  1708. initial=False, quiet=quiet, alt_dir=alt_dir)
  1709. return ok
  1710. def _ApplyCloneBundle(self, initial=False, quiet=False):
  1711. if initial and (self.manifest.manifestProject.config.GetString('repo.depth') or self.clone_depth):
  1712. return False
  1713. remote = self.GetRemote(self.remote.name)
  1714. bundle_url = remote.url + '/clone.bundle'
  1715. bundle_url = GitConfig.ForUser().UrlInsteadOf(bundle_url)
  1716. if GetSchemeFromUrl(bundle_url) not in (
  1717. 'http', 'https', 'persistent-http', 'persistent-https'):
  1718. return False
  1719. bundle_dst = os.path.join(self.gitdir, 'clone.bundle')
  1720. bundle_tmp = os.path.join(self.gitdir, 'clone.bundle.tmp')
  1721. exist_dst = os.path.exists(bundle_dst)
  1722. exist_tmp = os.path.exists(bundle_tmp)
  1723. if not initial and not exist_dst and not exist_tmp:
  1724. return False
  1725. if not exist_dst:
  1726. exist_dst = self._FetchBundle(bundle_url, bundle_tmp, bundle_dst, quiet)
  1727. if not exist_dst:
  1728. return False
  1729. cmd = ['fetch']
  1730. if quiet:
  1731. cmd.append('--quiet')
  1732. if not self.worktree:
  1733. cmd.append('--update-head-ok')
  1734. cmd.append(bundle_dst)
  1735. for f in remote.fetch:
  1736. cmd.append(str(f))
  1737. cmd.append('refs/tags/*:refs/tags/*')
  1738. ok = GitCommand(self, cmd, bare=True).Wait() == 0
  1739. if os.path.exists(bundle_dst):
  1740. os.remove(bundle_dst)
  1741. if os.path.exists(bundle_tmp):
  1742. os.remove(bundle_tmp)
  1743. return ok
  1744. def _FetchBundle(self, srcUrl, tmpPath, dstPath, quiet):
  1745. if os.path.exists(dstPath):
  1746. os.remove(dstPath)
  1747. cmd = ['curl', '--fail', '--output', tmpPath, '--netrc', '--location']
  1748. if quiet:
  1749. cmd += ['--silent']
  1750. if os.path.exists(tmpPath):
  1751. size = os.stat(tmpPath).st_size
  1752. if size >= 1024:
  1753. cmd += ['--continue-at', '%d' % (size,)]
  1754. else:
  1755. os.remove(tmpPath)
  1756. if 'http_proxy' in os.environ and 'darwin' == sys.platform:
  1757. cmd += ['--proxy', os.environ['http_proxy']]
  1758. with GetUrlCookieFile(srcUrl, quiet) as (cookiefile, proxy):
  1759. if cookiefile:
  1760. cmd += ['--cookie', cookiefile, '--cookie-jar', cookiefile]
  1761. if srcUrl.startswith('persistent-'):
  1762. srcUrl = srcUrl[len('persistent-'):]
  1763. cmd += [srcUrl]
  1764. if IsTrace():
  1765. Trace('%s', ' '.join(cmd))
  1766. try:
  1767. proc = subprocess.Popen(cmd)
  1768. except OSError:
  1769. return False
  1770. curlret = proc.wait()
  1771. if curlret == 22:
  1772. # From curl man page:
  1773. # 22: HTTP page not retrieved. The requested url was not found or
  1774. # returned another error with the HTTP error code being 400 or above.
  1775. # This return code only appears if -f, --fail is used.
  1776. if not quiet:
  1777. print("Server does not provide clone.bundle; ignoring.",
  1778. file=sys.stderr)
  1779. return False
  1780. if os.path.exists(tmpPath):
  1781. if curlret == 0 and self._IsValidBundle(tmpPath, quiet):
  1782. os.rename(tmpPath, dstPath)
  1783. return True
  1784. else:
  1785. os.remove(tmpPath)
  1786. return False
  1787. else:
  1788. return False
  1789. def _IsValidBundle(self, path, quiet):
  1790. try:
  1791. with open(path) as f:
  1792. if f.read(16) == '# v2 git bundle\n':
  1793. return True
  1794. else:
  1795. if not quiet:
  1796. print("Invalid clone.bundle file; ignoring.", file=sys.stderr)
  1797. return False
  1798. except OSError:
  1799. return False
  1800. def _Checkout(self, rev, quiet=False):
  1801. cmd = ['checkout']
  1802. if quiet:
  1803. cmd.append('-q')
  1804. cmd.append(rev)
  1805. cmd.append('--')
  1806. if GitCommand(self, cmd).Wait() != 0:
  1807. if self._allrefs:
  1808. raise GitError('%s checkout %s ' % (self.name, rev))
  1809. def _CherryPick(self, rev):
  1810. cmd = ['cherry-pick']
  1811. cmd.append(rev)
  1812. cmd.append('--')
  1813. if GitCommand(self, cmd).Wait() != 0:
  1814. if self._allrefs:
  1815. raise GitError('%s cherry-pick %s ' % (self.name, rev))
  1816. def _Revert(self, rev):
  1817. cmd = ['revert']
  1818. cmd.append('--no-edit')
  1819. cmd.append(rev)
  1820. cmd.append('--')
  1821. if GitCommand(self, cmd).Wait() != 0:
  1822. if self._allrefs:
  1823. raise GitError('%s revert %s ' % (self.name, rev))
  1824. def _ResetHard(self, rev, quiet=True):
  1825. cmd = ['reset', '--hard']
  1826. if quiet:
  1827. cmd.append('-q')
  1828. cmd.append(rev)
  1829. if GitCommand(self, cmd).Wait() != 0:
  1830. raise GitError('%s reset --hard %s ' % (self.name, rev))
  1831. def _Rebase(self, upstream, onto=None):
  1832. cmd = ['rebase']
  1833. if onto is not None:
  1834. cmd.extend(['--onto', onto])
  1835. cmd.append(upstream)
  1836. if GitCommand(self, cmd).Wait() != 0:
  1837. raise GitError('%s rebase %s ' % (self.name, upstream))
  1838. def _FastForward(self, head, ffonly=False):
  1839. cmd = ['merge', head]
  1840. if ffonly:
  1841. cmd.append("--ff-only")
  1842. if GitCommand(self, cmd).Wait() != 0:
  1843. raise GitError('%s merge %s ' % (self.name, head))
  1844. def _InitGitDir(self, mirror_git=None, force_sync=False):
  1845. init_git_dir = not os.path.exists(self.gitdir)
  1846. init_obj_dir = not os.path.exists(self.objdir)
  1847. try:
  1848. # Initialize the bare repository, which contains all of the objects.
  1849. if init_obj_dir:
  1850. os.makedirs(self.objdir)
  1851. self.bare_objdir.init()
  1852. # If we have a separate directory to hold refs, initialize it as well.
  1853. if self.objdir != self.gitdir:
  1854. if init_git_dir:
  1855. os.makedirs(self.gitdir)
  1856. if init_obj_dir or init_git_dir:
  1857. self._ReferenceGitDir(self.objdir, self.gitdir, share_refs=False,
  1858. copy_all=True)
  1859. try:
  1860. self._CheckDirReference(self.objdir, self.gitdir, share_refs=False)
  1861. except GitError as e:
  1862. if force_sync:
  1863. print("Retrying clone after deleting %s" % self.gitdir, file=sys.stderr)
  1864. try:
  1865. shutil.rmtree(os.path.realpath(self.gitdir))
  1866. if self.worktree and os.path.exists(
  1867. os.path.realpath(self.worktree)):
  1868. shutil.rmtree(os.path.realpath(self.worktree))
  1869. return self._InitGitDir(mirror_git=mirror_git, force_sync=False)
  1870. except:
  1871. raise e
  1872. raise e
  1873. if init_git_dir:
  1874. mp = self.manifest.manifestProject
  1875. ref_dir = mp.config.GetString('repo.reference') or ''
  1876. if ref_dir or mirror_git:
  1877. if not mirror_git:
  1878. mirror_git = os.path.join(ref_dir, self.name + '.git')
  1879. repo_git = os.path.join(ref_dir, '.repo', 'projects',
  1880. self.relpath + '.git')
  1881. if os.path.exists(mirror_git):
  1882. ref_dir = mirror_git
  1883. elif os.path.exists(repo_git):
  1884. ref_dir = repo_git
  1885. else:
  1886. ref_dir = None
  1887. if ref_dir:
  1888. _lwrite(os.path.join(self.gitdir, 'objects/info/alternates'),
  1889. os.path.join(ref_dir, 'objects') + '\n')
  1890. self._UpdateHooks()
  1891. m = self.manifest.manifestProject.config
  1892. for key in ['user.name', 'user.email']:
  1893. if m.Has(key, include_defaults=False):
  1894. self.config.SetString(key, m.GetString(key))
  1895. if self.manifest.IsMirror:
  1896. self.config.SetString('core.bare', 'true')
  1897. else:
  1898. self.config.SetString('core.bare', None)
  1899. except Exception:
  1900. if init_obj_dir and os.path.exists(self.objdir):
  1901. shutil.rmtree(self.objdir)
  1902. if init_git_dir and os.path.exists(self.gitdir):
  1903. shutil.rmtree(self.gitdir)
  1904. raise
  1905. def _UpdateHooks(self):
  1906. if os.path.exists(self.gitdir):
  1907. self._InitHooks()
  1908. def _InitHooks(self):
  1909. hooks = os.path.realpath(self._gitdir_path('hooks'))
  1910. if not os.path.exists(hooks):
  1911. os.makedirs(hooks)
  1912. for stock_hook in _ProjectHooks():
  1913. name = os.path.basename(stock_hook)
  1914. if name in ('commit-msg',) and not self.remote.review \
  1915. and not self is self.manifest.manifestProject:
  1916. # Don't install a Gerrit Code Review hook if this
  1917. # project does not appear to use it for reviews.
  1918. #
  1919. # Since the manifest project is one of those, but also
  1920. # managed through gerrit, it's excluded
  1921. continue
  1922. dst = os.path.join(hooks, name)
  1923. if os.path.islink(dst):
  1924. continue
  1925. if os.path.exists(dst):
  1926. if filecmp.cmp(stock_hook, dst, shallow=False):
  1927. os.remove(dst)
  1928. else:
  1929. _warn("%s: Not replacing locally modified %s hook", self.relpath, name)
  1930. continue
  1931. try:
  1932. os.symlink(os.path.relpath(stock_hook, os.path.dirname(dst)), dst)
  1933. except OSError as e:
  1934. if e.errno == errno.EPERM:
  1935. raise GitError('filesystem must support symlinks')
  1936. else:
  1937. raise
  1938. def _InitRemote(self):
  1939. if self.remote.url:
  1940. remote = self.GetRemote(self.remote.name)
  1941. remote.url = self.remote.url
  1942. remote.review = self.remote.review
  1943. remote.projectname = self.name
  1944. if self.worktree:
  1945. remote.ResetFetch(mirror=False)
  1946. else:
  1947. remote.ResetFetch(mirror=True)
  1948. remote.Save()
  1949. def _InitMRef(self):
  1950. if self.manifest.branch:
  1951. self._InitAnyMRef(R_M + self.manifest.branch)
  1952. def _InitMirrorHead(self):
  1953. self._InitAnyMRef(HEAD)
  1954. def _InitAnyMRef(self, ref):
  1955. cur = self.bare_ref.symref(ref)
  1956. if self.revisionId:
  1957. if cur != '' or self.bare_ref.get(ref) != self.revisionId:
  1958. msg = 'manifest set to %s' % self.revisionId
  1959. dst = self.revisionId + '^0'
  1960. self.bare_git.UpdateRef(ref, dst, message=msg, detach=True)
  1961. else:
  1962. remote = self.GetRemote(self.remote.name)
  1963. dst = remote.ToLocal(self.revisionExpr)
  1964. if cur != dst:
  1965. msg = 'manifest set to %s' % self.revisionExpr
  1966. self.bare_git.symbolic_ref('-m', msg, ref, dst)
  1967. def _CheckDirReference(self, srcdir, destdir, share_refs):
  1968. symlink_files = self.shareable_files
  1969. symlink_dirs = self.shareable_dirs
  1970. if share_refs:
  1971. symlink_files += self.working_tree_files
  1972. symlink_dirs += self.working_tree_dirs
  1973. to_symlink = symlink_files + symlink_dirs
  1974. for name in set(to_symlink):
  1975. dst = os.path.realpath(os.path.join(destdir, name))
  1976. if os.path.lexists(dst):
  1977. src = os.path.realpath(os.path.join(srcdir, name))
  1978. # Fail if the links are pointing to the wrong place
  1979. if src != dst:
  1980. raise GitError('--force-sync not enabled; cannot overwrite a local '
  1981. 'work tree. If you\'re comfortable with the '
  1982. 'possibility of losing the work tree\'s git metadata,'
  1983. ' use `repo sync --force-sync {0}` to '
  1984. 'proceed.'.format(self.relpath))
  1985. def _ReferenceGitDir(self, gitdir, dotgit, share_refs, copy_all):
  1986. """Update |dotgit| to reference |gitdir|, using symlinks where possible.
  1987. Args:
  1988. gitdir: The bare git repository. Must already be initialized.
  1989. dotgit: The repository you would like to initialize.
  1990. share_refs: If true, |dotgit| will store its refs under |gitdir|.
  1991. Only one work tree can store refs under a given |gitdir|.
  1992. copy_all: If true, copy all remaining files from |gitdir| -> |dotgit|.
  1993. This saves you the effort of initializing |dotgit| yourself.
  1994. """
  1995. symlink_files = self.shareable_files
  1996. symlink_dirs = self.shareable_dirs
  1997. if share_refs:
  1998. symlink_files += self.working_tree_files
  1999. symlink_dirs += self.working_tree_dirs
  2000. to_symlink = symlink_files + symlink_dirs
  2001. to_copy = []
  2002. if copy_all:
  2003. to_copy = os.listdir(gitdir)
  2004. dotgit = os.path.realpath(dotgit)
  2005. for name in set(to_copy).union(to_symlink):
  2006. try:
  2007. src = os.path.realpath(os.path.join(gitdir, name))
  2008. dst = os.path.join(dotgit, name)
  2009. if os.path.lexists(dst):
  2010. continue
  2011. # If the source dir doesn't exist, create an empty dir.
  2012. if name in symlink_dirs and not os.path.lexists(src):
  2013. os.makedirs(src)
  2014. # If the source file doesn't exist, ensure the destination
  2015. # file doesn't either.
  2016. if name in symlink_files and not os.path.lexists(src):
  2017. try:
  2018. os.remove(dst)
  2019. except OSError:
  2020. pass
  2021. if name in to_symlink:
  2022. os.symlink(os.path.relpath(src, os.path.dirname(dst)), dst)
  2023. elif copy_all and not os.path.islink(dst):
  2024. if os.path.isdir(src):
  2025. shutil.copytree(src, dst)
  2026. elif os.path.isfile(src):
  2027. shutil.copy(src, dst)
  2028. except OSError as e:
  2029. if e.errno == errno.EPERM:
  2030. raise DownloadError('filesystem must support symlinks')
  2031. else:
  2032. raise
  2033. def _InitWorkTree(self, force_sync=False):
  2034. dotgit = os.path.join(self.worktree, '.git')
  2035. init_dotgit = not os.path.exists(dotgit)
  2036. try:
  2037. if init_dotgit:
  2038. os.makedirs(dotgit)
  2039. self._ReferenceGitDir(self.gitdir, dotgit, share_refs=True,
  2040. copy_all=False)
  2041. try:
  2042. self._CheckDirReference(self.gitdir, dotgit, share_refs=True)
  2043. except GitError as e:
  2044. if force_sync:
  2045. try:
  2046. shutil.rmtree(dotgit)
  2047. return self._InitWorkTree(force_sync=False)
  2048. except:
  2049. raise e
  2050. raise e
  2051. if init_dotgit:
  2052. _lwrite(os.path.join(dotgit, HEAD), '%s\n' % self.GetRevisionId())
  2053. cmd = ['read-tree', '--reset', '-u']
  2054. cmd.append('-v')
  2055. cmd.append(HEAD)
  2056. if GitCommand(self, cmd).Wait() != 0:
  2057. raise GitError("cannot initialize work tree")
  2058. self._CopyAndLinkFiles()
  2059. except Exception:
  2060. if init_dotgit:
  2061. shutil.rmtree(dotgit)
  2062. raise
  2063. def _gitdir_path(self, path):
  2064. return os.path.realpath(os.path.join(self.gitdir, path))
  2065. def _revlist(self, *args, **kw):
  2066. a = []
  2067. a.extend(args)
  2068. a.append('--')
  2069. return self.work_git.rev_list(*a, **kw)
  2070. @property
  2071. def _allrefs(self):
  2072. return self.bare_ref.all
  2073. def _getLogs(self, rev1, rev2, oneline=False, color=True):
  2074. """Get logs between two revisions of this project."""
  2075. comp = '..'
  2076. if rev1:
  2077. revs = [rev1]
  2078. if rev2:
  2079. revs.extend([comp, rev2])
  2080. cmd = ['log', ''.join(revs)]
  2081. out = DiffColoring(self.config)
  2082. if out.is_on and color:
  2083. cmd.append('--color')
  2084. if oneline:
  2085. cmd.append('--oneline')
  2086. try:
  2087. log = GitCommand(self, cmd, capture_stdout=True, capture_stderr=True)
  2088. if log.Wait() == 0:
  2089. return log.stdout
  2090. except GitError:
  2091. # worktree may not exist if groups changed for example. In that case,
  2092. # try in gitdir instead.
  2093. if not os.path.exists(self.worktree):
  2094. return self.bare_git.log(*cmd[1:])
  2095. else:
  2096. raise
  2097. return None
  2098. def getAddedAndRemovedLogs(self, toProject, oneline=False, color=True):
  2099. """Get the list of logs from this revision to given revisionId"""
  2100. logs = {}
  2101. selfId = self.GetRevisionId(self._allrefs)
  2102. toId = toProject.GetRevisionId(toProject._allrefs)
  2103. logs['added'] = self._getLogs(selfId, toId, oneline=oneline, color=color)
  2104. logs['removed'] = self._getLogs(toId, selfId, oneline=oneline, color=color)
  2105. return logs
  2106. class _GitGetByExec(object):
  2107. def __init__(self, project, bare, gitdir):
  2108. self._project = project
  2109. self._bare = bare
  2110. self._gitdir = gitdir
  2111. def LsOthers(self):
  2112. p = GitCommand(self._project,
  2113. ['ls-files',
  2114. '-z',
  2115. '--others',
  2116. '--exclude-standard'],
  2117. bare=False,
  2118. gitdir=self._gitdir,
  2119. capture_stdout=True,
  2120. capture_stderr=True)
  2121. if p.Wait() == 0:
  2122. out = p.stdout
  2123. if out:
  2124. return out[:-1].split('\0') # pylint: disable=W1401
  2125. # Backslash is not anomalous
  2126. return []
  2127. def DiffZ(self, name, *args):
  2128. cmd = [name]
  2129. cmd.append('-z')
  2130. cmd.extend(args)
  2131. p = GitCommand(self._project,
  2132. cmd,
  2133. gitdir=self._gitdir,
  2134. bare=False,
  2135. capture_stdout=True,
  2136. capture_stderr=True)
  2137. try:
  2138. out = p.process.stdout.read()
  2139. r = {}
  2140. if out:
  2141. out = iter(out[:-1].split('\0')) # pylint: disable=W1401
  2142. while out:
  2143. try:
  2144. info = next(out)
  2145. path = next(out)
  2146. except StopIteration:
  2147. break
  2148. class _Info(object):
  2149. def __init__(self, path, omode, nmode, oid, nid, state):
  2150. self.path = path
  2151. self.src_path = None
  2152. self.old_mode = omode
  2153. self.new_mode = nmode
  2154. self.old_id = oid
  2155. self.new_id = nid
  2156. if len(state) == 1:
  2157. self.status = state
  2158. self.level = None
  2159. else:
  2160. self.status = state[:1]
  2161. self.level = state[1:]
  2162. while self.level.startswith('0'):
  2163. self.level = self.level[1:]
  2164. info = info[1:].split(' ')
  2165. info = _Info(path, *info)
  2166. if info.status in ('R', 'C'):
  2167. info.src_path = info.path
  2168. info.path = next(out)
  2169. r[info.path] = info
  2170. return r
  2171. finally:
  2172. p.Wait()
  2173. def GetHead(self):
  2174. if self._bare:
  2175. path = os.path.join(self._project.gitdir, HEAD)
  2176. else:
  2177. path = os.path.join(self._project.worktree, '.git', HEAD)
  2178. try:
  2179. fd = open(path, 'rb')
  2180. except IOError as e:
  2181. raise NoManifestException(path, str(e))
  2182. try:
  2183. line = fd.read()
  2184. finally:
  2185. fd.close()
  2186. try:
  2187. line = line.decode()
  2188. except AttributeError:
  2189. pass
  2190. if line.startswith('ref: '):
  2191. return line[5:-1]
  2192. return line[:-1]
  2193. def SetHead(self, ref, message=None):
  2194. cmdv = []
  2195. if message is not None:
  2196. cmdv.extend(['-m', message])
  2197. cmdv.append(HEAD)
  2198. cmdv.append(ref)
  2199. self.symbolic_ref(*cmdv)
  2200. def DetachHead(self, new, message=None):
  2201. cmdv = ['--no-deref']
  2202. if message is not None:
  2203. cmdv.extend(['-m', message])
  2204. cmdv.append(HEAD)
  2205. cmdv.append(new)
  2206. self.update_ref(*cmdv)
  2207. def UpdateRef(self, name, new, old=None,
  2208. message=None,
  2209. detach=False):
  2210. cmdv = []
  2211. if message is not None:
  2212. cmdv.extend(['-m', message])
  2213. if detach:
  2214. cmdv.append('--no-deref')
  2215. cmdv.append(name)
  2216. cmdv.append(new)
  2217. if old is not None:
  2218. cmdv.append(old)
  2219. self.update_ref(*cmdv)
  2220. def DeleteRef(self, name, old=None):
  2221. if not old:
  2222. old = self.rev_parse(name)
  2223. self.update_ref('-d', name, old)
  2224. self._project.bare_ref.deleted(name)
  2225. def rev_list(self, *args, **kw):
  2226. if 'format' in kw:
  2227. cmdv = ['log', '--pretty=format:%s' % kw['format']]
  2228. else:
  2229. cmdv = ['rev-list']
  2230. cmdv.extend(args)
  2231. p = GitCommand(self._project,
  2232. cmdv,
  2233. bare=self._bare,
  2234. gitdir=self._gitdir,
  2235. capture_stdout=True,
  2236. capture_stderr=True)
  2237. r = []
  2238. for line in p.process.stdout:
  2239. if line[-1] == '\n':
  2240. line = line[:-1]
  2241. r.append(line)
  2242. if p.Wait() != 0:
  2243. raise GitError('%s rev-list %s: %s' % (
  2244. self._project.name,
  2245. str(args),
  2246. p.stderr))
  2247. return r
  2248. def __getattr__(self, name):
  2249. """Allow arbitrary git commands using pythonic syntax.
  2250. This allows you to do things like:
  2251. git_obj.rev_parse('HEAD')
  2252. Since we don't have a 'rev_parse' method defined, the __getattr__ will
  2253. run. We'll replace the '_' with a '-' and try to run a git command.
  2254. Any other positional arguments will be passed to the git command, and the
  2255. following keyword arguments are supported:
  2256. config: An optional dict of git config options to be passed with '-c'.
  2257. Args:
  2258. name: The name of the git command to call. Any '_' characters will
  2259. be replaced with '-'.
  2260. Returns:
  2261. A callable object that will try to call git with the named command.
  2262. """
  2263. name = name.replace('_', '-')
  2264. def runner(*args, **kwargs):
  2265. cmdv = []
  2266. config = kwargs.pop('config', None)
  2267. for k in kwargs:
  2268. raise TypeError('%s() got an unexpected keyword argument %r'
  2269. % (name, k))
  2270. if config is not None:
  2271. if not git_require((1, 7, 2)):
  2272. raise ValueError('cannot set config on command line for %s()'
  2273. % name)
  2274. for k, v in config.items():
  2275. cmdv.append('-c')
  2276. cmdv.append('%s=%s' % (k, v))
  2277. cmdv.append(name)
  2278. cmdv.extend(args)
  2279. p = GitCommand(self._project,
  2280. cmdv,
  2281. bare=self._bare,
  2282. gitdir=self._gitdir,
  2283. capture_stdout=True,
  2284. capture_stderr=True)
  2285. if p.Wait() != 0:
  2286. raise GitError('%s %s: %s' % (
  2287. self._project.name,
  2288. name,
  2289. p.stderr))
  2290. r = p.stdout
  2291. try:
  2292. r = r.decode('utf-8')
  2293. except AttributeError:
  2294. pass
  2295. if r.endswith('\n') and r.index('\n') == len(r) - 1:
  2296. return r[:-1]
  2297. return r
  2298. return runner
  2299. class _PriorSyncFailedError(Exception):
  2300. def __str__(self):
  2301. return 'prior sync failed; rebase still in progress'
  2302. class _DirtyError(Exception):
  2303. def __str__(self):
  2304. return 'contains uncommitted changes'
  2305. class _InfoMessage(object):
  2306. def __init__(self, project, text):
  2307. self.project = project
  2308. self.text = text
  2309. def Print(self, syncbuf):
  2310. syncbuf.out.info('%s/: %s', self.project.relpath, self.text)
  2311. syncbuf.out.nl()
  2312. class _Failure(object):
  2313. def __init__(self, project, why):
  2314. self.project = project
  2315. self.why = why
  2316. def Print(self, syncbuf):
  2317. syncbuf.out.fail('error: %s/: %s',
  2318. self.project.relpath,
  2319. str(self.why))
  2320. syncbuf.out.nl()
  2321. class _Later(object):
  2322. def __init__(self, project, action):
  2323. self.project = project
  2324. self.action = action
  2325. def Run(self, syncbuf):
  2326. out = syncbuf.out
  2327. out.project('project %s/', self.project.relpath)
  2328. out.nl()
  2329. try:
  2330. self.action()
  2331. out.nl()
  2332. return True
  2333. except GitError:
  2334. out.nl()
  2335. return False
  2336. class _SyncColoring(Coloring):
  2337. def __init__(self, config):
  2338. Coloring.__init__(self, config, 'reposync')
  2339. self.project = self.printer('header', attr='bold')
  2340. self.info = self.printer('info')
  2341. self.fail = self.printer('fail', fg='red')
  2342. class SyncBuffer(object):
  2343. def __init__(self, config, detach_head=False):
  2344. self._messages = []
  2345. self._failures = []
  2346. self._later_queue1 = []
  2347. self._later_queue2 = []
  2348. self.out = _SyncColoring(config)
  2349. self.out.redirect(sys.stderr)
  2350. self.detach_head = detach_head
  2351. self.clean = True
  2352. def info(self, project, fmt, *args):
  2353. self._messages.append(_InfoMessage(project, fmt % args))
  2354. def fail(self, project, err=None):
  2355. self._failures.append(_Failure(project, err))
  2356. self.clean = False
  2357. def later1(self, project, what):
  2358. self._later_queue1.append(_Later(project, what))
  2359. def later2(self, project, what):
  2360. self._later_queue2.append(_Later(project, what))
  2361. def Finish(self):
  2362. self._PrintMessages()
  2363. self._RunLater()
  2364. self._PrintMessages()
  2365. return self.clean
  2366. def _RunLater(self):
  2367. for q in ['_later_queue1', '_later_queue2']:
  2368. if not self._RunQueue(q):
  2369. return
  2370. def _RunQueue(self, queue):
  2371. for m in getattr(self, queue):
  2372. if not m.Run(self):
  2373. self.clean = False
  2374. return False
  2375. setattr(self, queue, [])
  2376. return True
  2377. def _PrintMessages(self):
  2378. for m in self._messages:
  2379. m.Print(self)
  2380. for m in self._failures:
  2381. m.Print(self)
  2382. self._messages = []
  2383. self._failures = []
  2384. class MetaProject(Project):
  2385. """A special project housed under .repo.
  2386. """
  2387. def __init__(self, manifest, name, gitdir, worktree):
  2388. Project.__init__(self,
  2389. manifest=manifest,
  2390. name=name,
  2391. gitdir=gitdir,
  2392. objdir=gitdir,
  2393. worktree=worktree,
  2394. remote=RemoteSpec('origin'),
  2395. relpath='.repo/%s' % name,
  2396. revisionExpr='refs/heads/master',
  2397. revisionId=None,
  2398. groups=None)
  2399. def PreSync(self):
  2400. if self.Exists:
  2401. cb = self.CurrentBranch
  2402. if cb:
  2403. base = self.GetBranch(cb).merge
  2404. if base:
  2405. self.revisionExpr = base
  2406. self.revisionId = None
  2407. def MetaBranchSwitch(self):
  2408. """ Prepare MetaProject for manifest branch switch
  2409. """
  2410. # detach and delete manifest branch, allowing a new
  2411. # branch to take over
  2412. syncbuf = SyncBuffer(self.config, detach_head=True)
  2413. self.Sync_LocalHalf(syncbuf)
  2414. syncbuf.Finish()
  2415. return GitCommand(self,
  2416. ['update-ref', '-d', 'refs/heads/default'],
  2417. capture_stdout=True,
  2418. capture_stderr=True).Wait() == 0
  2419. @property
  2420. def LastFetch(self):
  2421. try:
  2422. fh = os.path.join(self.gitdir, 'FETCH_HEAD')
  2423. return os.path.getmtime(fh)
  2424. except OSError:
  2425. return 0
  2426. @property
  2427. def HasChanges(self):
  2428. """Has the remote received new commits not yet checked out?
  2429. """
  2430. if not self.remote or not self.revisionExpr:
  2431. return False
  2432. all_refs = self.bare_ref.all
  2433. revid = self.GetRevisionId(all_refs)
  2434. head = self.work_git.GetHead()
  2435. if head.startswith(R_HEADS):
  2436. try:
  2437. head = all_refs[head]
  2438. except KeyError:
  2439. head = None
  2440. if revid == head:
  2441. return False
  2442. elif self._revlist(not_rev(HEAD), revid):
  2443. return True
  2444. return False