project.py 100 KB

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