project.py 101 KB

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