project.py 83 KB

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