project.py 100 KB

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