project.py 81 KB

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