project.py 77 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571
  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 GetRevisionId(self, all_refs=None):
  937. if self.revisionId:
  938. return self.revisionId
  939. rem = self.GetRemote(self.remote.name)
  940. rev = rem.ToLocal(self.revisionExpr)
  941. if all_refs is not None and rev in all_refs:
  942. return all_refs[rev]
  943. try:
  944. return self.bare_git.rev_parse('--verify', '%s^0' % rev)
  945. except GitError:
  946. raise ManifestInvalidRevisionError(
  947. 'revision %s in %s not found' % (self.revisionExpr,
  948. self.name))
  949. def Sync_LocalHalf(self, syncbuf):
  950. """Perform only the local IO portion of the sync process.
  951. Network access is not required.
  952. """
  953. self._InitWorkTree()
  954. all_refs = self.bare_ref.all
  955. self.CleanPublishedCache(all_refs)
  956. revid = self.GetRevisionId(all_refs)
  957. def _doff():
  958. self._FastForward(revid)
  959. self._CopyFiles()
  960. head = self.work_git.GetHead()
  961. if head.startswith(R_HEADS):
  962. branch = head[len(R_HEADS):]
  963. try:
  964. head = all_refs[head]
  965. except KeyError:
  966. head = None
  967. else:
  968. branch = None
  969. if branch is None or syncbuf.detach_head:
  970. # Currently on a detached HEAD. The user is assumed to
  971. # not have any local modifications worth worrying about.
  972. #
  973. if self.IsRebaseInProgress():
  974. syncbuf.fail(self, _PriorSyncFailedError())
  975. return
  976. if head == revid:
  977. # No changes; don't do anything further.
  978. # Except if the head needs to be detached
  979. #
  980. if not syncbuf.detach_head:
  981. return
  982. else:
  983. lost = self._revlist(not_rev(revid), HEAD)
  984. if lost:
  985. syncbuf.info(self, "discarding %d commits", len(lost))
  986. try:
  987. self._Checkout(revid, quiet=True)
  988. except GitError as e:
  989. syncbuf.fail(self, e)
  990. return
  991. self._CopyFiles()
  992. return
  993. if head == revid:
  994. # No changes; don't do anything further.
  995. #
  996. return
  997. branch = self.GetBranch(branch)
  998. if not branch.LocalMerge:
  999. # The current branch has no tracking configuration.
  1000. # Jump off it to a detached HEAD.
  1001. #
  1002. syncbuf.info(self,
  1003. "leaving %s; does not track upstream",
  1004. branch.name)
  1005. try:
  1006. self._Checkout(revid, quiet=True)
  1007. except GitError as e:
  1008. syncbuf.fail(self, e)
  1009. return
  1010. self._CopyFiles()
  1011. return
  1012. upstream_gain = self._revlist(not_rev(HEAD), revid)
  1013. pub = self.WasPublished(branch.name, all_refs)
  1014. if pub:
  1015. not_merged = self._revlist(not_rev(revid), pub)
  1016. if not_merged:
  1017. if upstream_gain:
  1018. # The user has published this branch and some of those
  1019. # commits are not yet merged upstream. We do not want
  1020. # to rewrite the published commits so we punt.
  1021. #
  1022. syncbuf.fail(self,
  1023. "branch %s is published (but not merged) and is now %d commits behind"
  1024. % (branch.name, len(upstream_gain)))
  1025. return
  1026. elif pub == head:
  1027. # All published commits are merged, and thus we are a
  1028. # strict subset. We can fast-forward safely.
  1029. #
  1030. syncbuf.later1(self, _doff)
  1031. return
  1032. # Examine the local commits not in the remote. Find the
  1033. # last one attributed to this user, if any.
  1034. #
  1035. local_changes = self._revlist(not_rev(revid), HEAD, format='%H %ce')
  1036. last_mine = None
  1037. cnt_mine = 0
  1038. for commit in local_changes:
  1039. commit_id, committer_email = commit.decode('utf-8').split(' ', 1)
  1040. if committer_email == self.UserEmail:
  1041. last_mine = commit_id
  1042. cnt_mine += 1
  1043. if not upstream_gain and cnt_mine == len(local_changes):
  1044. return
  1045. if self.IsDirty(consider_untracked=False):
  1046. syncbuf.fail(self, _DirtyError())
  1047. return
  1048. # If the upstream switched on us, warn the user.
  1049. #
  1050. if branch.merge != self.revisionExpr:
  1051. if branch.merge and self.revisionExpr:
  1052. syncbuf.info(self,
  1053. 'manifest switched %s...%s',
  1054. branch.merge,
  1055. self.revisionExpr)
  1056. elif branch.merge:
  1057. syncbuf.info(self,
  1058. 'manifest no longer tracks %s',
  1059. branch.merge)
  1060. if cnt_mine < len(local_changes):
  1061. # Upstream rebased. Not everything in HEAD
  1062. # was created by this user.
  1063. #
  1064. syncbuf.info(self,
  1065. "discarding %d commits removed from upstream",
  1066. len(local_changes) - cnt_mine)
  1067. branch.remote = self.GetRemote(self.remote.name)
  1068. if not ID_RE.match(self.revisionExpr):
  1069. # in case of manifest sync the revisionExpr might be a SHA1
  1070. branch.merge = self.revisionExpr
  1071. branch.Save()
  1072. if cnt_mine > 0 and self.rebase:
  1073. def _dorebase():
  1074. self._Rebase(upstream = '%s^1' % last_mine, onto = revid)
  1075. self._CopyFiles()
  1076. syncbuf.later2(self, _dorebase)
  1077. elif local_changes:
  1078. try:
  1079. self._ResetHard(revid)
  1080. self._CopyFiles()
  1081. except GitError as e:
  1082. syncbuf.fail(self, e)
  1083. return
  1084. else:
  1085. syncbuf.later1(self, _doff)
  1086. def AddCopyFile(self, src, dest, absdest):
  1087. # dest should already be an absolute path, but src is project relative
  1088. # make src an absolute path
  1089. abssrc = os.path.join(self.worktree, src)
  1090. self.copyfiles.append(_CopyFile(src, dest, abssrc, absdest))
  1091. def AddAnnotation(self, name, value, keep):
  1092. self.annotations.append(_Annotation(name, value, keep))
  1093. def DownloadPatchSet(self, change_id, patch_id):
  1094. """Download a single patch set of a single change to FETCH_HEAD.
  1095. """
  1096. remote = self.GetRemote(self.remote.name)
  1097. cmd = ['fetch', remote.name]
  1098. cmd.append('refs/changes/%2.2d/%d/%d' \
  1099. % (change_id % 100, change_id, patch_id))
  1100. if GitCommand(self, cmd, bare=True).Wait() != 0:
  1101. return None
  1102. return DownloadedChange(self,
  1103. self.GetRevisionId(),
  1104. change_id,
  1105. patch_id,
  1106. self.bare_git.rev_parse('FETCH_HEAD'))
  1107. ## Branch Management ##
  1108. def StartBranch(self, name):
  1109. """Create a new branch off the manifest's revision.
  1110. """
  1111. head = self.work_git.GetHead()
  1112. if head == (R_HEADS + name):
  1113. return True
  1114. all_refs = self.bare_ref.all
  1115. if (R_HEADS + name) in all_refs:
  1116. return GitCommand(self,
  1117. ['checkout', name, '--'],
  1118. capture_stdout = True,
  1119. capture_stderr = True).Wait() == 0
  1120. branch = self.GetBranch(name)
  1121. branch.remote = self.GetRemote(self.remote.name)
  1122. branch.merge = self.revisionExpr
  1123. revid = self.GetRevisionId(all_refs)
  1124. if head.startswith(R_HEADS):
  1125. try:
  1126. head = all_refs[head]
  1127. except KeyError:
  1128. head = None
  1129. if revid and head and revid == head:
  1130. ref = os.path.join(self.gitdir, R_HEADS + name)
  1131. try:
  1132. os.makedirs(os.path.dirname(ref))
  1133. except OSError:
  1134. pass
  1135. _lwrite(ref, '%s\n' % revid)
  1136. _lwrite(os.path.join(self.worktree, '.git', HEAD),
  1137. 'ref: %s%s\n' % (R_HEADS, name))
  1138. branch.Save()
  1139. return True
  1140. if GitCommand(self,
  1141. ['checkout', '-b', branch.name, revid],
  1142. capture_stdout = True,
  1143. capture_stderr = True).Wait() == 0:
  1144. branch.Save()
  1145. return True
  1146. return False
  1147. def CheckoutBranch(self, name):
  1148. """Checkout a local topic branch.
  1149. Args:
  1150. name: The name of the branch to checkout.
  1151. Returns:
  1152. True if the checkout succeeded; False if it didn't; None if the branch
  1153. didn't exist.
  1154. """
  1155. rev = R_HEADS + name
  1156. head = self.work_git.GetHead()
  1157. if head == rev:
  1158. # Already on the branch
  1159. #
  1160. return True
  1161. all_refs = self.bare_ref.all
  1162. try:
  1163. revid = all_refs[rev]
  1164. except KeyError:
  1165. # Branch does not exist in this project
  1166. #
  1167. return None
  1168. if head.startswith(R_HEADS):
  1169. try:
  1170. head = all_refs[head]
  1171. except KeyError:
  1172. head = None
  1173. if head == revid:
  1174. # Same revision; just update HEAD to point to the new
  1175. # target branch, but otherwise take no other action.
  1176. #
  1177. _lwrite(os.path.join(self.worktree, '.git', HEAD),
  1178. 'ref: %s%s\n' % (R_HEADS, name))
  1179. return True
  1180. return GitCommand(self,
  1181. ['checkout', name, '--'],
  1182. capture_stdout = True,
  1183. capture_stderr = True).Wait() == 0
  1184. def AbandonBranch(self, name):
  1185. """Destroy a local topic branch.
  1186. Args:
  1187. name: The name of the branch to abandon.
  1188. Returns:
  1189. True if the abandon succeeded; False if it didn't; None if the branch
  1190. didn't exist.
  1191. """
  1192. rev = R_HEADS + name
  1193. all_refs = self.bare_ref.all
  1194. if rev not in all_refs:
  1195. # Doesn't exist
  1196. return None
  1197. head = self.work_git.GetHead()
  1198. if head == rev:
  1199. # We can't destroy the branch while we are sitting
  1200. # on it. Switch to a detached HEAD.
  1201. #
  1202. head = all_refs[head]
  1203. revid = self.GetRevisionId(all_refs)
  1204. if head == revid:
  1205. _lwrite(os.path.join(self.worktree, '.git', HEAD),
  1206. '%s\n' % revid)
  1207. else:
  1208. self._Checkout(revid, quiet=True)
  1209. return GitCommand(self,
  1210. ['branch', '-D', name],
  1211. capture_stdout = True,
  1212. capture_stderr = True).Wait() == 0
  1213. def PruneHeads(self):
  1214. """Prune any topic branches already merged into upstream.
  1215. """
  1216. cb = self.CurrentBranch
  1217. kill = []
  1218. left = self._allrefs
  1219. for name in left.keys():
  1220. if name.startswith(R_HEADS):
  1221. name = name[len(R_HEADS):]
  1222. if cb is None or name != cb:
  1223. kill.append(name)
  1224. rev = self.GetRevisionId(left)
  1225. if cb is not None \
  1226. and not self._revlist(HEAD + '...' + rev) \
  1227. and not self.IsDirty(consider_untracked = False):
  1228. self.work_git.DetachHead(HEAD)
  1229. kill.append(cb)
  1230. if kill:
  1231. old = self.bare_git.GetHead()
  1232. if old is None:
  1233. old = 'refs/heads/please_never_use_this_as_a_branch_name'
  1234. try:
  1235. self.bare_git.DetachHead(rev)
  1236. b = ['branch', '-d']
  1237. b.extend(kill)
  1238. b = GitCommand(self, b, bare=True,
  1239. capture_stdout=True,
  1240. capture_stderr=True)
  1241. b.Wait()
  1242. finally:
  1243. self.bare_git.SetHead(old)
  1244. left = self._allrefs
  1245. for branch in kill:
  1246. if (R_HEADS + branch) not in left:
  1247. self.CleanPublishedCache()
  1248. break
  1249. if cb and cb not in kill:
  1250. kill.append(cb)
  1251. kill.sort()
  1252. kept = []
  1253. for branch in kill:
  1254. if (R_HEADS + branch) in left:
  1255. branch = self.GetBranch(branch)
  1256. base = branch.LocalMerge
  1257. if not base:
  1258. base = rev
  1259. kept.append(ReviewableBranch(self, branch, base))
  1260. return kept
  1261. ## Submodule Management ##
  1262. def GetRegisteredSubprojects(self):
  1263. result = []
  1264. def rec(subprojects):
  1265. if not subprojects:
  1266. return
  1267. result.extend(subprojects)
  1268. for p in subprojects:
  1269. rec(p.subprojects)
  1270. rec(self.subprojects)
  1271. return result
  1272. def _GetSubmodules(self):
  1273. # Unfortunately we cannot call `git submodule status --recursive` here
  1274. # because the working tree might not exist yet, and it cannot be used
  1275. # without a working tree in its current implementation.
  1276. def get_submodules(gitdir, rev):
  1277. # Parse .gitmodules for submodule sub_paths and sub_urls
  1278. sub_paths, sub_urls = parse_gitmodules(gitdir, rev)
  1279. if not sub_paths:
  1280. return []
  1281. # Run `git ls-tree` to read SHAs of submodule object, which happen to be
  1282. # revision of submodule repository
  1283. sub_revs = git_ls_tree(gitdir, rev, sub_paths)
  1284. submodules = []
  1285. for sub_path, sub_url in zip(sub_paths, sub_urls):
  1286. try:
  1287. sub_rev = sub_revs[sub_path]
  1288. except KeyError:
  1289. # Ignore non-exist submodules
  1290. continue
  1291. submodules.append((sub_rev, sub_path, sub_url))
  1292. return submodules
  1293. re_path = re.compile(r'^submodule\.([^.]+)\.path=(.*)$')
  1294. re_url = re.compile(r'^submodule\.([^.]+)\.url=(.*)$')
  1295. def parse_gitmodules(gitdir, rev):
  1296. cmd = ['cat-file', 'blob', '%s:.gitmodules' % rev]
  1297. try:
  1298. p = GitCommand(None, cmd, capture_stdout = True, capture_stderr = True,
  1299. bare = True, gitdir = gitdir)
  1300. except GitError:
  1301. return [], []
  1302. if p.Wait() != 0:
  1303. return [], []
  1304. gitmodules_lines = []
  1305. fd, temp_gitmodules_path = tempfile.mkstemp()
  1306. try:
  1307. os.write(fd, p.stdout)
  1308. os.close(fd)
  1309. cmd = ['config', '--file', temp_gitmodules_path, '--list']
  1310. p = GitCommand(None, cmd, capture_stdout = True, capture_stderr = True,
  1311. bare = True, gitdir = gitdir)
  1312. if p.Wait() != 0:
  1313. return [], []
  1314. gitmodules_lines = p.stdout.split('\n')
  1315. except GitError:
  1316. return [], []
  1317. finally:
  1318. os.remove(temp_gitmodules_path)
  1319. names = set()
  1320. paths = {}
  1321. urls = {}
  1322. for line in gitmodules_lines:
  1323. if not line:
  1324. continue
  1325. m = re_path.match(line)
  1326. if m:
  1327. names.add(m.group(1))
  1328. paths[m.group(1)] = m.group(2)
  1329. continue
  1330. m = re_url.match(line)
  1331. if m:
  1332. names.add(m.group(1))
  1333. urls[m.group(1)] = m.group(2)
  1334. continue
  1335. names = sorted(names)
  1336. return ([paths.get(name, '') for name in names],
  1337. [urls.get(name, '') for name in names])
  1338. def git_ls_tree(gitdir, rev, paths):
  1339. cmd = ['ls-tree', rev, '--']
  1340. cmd.extend(paths)
  1341. try:
  1342. p = GitCommand(None, cmd, capture_stdout = True, capture_stderr = True,
  1343. bare = True, gitdir = gitdir)
  1344. except GitError:
  1345. return []
  1346. if p.Wait() != 0:
  1347. return []
  1348. objects = {}
  1349. for line in p.stdout.split('\n'):
  1350. if not line.strip():
  1351. continue
  1352. object_rev, object_path = line.split()[2:4]
  1353. objects[object_path] = object_rev
  1354. return objects
  1355. try:
  1356. rev = self.GetRevisionId()
  1357. except GitError:
  1358. return []
  1359. return get_submodules(self.gitdir, rev)
  1360. def GetDerivedSubprojects(self):
  1361. result = []
  1362. if not self.Exists:
  1363. # If git repo does not exist yet, querying its submodules will
  1364. # mess up its states; so return here.
  1365. return result
  1366. for rev, path, url in self._GetSubmodules():
  1367. name = self.manifest.GetSubprojectName(self, path)
  1368. relpath, worktree, gitdir, objdir = \
  1369. self.manifest.GetSubprojectPaths(self, name, path)
  1370. project = self.manifest.paths.get(relpath)
  1371. if project:
  1372. result.extend(project.GetDerivedSubprojects())
  1373. continue
  1374. remote = RemoteSpec(self.remote.name,
  1375. url = url,
  1376. review = self.remote.review)
  1377. subproject = Project(manifest = self.manifest,
  1378. name = name,
  1379. remote = remote,
  1380. gitdir = gitdir,
  1381. objdir = objdir,
  1382. worktree = worktree,
  1383. relpath = relpath,
  1384. revisionExpr = self.revisionExpr,
  1385. revisionId = rev,
  1386. rebase = self.rebase,
  1387. groups = self.groups,
  1388. sync_c = self.sync_c,
  1389. sync_s = self.sync_s,
  1390. parent = self,
  1391. is_derived = True)
  1392. result.append(subproject)
  1393. result.extend(subproject.GetDerivedSubprojects())
  1394. return result
  1395. ## Direct Git Commands ##
  1396. def _FetchArchive(self, tarpath, cwd=None):
  1397. cmd = ['archive', '-v', '-o', tarpath]
  1398. cmd.append('--remote=%s' % self.remote.url)
  1399. cmd.append('--prefix=%s/' % self.relpath)
  1400. cmd.append(self.revisionExpr)
  1401. command = GitCommand(self, cmd, cwd=cwd,
  1402. capture_stdout=True,
  1403. capture_stderr=True)
  1404. if command.Wait() != 0:
  1405. raise GitError('git archive %s: %s' % (self.name, command.stderr))
  1406. def _RemoteFetch(self, name=None,
  1407. current_branch_only=False,
  1408. initial=False,
  1409. quiet=False,
  1410. alt_dir=None,
  1411. no_tags=False):
  1412. is_sha1 = False
  1413. tag_name = None
  1414. def CheckForSha1():
  1415. try:
  1416. # if revision (sha or tag) is not present then following function
  1417. # throws an error.
  1418. self.bare_git.rev_parse('--verify', '%s^0' % self.revisionExpr)
  1419. return True
  1420. except GitError:
  1421. # There is no such persistent revision. We have to fetch it.
  1422. return False
  1423. if self.clone_depth:
  1424. depth = self.clone_depth
  1425. else:
  1426. depth = self.manifest.manifestProject.config.GetString('repo.depth')
  1427. if depth:
  1428. current_branch_only = True
  1429. if current_branch_only:
  1430. if ID_RE.match(self.revisionExpr) is not None:
  1431. is_sha1 = True
  1432. elif self.revisionExpr.startswith(R_TAGS):
  1433. # this is a tag and its sha1 value should never change
  1434. tag_name = self.revisionExpr[len(R_TAGS):]
  1435. if is_sha1 or tag_name is not None:
  1436. if CheckForSha1():
  1437. return True
  1438. if is_sha1 and (not self.upstream or ID_RE.match(self.upstream)):
  1439. current_branch_only = False
  1440. if not name:
  1441. name = self.remote.name
  1442. ssh_proxy = False
  1443. remote = self.GetRemote(name)
  1444. if remote.PreConnectFetch():
  1445. ssh_proxy = True
  1446. if initial:
  1447. if alt_dir and 'objects' == os.path.basename(alt_dir):
  1448. ref_dir = os.path.dirname(alt_dir)
  1449. packed_refs = os.path.join(self.gitdir, 'packed-refs')
  1450. remote = self.GetRemote(name)
  1451. all_refs = self.bare_ref.all
  1452. ids = set(all_refs.values())
  1453. tmp = set()
  1454. for r, ref_id in GitRefs(ref_dir).all.items():
  1455. if r not in all_refs:
  1456. if r.startswith(R_TAGS) or remote.WritesTo(r):
  1457. all_refs[r] = ref_id
  1458. ids.add(ref_id)
  1459. continue
  1460. if ref_id in ids:
  1461. continue
  1462. r = 'refs/_alt/%s' % ref_id
  1463. all_refs[r] = ref_id
  1464. ids.add(ref_id)
  1465. tmp.add(r)
  1466. tmp_packed = ''
  1467. old_packed = ''
  1468. for r in sorted(all_refs):
  1469. line = '%s %s\n' % (all_refs[r], r)
  1470. tmp_packed += line
  1471. if r not in tmp:
  1472. old_packed += line
  1473. _lwrite(packed_refs, tmp_packed)
  1474. else:
  1475. alt_dir = None
  1476. cmd = ['fetch']
  1477. # The --depth option only affects the initial fetch; after that we'll do
  1478. # full fetches of changes.
  1479. if depth and initial:
  1480. cmd.append('--depth=%s' % depth)
  1481. if quiet:
  1482. cmd.append('--quiet')
  1483. if not self.worktree:
  1484. cmd.append('--update-head-ok')
  1485. cmd.append(name)
  1486. if not current_branch_only:
  1487. # Fetch whole repo
  1488. # If using depth then we should not get all the tags since they may
  1489. # be outside of the depth.
  1490. if no_tags or depth:
  1491. cmd.append('--no-tags')
  1492. else:
  1493. cmd.append('--tags')
  1494. cmd.append(str((u'+refs/heads/*:') + remote.ToLocal('refs/heads/*')))
  1495. elif tag_name is not None:
  1496. cmd.append('tag')
  1497. cmd.append(tag_name)
  1498. else:
  1499. branch = self.revisionExpr
  1500. if is_sha1:
  1501. branch = self.upstream
  1502. if branch.startswith(R_HEADS):
  1503. branch = branch[len(R_HEADS):]
  1504. cmd.append(str((u'+refs/heads/%s:' % branch) + remote.ToLocal('refs/heads/%s' % branch)))
  1505. ok = False
  1506. for _i in range(2):
  1507. ret = GitCommand(self, cmd, bare=True, ssh_proxy=ssh_proxy).Wait()
  1508. if ret == 0:
  1509. ok = True
  1510. break
  1511. elif current_branch_only and is_sha1 and ret == 128:
  1512. # Exit code 128 means "couldn't find the ref you asked for"; if we're in sha1
  1513. # mode, we just tried sync'ing from the upstream field; it doesn't exist, thus
  1514. # abort the optimization attempt and do a full sync.
  1515. break
  1516. time.sleep(random.randint(30, 45))
  1517. if initial:
  1518. if alt_dir:
  1519. if old_packed != '':
  1520. _lwrite(packed_refs, old_packed)
  1521. else:
  1522. os.remove(packed_refs)
  1523. self.bare_git.pack_refs('--all', '--prune')
  1524. if is_sha1 and current_branch_only and self.upstream:
  1525. # We just synced the upstream given branch; verify we
  1526. # got what we wanted, else trigger a second run of all
  1527. # refs.
  1528. if not CheckForSha1():
  1529. return self._RemoteFetch(name=name, current_branch_only=False,
  1530. initial=False, quiet=quiet, alt_dir=alt_dir)
  1531. return ok
  1532. def _ApplyCloneBundle(self, initial=False, quiet=False):
  1533. if initial and (self.manifest.manifestProject.config.GetString('repo.depth') or self.clone_depth):
  1534. return False
  1535. remote = self.GetRemote(self.remote.name)
  1536. bundle_url = remote.url + '/clone.bundle'
  1537. bundle_url = GitConfig.ForUser().UrlInsteadOf(bundle_url)
  1538. if GetSchemeFromUrl(bundle_url) not in (
  1539. 'http', 'https', 'persistent-http', 'persistent-https'):
  1540. return False
  1541. bundle_dst = os.path.join(self.gitdir, 'clone.bundle')
  1542. bundle_tmp = os.path.join(self.gitdir, 'clone.bundle.tmp')
  1543. exist_dst = os.path.exists(bundle_dst)
  1544. exist_tmp = os.path.exists(bundle_tmp)
  1545. if not initial and not exist_dst and not exist_tmp:
  1546. return False
  1547. if not exist_dst:
  1548. exist_dst = self._FetchBundle(bundle_url, bundle_tmp, bundle_dst, quiet)
  1549. if not exist_dst:
  1550. return False
  1551. cmd = ['fetch']
  1552. if quiet:
  1553. cmd.append('--quiet')
  1554. if not self.worktree:
  1555. cmd.append('--update-head-ok')
  1556. cmd.append(bundle_dst)
  1557. for f in remote.fetch:
  1558. cmd.append(str(f))
  1559. cmd.append('refs/tags/*:refs/tags/*')
  1560. ok = GitCommand(self, cmd, bare=True).Wait() == 0
  1561. if os.path.exists(bundle_dst):
  1562. os.remove(bundle_dst)
  1563. if os.path.exists(bundle_tmp):
  1564. os.remove(bundle_tmp)
  1565. return ok
  1566. def _FetchBundle(self, srcUrl, tmpPath, dstPath, quiet):
  1567. if os.path.exists(dstPath):
  1568. os.remove(dstPath)
  1569. cmd = ['curl', '--fail', '--output', tmpPath, '--netrc', '--location']
  1570. if quiet:
  1571. cmd += ['--silent']
  1572. if os.path.exists(tmpPath):
  1573. size = os.stat(tmpPath).st_size
  1574. if size >= 1024:
  1575. cmd += ['--continue-at', '%d' % (size,)]
  1576. else:
  1577. os.remove(tmpPath)
  1578. if 'http_proxy' in os.environ and 'darwin' == sys.platform:
  1579. cmd += ['--proxy', os.environ['http_proxy']]
  1580. cookiefile = self._GetBundleCookieFile(srcUrl)
  1581. if cookiefile:
  1582. cmd += ['--cookie', cookiefile]
  1583. if srcUrl.startswith('persistent-'):
  1584. srcUrl = srcUrl[len('persistent-'):]
  1585. cmd += [srcUrl]
  1586. if IsTrace():
  1587. Trace('%s', ' '.join(cmd))
  1588. try:
  1589. proc = subprocess.Popen(cmd)
  1590. except OSError:
  1591. return False
  1592. curlret = proc.wait()
  1593. if curlret == 22:
  1594. # From curl man page:
  1595. # 22: HTTP page not retrieved. The requested url was not found or
  1596. # returned another error with the HTTP error code being 400 or above.
  1597. # This return code only appears if -f, --fail is used.
  1598. if not quiet:
  1599. print("Server does not provide clone.bundle; ignoring.",
  1600. file=sys.stderr)
  1601. return False
  1602. if os.path.exists(tmpPath):
  1603. if curlret == 0 and self._IsValidBundle(tmpPath):
  1604. os.rename(tmpPath, dstPath)
  1605. return True
  1606. else:
  1607. os.remove(tmpPath)
  1608. return False
  1609. else:
  1610. return False
  1611. def _IsValidBundle(self, path):
  1612. try:
  1613. with open(path) as f:
  1614. if f.read(16) == '# v2 git bundle\n':
  1615. return True
  1616. else:
  1617. print("Invalid clone.bundle file; ignoring.", file=sys.stderr)
  1618. return False
  1619. except OSError:
  1620. return False
  1621. def _GetBundleCookieFile(self, url):
  1622. if url.startswith('persistent-'):
  1623. try:
  1624. p = subprocess.Popen(
  1625. ['git-remote-persistent-https', '-print_config', url],
  1626. stdin=subprocess.PIPE, stdout=subprocess.PIPE,
  1627. stderr=subprocess.PIPE)
  1628. p.stdin.close() # Tell subprocess it's ok to close.
  1629. prefix = 'http.cookiefile='
  1630. cookiefile = None
  1631. for line in p.stdout:
  1632. line = line.strip()
  1633. if line.startswith(prefix):
  1634. cookiefile = line[len(prefix):]
  1635. break
  1636. if p.wait():
  1637. err_msg = p.stderr.read()
  1638. if ' -print_config' in err_msg:
  1639. pass # Persistent proxy doesn't support -print_config.
  1640. else:
  1641. print(err_msg, file=sys.stderr)
  1642. if cookiefile:
  1643. return cookiefile
  1644. except OSError as e:
  1645. if e.errno == errno.ENOENT:
  1646. pass # No persistent proxy.
  1647. raise
  1648. return GitConfig.ForUser().GetString('http.cookiefile')
  1649. def _Checkout(self, rev, quiet=False):
  1650. cmd = ['checkout']
  1651. if quiet:
  1652. cmd.append('-q')
  1653. cmd.append(rev)
  1654. cmd.append('--')
  1655. if GitCommand(self, cmd).Wait() != 0:
  1656. if self._allrefs:
  1657. raise GitError('%s checkout %s ' % (self.name, rev))
  1658. def _CherryPick(self, rev, quiet=False):
  1659. cmd = ['cherry-pick']
  1660. cmd.append(rev)
  1661. cmd.append('--')
  1662. if GitCommand(self, cmd).Wait() != 0:
  1663. if self._allrefs:
  1664. raise GitError('%s cherry-pick %s ' % (self.name, rev))
  1665. def _Revert(self, rev, quiet=False):
  1666. cmd = ['revert']
  1667. cmd.append('--no-edit')
  1668. cmd.append(rev)
  1669. cmd.append('--')
  1670. if GitCommand(self, cmd).Wait() != 0:
  1671. if self._allrefs:
  1672. raise GitError('%s revert %s ' % (self.name, rev))
  1673. def _ResetHard(self, rev, quiet=True):
  1674. cmd = ['reset', '--hard']
  1675. if quiet:
  1676. cmd.append('-q')
  1677. cmd.append(rev)
  1678. if GitCommand(self, cmd).Wait() != 0:
  1679. raise GitError('%s reset --hard %s ' % (self.name, rev))
  1680. def _Rebase(self, upstream, onto = None):
  1681. cmd = ['rebase']
  1682. if onto is not None:
  1683. cmd.extend(['--onto', onto])
  1684. cmd.append(upstream)
  1685. if GitCommand(self, cmd).Wait() != 0:
  1686. raise GitError('%s rebase %s ' % (self.name, upstream))
  1687. def _FastForward(self, head, ffonly=False):
  1688. cmd = ['merge', head]
  1689. if ffonly:
  1690. cmd.append("--ff-only")
  1691. if GitCommand(self, cmd).Wait() != 0:
  1692. raise GitError('%s merge %s ' % (self.name, head))
  1693. def _InitGitDir(self, mirror_git=None):
  1694. if not os.path.exists(self.gitdir):
  1695. # Initialize the bare repository, which contains all of the objects.
  1696. if not os.path.exists(self.objdir):
  1697. os.makedirs(self.objdir)
  1698. self.bare_objdir.init()
  1699. # If we have a separate directory to hold refs, initialize it as well.
  1700. if self.objdir != self.gitdir:
  1701. os.makedirs(self.gitdir)
  1702. self._ReferenceGitDir(self.objdir, self.gitdir, share_refs=False,
  1703. copy_all=True)
  1704. mp = self.manifest.manifestProject
  1705. ref_dir = mp.config.GetString('repo.reference') or ''
  1706. if ref_dir or mirror_git:
  1707. if not mirror_git:
  1708. mirror_git = os.path.join(ref_dir, self.name + '.git')
  1709. repo_git = os.path.join(ref_dir, '.repo', 'projects',
  1710. self.relpath + '.git')
  1711. if os.path.exists(mirror_git):
  1712. ref_dir = mirror_git
  1713. elif os.path.exists(repo_git):
  1714. ref_dir = repo_git
  1715. else:
  1716. ref_dir = None
  1717. if ref_dir:
  1718. _lwrite(os.path.join(self.gitdir, 'objects/info/alternates'),
  1719. os.path.join(ref_dir, 'objects') + '\n')
  1720. self._UpdateHooks()
  1721. m = self.manifest.manifestProject.config
  1722. for key in ['user.name', 'user.email']:
  1723. if m.Has(key, include_defaults = False):
  1724. self.config.SetString(key, m.GetString(key))
  1725. if self.manifest.IsMirror:
  1726. self.config.SetString('core.bare', 'true')
  1727. else:
  1728. self.config.SetString('core.bare', None)
  1729. def _UpdateHooks(self):
  1730. if os.path.exists(self.gitdir):
  1731. # Always recreate hooks since they can have been changed
  1732. # since the latest update.
  1733. hooks = self._gitdir_path('hooks')
  1734. try:
  1735. to_rm = os.listdir(hooks)
  1736. except OSError:
  1737. to_rm = []
  1738. for old_hook in to_rm:
  1739. os.remove(os.path.join(hooks, old_hook))
  1740. self._InitHooks()
  1741. def _InitHooks(self):
  1742. hooks = os.path.realpath(self._gitdir_path('hooks'))
  1743. if not os.path.exists(hooks):
  1744. os.makedirs(hooks)
  1745. for stock_hook in _ProjectHooks():
  1746. name = os.path.basename(stock_hook)
  1747. if name in ('commit-msg',) and not self.remote.review \
  1748. and not self is self.manifest.manifestProject:
  1749. # Don't install a Gerrit Code Review hook if this
  1750. # project does not appear to use it for reviews.
  1751. #
  1752. # Since the manifest project is one of those, but also
  1753. # managed through gerrit, it's excluded
  1754. continue
  1755. dst = os.path.join(hooks, name)
  1756. if os.path.islink(dst):
  1757. continue
  1758. if os.path.exists(dst):
  1759. if filecmp.cmp(stock_hook, dst, shallow=False):
  1760. os.remove(dst)
  1761. else:
  1762. _error("%s: Not replacing %s hook", self.relpath, name)
  1763. continue
  1764. try:
  1765. os.symlink(os.path.relpath(stock_hook, os.path.dirname(dst)), dst)
  1766. except OSError as e:
  1767. if e.errno == errno.EPERM:
  1768. raise GitError('filesystem must support symlinks')
  1769. else:
  1770. raise
  1771. def _InitRemote(self):
  1772. if self.remote.url:
  1773. remote = self.GetRemote(self.remote.name)
  1774. remote.url = self.remote.url
  1775. remote.review = self.remote.review
  1776. remote.projectname = self.name
  1777. if self.worktree:
  1778. remote.ResetFetch(mirror=False)
  1779. else:
  1780. remote.ResetFetch(mirror=True)
  1781. remote.Save()
  1782. def _InitMRef(self):
  1783. if self.manifest.branch:
  1784. self._InitAnyMRef(R_M + self.manifest.branch)
  1785. def _InitMirrorHead(self):
  1786. self._InitAnyMRef(HEAD)
  1787. def _InitAnyMRef(self, ref):
  1788. cur = self.bare_ref.symref(ref)
  1789. if self.revisionId:
  1790. if cur != '' or self.bare_ref.get(ref) != self.revisionId:
  1791. msg = 'manifest set to %s' % self.revisionId
  1792. dst = self.revisionId + '^0'
  1793. self.bare_git.UpdateRef(ref, dst, message = msg, detach = True)
  1794. else:
  1795. remote = self.GetRemote(self.remote.name)
  1796. dst = remote.ToLocal(self.revisionExpr)
  1797. if cur != dst:
  1798. msg = 'manifest set to %s' % self.revisionExpr
  1799. self.bare_git.symbolic_ref('-m', msg, ref, dst)
  1800. def _ReferenceGitDir(self, gitdir, dotgit, share_refs, copy_all):
  1801. """Update |dotgit| to reference |gitdir|, using symlinks where possible.
  1802. Args:
  1803. gitdir: The bare git repository. Must already be initialized.
  1804. dotgit: The repository you would like to initialize.
  1805. share_refs: If true, |dotgit| will store its refs under |gitdir|.
  1806. Only one work tree can store refs under a given |gitdir|.
  1807. copy_all: If true, copy all remaining files from |gitdir| -> |dotgit|.
  1808. This saves you the effort of initializing |dotgit| yourself.
  1809. """
  1810. # These objects can be shared between several working trees.
  1811. symlink_files = ['description', 'info']
  1812. symlink_dirs = ['hooks', 'objects', 'rr-cache', 'svn']
  1813. if share_refs:
  1814. # These objects can only be used by a single working tree.
  1815. symlink_files += ['config', 'packed-refs']
  1816. symlink_dirs += ['logs', 'refs']
  1817. to_symlink = symlink_files + symlink_dirs
  1818. to_copy = []
  1819. if copy_all:
  1820. to_copy = os.listdir(gitdir)
  1821. for name in set(to_copy).union(to_symlink):
  1822. try:
  1823. src = os.path.realpath(os.path.join(gitdir, name))
  1824. dst = os.path.realpath(os.path.join(dotgit, name))
  1825. if os.path.lexists(dst) and not os.path.islink(dst):
  1826. raise GitError('cannot overwrite a local work tree')
  1827. # If the source dir doesn't exist, create an empty dir.
  1828. if name in symlink_dirs and not os.path.lexists(src):
  1829. os.makedirs(src)
  1830. if name in to_symlink:
  1831. os.symlink(os.path.relpath(src, os.path.dirname(dst)), dst)
  1832. elif copy_all and not os.path.islink(dst):
  1833. if os.path.isdir(src):
  1834. shutil.copytree(src, dst)
  1835. elif os.path.isfile(src):
  1836. shutil.copy(src, dst)
  1837. except OSError as e:
  1838. if e.errno == errno.EPERM:
  1839. raise GitError('filesystem must support symlinks')
  1840. else:
  1841. raise
  1842. def _InitWorkTree(self):
  1843. dotgit = os.path.join(self.worktree, '.git')
  1844. if not os.path.exists(dotgit):
  1845. os.makedirs(dotgit)
  1846. self._ReferenceGitDir(self.gitdir, dotgit, share_refs=True,
  1847. copy_all=False)
  1848. _lwrite(os.path.join(dotgit, HEAD), '%s\n' % self.GetRevisionId())
  1849. cmd = ['read-tree', '--reset', '-u']
  1850. cmd.append('-v')
  1851. cmd.append(HEAD)
  1852. if GitCommand(self, cmd).Wait() != 0:
  1853. raise GitError("cannot initialize work tree")
  1854. self._CopyFiles()
  1855. def _gitdir_path(self, path):
  1856. return os.path.realpath(os.path.join(self.gitdir, path))
  1857. def _revlist(self, *args, **kw):
  1858. a = []
  1859. a.extend(args)
  1860. a.append('--')
  1861. return self.work_git.rev_list(*a, **kw)
  1862. @property
  1863. def _allrefs(self):
  1864. return self.bare_ref.all
  1865. class _GitGetByExec(object):
  1866. def __init__(self, project, bare, gitdir):
  1867. self._project = project
  1868. self._bare = bare
  1869. self._gitdir = gitdir
  1870. def LsOthers(self):
  1871. p = GitCommand(self._project,
  1872. ['ls-files',
  1873. '-z',
  1874. '--others',
  1875. '--exclude-standard'],
  1876. bare = False,
  1877. gitdir=self._gitdir,
  1878. capture_stdout = True,
  1879. capture_stderr = True)
  1880. if p.Wait() == 0:
  1881. out = p.stdout
  1882. if out:
  1883. return out[:-1].split('\0') # pylint: disable=W1401
  1884. # Backslash is not anomalous
  1885. return []
  1886. def DiffZ(self, name, *args):
  1887. cmd = [name]
  1888. cmd.append('-z')
  1889. cmd.extend(args)
  1890. p = GitCommand(self._project,
  1891. cmd,
  1892. gitdir=self._gitdir,
  1893. bare = False,
  1894. capture_stdout = True,
  1895. capture_stderr = True)
  1896. try:
  1897. out = p.process.stdout.read()
  1898. r = {}
  1899. if out:
  1900. out = iter(out[:-1].split('\0')) # pylint: disable=W1401
  1901. while out:
  1902. try:
  1903. info = out.next()
  1904. path = out.next()
  1905. except StopIteration:
  1906. break
  1907. class _Info(object):
  1908. def __init__(self, path, omode, nmode, oid, nid, state):
  1909. self.path = path
  1910. self.src_path = None
  1911. self.old_mode = omode
  1912. self.new_mode = nmode
  1913. self.old_id = oid
  1914. self.new_id = nid
  1915. if len(state) == 1:
  1916. self.status = state
  1917. self.level = None
  1918. else:
  1919. self.status = state[:1]
  1920. self.level = state[1:]
  1921. while self.level.startswith('0'):
  1922. self.level = self.level[1:]
  1923. info = info[1:].split(' ')
  1924. info = _Info(path, *info)
  1925. if info.status in ('R', 'C'):
  1926. info.src_path = info.path
  1927. info.path = out.next()
  1928. r[info.path] = info
  1929. return r
  1930. finally:
  1931. p.Wait()
  1932. def GetHead(self):
  1933. if self._bare:
  1934. path = os.path.join(self._project.gitdir, HEAD)
  1935. else:
  1936. path = os.path.join(self._project.worktree, '.git', HEAD)
  1937. try:
  1938. fd = open(path, 'rb')
  1939. except IOError:
  1940. raise NoManifestException(path)
  1941. try:
  1942. line = fd.read()
  1943. finally:
  1944. fd.close()
  1945. try:
  1946. line = line.decode()
  1947. except AttributeError:
  1948. pass
  1949. if line.startswith('ref: '):
  1950. return line[5:-1]
  1951. return line[:-1]
  1952. def SetHead(self, ref, message=None):
  1953. cmdv = []
  1954. if message is not None:
  1955. cmdv.extend(['-m', message])
  1956. cmdv.append(HEAD)
  1957. cmdv.append(ref)
  1958. self.symbolic_ref(*cmdv)
  1959. def DetachHead(self, new, message=None):
  1960. cmdv = ['--no-deref']
  1961. if message is not None:
  1962. cmdv.extend(['-m', message])
  1963. cmdv.append(HEAD)
  1964. cmdv.append(new)
  1965. self.update_ref(*cmdv)
  1966. def UpdateRef(self, name, new, old=None,
  1967. message=None,
  1968. detach=False):
  1969. cmdv = []
  1970. if message is not None:
  1971. cmdv.extend(['-m', message])
  1972. if detach:
  1973. cmdv.append('--no-deref')
  1974. cmdv.append(name)
  1975. cmdv.append(new)
  1976. if old is not None:
  1977. cmdv.append(old)
  1978. self.update_ref(*cmdv)
  1979. def DeleteRef(self, name, old=None):
  1980. if not old:
  1981. old = self.rev_parse(name)
  1982. self.update_ref('-d', name, old)
  1983. self._project.bare_ref.deleted(name)
  1984. def rev_list(self, *args, **kw):
  1985. if 'format' in kw:
  1986. cmdv = ['log', '--pretty=format:%s' % kw['format']]
  1987. else:
  1988. cmdv = ['rev-list']
  1989. cmdv.extend(args)
  1990. p = GitCommand(self._project,
  1991. cmdv,
  1992. bare = self._bare,
  1993. gitdir=self._gitdir,
  1994. capture_stdout = True,
  1995. capture_stderr = True)
  1996. r = []
  1997. for line in p.process.stdout:
  1998. if line[-1] == '\n':
  1999. line = line[:-1]
  2000. r.append(line)
  2001. if p.Wait() != 0:
  2002. raise GitError('%s rev-list %s: %s' % (
  2003. self._project.name,
  2004. str(args),
  2005. p.stderr))
  2006. return r
  2007. def __getattr__(self, name):
  2008. """Allow arbitrary git commands using pythonic syntax.
  2009. This allows you to do things like:
  2010. git_obj.rev_parse('HEAD')
  2011. Since we don't have a 'rev_parse' method defined, the __getattr__ will
  2012. run. We'll replace the '_' with a '-' and try to run a git command.
  2013. Any other positional arguments will be passed to the git command, and the
  2014. following keyword arguments are supported:
  2015. config: An optional dict of git config options to be passed with '-c'.
  2016. Args:
  2017. name: The name of the git command to call. Any '_' characters will
  2018. be replaced with '-'.
  2019. Returns:
  2020. A callable object that will try to call git with the named command.
  2021. """
  2022. name = name.replace('_', '-')
  2023. def runner(*args, **kwargs):
  2024. cmdv = []
  2025. config = kwargs.pop('config', None)
  2026. for k in kwargs:
  2027. raise TypeError('%s() got an unexpected keyword argument %r'
  2028. % (name, k))
  2029. if config is not None:
  2030. if not git_require((1, 7, 2)):
  2031. raise ValueError('cannot set config on command line for %s()'
  2032. % name)
  2033. for k, v in config.items():
  2034. cmdv.append('-c')
  2035. cmdv.append('%s=%s' % (k, v))
  2036. cmdv.append(name)
  2037. cmdv.extend(args)
  2038. p = GitCommand(self._project,
  2039. cmdv,
  2040. bare = self._bare,
  2041. gitdir=self._gitdir,
  2042. capture_stdout = True,
  2043. capture_stderr = True)
  2044. if p.Wait() != 0:
  2045. raise GitError('%s %s: %s' % (
  2046. self._project.name,
  2047. name,
  2048. p.stderr))
  2049. r = p.stdout
  2050. try:
  2051. r = r.decode('utf-8')
  2052. except AttributeError:
  2053. pass
  2054. if r.endswith('\n') and r.index('\n') == len(r) - 1:
  2055. return r[:-1]
  2056. return r
  2057. return runner
  2058. class _PriorSyncFailedError(Exception):
  2059. def __str__(self):
  2060. return 'prior sync failed; rebase still in progress'
  2061. class _DirtyError(Exception):
  2062. def __str__(self):
  2063. return 'contains uncommitted changes'
  2064. class _InfoMessage(object):
  2065. def __init__(self, project, text):
  2066. self.project = project
  2067. self.text = text
  2068. def Print(self, syncbuf):
  2069. syncbuf.out.info('%s/: %s', self.project.relpath, self.text)
  2070. syncbuf.out.nl()
  2071. class _Failure(object):
  2072. def __init__(self, project, why):
  2073. self.project = project
  2074. self.why = why
  2075. def Print(self, syncbuf):
  2076. syncbuf.out.fail('error: %s/: %s',
  2077. self.project.relpath,
  2078. str(self.why))
  2079. syncbuf.out.nl()
  2080. class _Later(object):
  2081. def __init__(self, project, action):
  2082. self.project = project
  2083. self.action = action
  2084. def Run(self, syncbuf):
  2085. out = syncbuf.out
  2086. out.project('project %s/', self.project.relpath)
  2087. out.nl()
  2088. try:
  2089. self.action()
  2090. out.nl()
  2091. return True
  2092. except GitError:
  2093. out.nl()
  2094. return False
  2095. class _SyncColoring(Coloring):
  2096. def __init__(self, config):
  2097. Coloring.__init__(self, config, 'reposync')
  2098. self.project = self.printer('header', attr = 'bold')
  2099. self.info = self.printer('info')
  2100. self.fail = self.printer('fail', fg='red')
  2101. class SyncBuffer(object):
  2102. def __init__(self, config, detach_head=False):
  2103. self._messages = []
  2104. self._failures = []
  2105. self._later_queue1 = []
  2106. self._later_queue2 = []
  2107. self.out = _SyncColoring(config)
  2108. self.out.redirect(sys.stderr)
  2109. self.detach_head = detach_head
  2110. self.clean = True
  2111. def info(self, project, fmt, *args):
  2112. self._messages.append(_InfoMessage(project, fmt % args))
  2113. def fail(self, project, err=None):
  2114. self._failures.append(_Failure(project, err))
  2115. self.clean = False
  2116. def later1(self, project, what):
  2117. self._later_queue1.append(_Later(project, what))
  2118. def later2(self, project, what):
  2119. self._later_queue2.append(_Later(project, what))
  2120. def Finish(self):
  2121. self._PrintMessages()
  2122. self._RunLater()
  2123. self._PrintMessages()
  2124. return self.clean
  2125. def _RunLater(self):
  2126. for q in ['_later_queue1', '_later_queue2']:
  2127. if not self._RunQueue(q):
  2128. return
  2129. def _RunQueue(self, queue):
  2130. for m in getattr(self, queue):
  2131. if not m.Run(self):
  2132. self.clean = False
  2133. return False
  2134. setattr(self, queue, [])
  2135. return True
  2136. def _PrintMessages(self):
  2137. for m in self._messages:
  2138. m.Print(self)
  2139. for m in self._failures:
  2140. m.Print(self)
  2141. self._messages = []
  2142. self._failures = []
  2143. class MetaProject(Project):
  2144. """A special project housed under .repo.
  2145. """
  2146. def __init__(self, manifest, name, gitdir, worktree):
  2147. Project.__init__(self,
  2148. manifest = manifest,
  2149. name = name,
  2150. gitdir = gitdir,
  2151. objdir = gitdir,
  2152. worktree = worktree,
  2153. remote = RemoteSpec('origin'),
  2154. relpath = '.repo/%s' % name,
  2155. revisionExpr = 'refs/heads/master',
  2156. revisionId = None,
  2157. groups = None)
  2158. def PreSync(self):
  2159. if self.Exists:
  2160. cb = self.CurrentBranch
  2161. if cb:
  2162. base = self.GetBranch(cb).merge
  2163. if base:
  2164. self.revisionExpr = base
  2165. self.revisionId = None
  2166. def MetaBranchSwitch(self, target):
  2167. """ Prepare MetaProject for manifest branch switch
  2168. """
  2169. # detach and delete manifest branch, allowing a new
  2170. # branch to take over
  2171. syncbuf = SyncBuffer(self.config, detach_head = True)
  2172. self.Sync_LocalHalf(syncbuf)
  2173. syncbuf.Finish()
  2174. return GitCommand(self,
  2175. ['update-ref', '-d', 'refs/heads/default'],
  2176. capture_stdout = True,
  2177. capture_stderr = True).Wait() == 0
  2178. @property
  2179. def LastFetch(self):
  2180. try:
  2181. fh = os.path.join(self.gitdir, 'FETCH_HEAD')
  2182. return os.path.getmtime(fh)
  2183. except OSError:
  2184. return 0
  2185. @property
  2186. def HasChanges(self):
  2187. """Has the remote received new commits not yet checked out?
  2188. """
  2189. if not self.remote or not self.revisionExpr:
  2190. return False
  2191. all_refs = self.bare_ref.all
  2192. revid = self.GetRevisionId(all_refs)
  2193. head = self.work_git.GetHead()
  2194. if head.startswith(R_HEADS):
  2195. try:
  2196. head = all_refs[head]
  2197. except KeyError:
  2198. head = None
  2199. if revid == head:
  2200. return False
  2201. elif self._revlist(not_rev(HEAD), revid):
  2202. return True
  2203. return False