project.py 79 KB

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