project.py 107 KB

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