project.py 101 KB

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