project.py 60 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130
  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. import traceback
  15. import errno
  16. import filecmp
  17. import os
  18. import random
  19. import re
  20. import shutil
  21. import stat
  22. import sys
  23. import time
  24. import urllib2
  25. try:
  26. import threading as _threading
  27. except ImportError:
  28. import dummy_threading as _threading
  29. try:
  30. from os import SEEK_END
  31. except ImportError:
  32. SEEK_END = 2
  33. from color import Coloring
  34. from git_command import GitCommand
  35. from git_config import GitConfig, IsId, GetSchemeFromUrl, ID_RE
  36. from error import DownloadError
  37. from error import GitError, HookError, ImportError, UploadError
  38. from error import ManifestInvalidRevisionError
  39. from progress import Progress
  40. from git_refs import GitRefs, HEAD, R_HEADS, R_TAGS, R_PUB, R_M
  41. _urllib_lock = _threading.Lock()
  42. def _lwrite(path, content):
  43. lock = '%s.lock' % path
  44. fd = open(lock, 'wb')
  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 >>sys.stderr, 'error: %s' % msg
  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.abspath(os.path.dirname(__file__))
  74. d = os.path.join(d , 'hooks')
  75. _project_hook_list = map(lambda x: os.path.join(d, x), os.listdir(d))
  76. return _project_hook_list
  77. def relpath(dst, src):
  78. src = os.path.dirname(src)
  79. top = os.path.commonprefix([dst, src])
  80. if top.endswith('/'):
  81. top = top[:-1]
  82. else:
  83. top = os.path.dirname(top)
  84. tmp = src
  85. rel = ''
  86. while top != tmp:
  87. rel += '../'
  88. tmp = os.path.dirname(tmp)
  89. return rel + dst[len(top) + 1:]
  90. class DownloadedChange(object):
  91. _commit_cache = None
  92. def __init__(self, project, base, change_id, ps_id, commit):
  93. self.project = project
  94. self.base = base
  95. self.change_id = change_id
  96. self.ps_id = ps_id
  97. self.commit = commit
  98. @property
  99. def commits(self):
  100. if self._commit_cache is None:
  101. self._commit_cache = self.project.bare_git.rev_list(
  102. '--abbrev=8',
  103. '--abbrev-commit',
  104. '--pretty=oneline',
  105. '--reverse',
  106. '--date-order',
  107. not_rev(self.base),
  108. self.commit,
  109. '--')
  110. return self._commit_cache
  111. class ReviewableBranch(object):
  112. _commit_cache = None
  113. def __init__(self, project, branch, base):
  114. self.project = project
  115. self.branch = branch
  116. self.base = base
  117. @property
  118. def name(self):
  119. return self.branch.name
  120. @property
  121. def commits(self):
  122. if self._commit_cache is None:
  123. self._commit_cache = self.project.bare_git.rev_list(
  124. '--abbrev=8',
  125. '--abbrev-commit',
  126. '--pretty=oneline',
  127. '--reverse',
  128. '--date-order',
  129. not_rev(self.base),
  130. R_HEADS + self.name,
  131. '--')
  132. return self._commit_cache
  133. @property
  134. def unabbrev_commits(self):
  135. r = dict()
  136. for commit in self.project.bare_git.rev_list(
  137. not_rev(self.base),
  138. R_HEADS + self.name,
  139. '--'):
  140. r[commit[0:8]] = commit
  141. return r
  142. @property
  143. def date(self):
  144. return self.project.bare_git.log(
  145. '--pretty=format:%cd',
  146. '-n', '1',
  147. R_HEADS + self.name,
  148. '--')
  149. def UploadForReview(self, people, auto_topic=False):
  150. self.project.UploadForReview(self.name,
  151. people,
  152. auto_topic=auto_topic)
  153. def GetPublishedRefs(self):
  154. refs = {}
  155. output = self.project.bare_git.ls_remote(
  156. self.branch.remote.SshReviewUrl(self.project.UserEmail),
  157. 'refs/changes/*')
  158. for line in output.split('\n'):
  159. try:
  160. (sha, ref) = line.split()
  161. refs[sha] = ref
  162. except ValueError:
  163. pass
  164. return refs
  165. class StatusColoring(Coloring):
  166. def __init__(self, config):
  167. Coloring.__init__(self, config, 'status')
  168. self.project = self.printer('header', attr = 'bold')
  169. self.branch = self.printer('header', attr = 'bold')
  170. self.nobranch = self.printer('nobranch', fg = 'red')
  171. self.important = self.printer('important', fg = 'red')
  172. self.added = self.printer('added', fg = 'green')
  173. self.changed = self.printer('changed', fg = 'red')
  174. self.untracked = self.printer('untracked', fg = 'red')
  175. class DiffColoring(Coloring):
  176. def __init__(self, config):
  177. Coloring.__init__(self, config, 'diff')
  178. self.project = self.printer('header', attr = 'bold')
  179. class _CopyFile:
  180. def __init__(self, src, dest, abssrc, absdest):
  181. self.src = src
  182. self.dest = dest
  183. self.abs_src = abssrc
  184. self.abs_dest = absdest
  185. def _Copy(self):
  186. src = self.abs_src
  187. dest = self.abs_dest
  188. # copy file if it does not exist or is out of date
  189. if not os.path.exists(dest) or not filecmp.cmp(src, dest):
  190. try:
  191. # remove existing file first, since it might be read-only
  192. if os.path.exists(dest):
  193. os.remove(dest)
  194. else:
  195. dir = os.path.dirname(dest)
  196. if not os.path.isdir(dir):
  197. os.makedirs(dir)
  198. shutil.copy(src, dest)
  199. # make the file read-only
  200. mode = os.stat(dest)[stat.ST_MODE]
  201. mode = mode & ~(stat.S_IWUSR | stat.S_IWGRP | stat.S_IWOTH)
  202. os.chmod(dest, mode)
  203. except IOError:
  204. _error('Cannot copy file %s to %s', src, dest)
  205. class RemoteSpec(object):
  206. def __init__(self,
  207. name,
  208. url = None,
  209. review = None):
  210. self.name = name
  211. self.url = url
  212. self.review = review
  213. class RepoHook(object):
  214. """A RepoHook contains information about a script to run as a hook.
  215. Hooks are used to run a python script before running an upload (for instance,
  216. to run presubmit checks). Eventually, we may have hooks for other actions.
  217. This shouldn't be confused with files in the 'repo/hooks' directory. Those
  218. files are copied into each '.git/hooks' folder for each project. Repo-level
  219. hooks are associated instead with repo actions.
  220. Hooks are always python. When a hook is run, we will load the hook into the
  221. interpreter and execute its main() function.
  222. """
  223. def __init__(self,
  224. hook_type,
  225. hooks_project,
  226. topdir,
  227. abort_if_user_denies=False):
  228. """RepoHook constructor.
  229. Params:
  230. hook_type: A string representing the type of hook. This is also used
  231. to figure out the name of the file containing the hook. For
  232. example: 'pre-upload'.
  233. hooks_project: The project containing the repo hooks. If you have a
  234. manifest, this is manifest.repo_hooks_project. OK if this is None,
  235. which will make the hook a no-op.
  236. topdir: Repo's top directory (the one containing the .repo directory).
  237. Scripts will run with CWD as this directory. If you have a manifest,
  238. this is manifest.topdir
  239. abort_if_user_denies: If True, we'll throw a HookError() if the user
  240. doesn't allow us to run the hook.
  241. """
  242. self._hook_type = hook_type
  243. self._hooks_project = hooks_project
  244. self._topdir = topdir
  245. self._abort_if_user_denies = abort_if_user_denies
  246. # Store the full path to the script for convenience.
  247. if self._hooks_project:
  248. self._script_fullpath = os.path.join(self._hooks_project.worktree,
  249. self._hook_type + '.py')
  250. else:
  251. self._script_fullpath = None
  252. def _GetHash(self):
  253. """Return a hash of the contents of the hooks directory.
  254. We'll just use git to do this. This hash has the property that if anything
  255. changes in the directory we will return a different has.
  256. SECURITY CONSIDERATION:
  257. This hash only represents the contents of files in the hook directory, not
  258. any other files imported or called by hooks. Changes to imported files
  259. can change the script behavior without affecting the hash.
  260. Returns:
  261. A string representing the hash. This will always be ASCII so that it can
  262. be printed to the user easily.
  263. """
  264. assert self._hooks_project, "Must have hooks to calculate their hash."
  265. # We will use the work_git object rather than just calling GetRevisionId().
  266. # That gives us a hash of the latest checked in version of the files that
  267. # the user will actually be executing. Specifically, GetRevisionId()
  268. # doesn't appear to change even if a user checks out a different version
  269. # of the hooks repo (via git checkout) nor if a user commits their own revs.
  270. #
  271. # NOTE: Local (non-committed) changes will not be factored into this hash.
  272. # I think this is OK, since we're really only worried about warning the user
  273. # about upstream changes.
  274. return self._hooks_project.work_git.rev_parse('HEAD')
  275. def _GetMustVerb(self):
  276. """Return 'must' if the hook is required; 'should' if not."""
  277. if self._abort_if_user_denies:
  278. return 'must'
  279. else:
  280. return 'should'
  281. def _CheckForHookApproval(self):
  282. """Check to see whether this hook has been approved.
  283. We'll look at the hash of all of the hooks. If this matches the hash that
  284. the user last approved, we're done. If it doesn't, we'll ask the user
  285. about approval.
  286. Note that we ask permission for each individual hook even though we use
  287. the hash of all hooks when detecting changes. We'd like the user to be
  288. able to approve / deny each hook individually. We only use the hash of all
  289. hooks because there is no other easy way to detect changes to local imports.
  290. Returns:
  291. True if this hook is approved to run; False otherwise.
  292. Raises:
  293. HookError: Raised if the user doesn't approve and abort_if_user_denies
  294. was passed to the consturctor.
  295. """
  296. hooks_dir = self._hooks_project.worktree
  297. hooks_config = self._hooks_project.config
  298. git_approval_key = 'repo.hooks.%s.approvedhash' % self._hook_type
  299. # Get the last hash that the user approved for this hook; may be None.
  300. old_hash = hooks_config.GetString(git_approval_key)
  301. # Get the current hash so we can tell if scripts changed since approval.
  302. new_hash = self._GetHash()
  303. if old_hash is not None:
  304. # User previously approved hook and asked not to be prompted again.
  305. if new_hash == old_hash:
  306. # Approval matched. We're done.
  307. return True
  308. else:
  309. # Give the user a reason why we're prompting, since they last told
  310. # us to "never ask again".
  311. prompt = 'WARNING: Scripts have changed since %s was allowed.\n\n' % (
  312. self._hook_type)
  313. else:
  314. prompt = ''
  315. # Prompt the user if we're not on a tty; on a tty we'll assume "no".
  316. if sys.stdout.isatty():
  317. prompt += ('Repo %s run the script:\n'
  318. ' %s\n'
  319. '\n'
  320. 'Do you want to allow this script to run '
  321. '(yes/yes-never-ask-again/NO)? ') % (
  322. self._GetMustVerb(), self._script_fullpath)
  323. response = raw_input(prompt).lower()
  324. print
  325. # User is doing a one-time approval.
  326. if response in ('y', 'yes'):
  327. return True
  328. elif response == 'yes-never-ask-again':
  329. hooks_config.SetString(git_approval_key, new_hash)
  330. return True
  331. # For anything else, we'll assume no approval.
  332. if self._abort_if_user_denies:
  333. raise HookError('You must allow the %s hook or use --no-verify.' %
  334. self._hook_type)
  335. return False
  336. def _ExecuteHook(self, **kwargs):
  337. """Actually execute the given hook.
  338. This will run the hook's 'main' function in our python interpreter.
  339. Args:
  340. kwargs: Keyword arguments to pass to the hook. These are often specific
  341. to the hook type. For instance, pre-upload hooks will contain
  342. a project_list.
  343. """
  344. # Keep sys.path and CWD stashed away so that we can always restore them
  345. # upon function exit.
  346. orig_path = os.getcwd()
  347. orig_syspath = sys.path
  348. try:
  349. # Always run hooks with CWD as topdir.
  350. os.chdir(self._topdir)
  351. # Put the hook dir as the first item of sys.path so hooks can do
  352. # relative imports. We want to replace the repo dir as [0] so
  353. # hooks can't import repo files.
  354. sys.path = [os.path.dirname(self._script_fullpath)] + sys.path[1:]
  355. # Exec, storing global context in the context dict. We catch exceptions
  356. # and convert to a HookError w/ just the failing traceback.
  357. context = {}
  358. try:
  359. execfile(self._script_fullpath, context)
  360. except Exception:
  361. raise HookError('%s\nFailed to import %s hook; see traceback above.' % (
  362. traceback.format_exc(), self._hook_type))
  363. # Running the script should have defined a main() function.
  364. if 'main' not in context:
  365. raise HookError('Missing main() in: "%s"' % self._script_fullpath)
  366. # Add 'hook_should_take_kwargs' to the arguments to be passed to main.
  367. # We don't actually want hooks to define their main with this argument--
  368. # it's there to remind them that their hook should always take **kwargs.
  369. # For instance, a pre-upload hook should be defined like:
  370. # def main(project_list, **kwargs):
  371. #
  372. # This allows us to later expand the API without breaking old hooks.
  373. kwargs = kwargs.copy()
  374. kwargs['hook_should_take_kwargs'] = True
  375. # Call the main function in the hook. If the hook should cause the
  376. # build to fail, it will raise an Exception. We'll catch that convert
  377. # to a HookError w/ just the failing traceback.
  378. try:
  379. context['main'](**kwargs)
  380. except Exception:
  381. raise HookError('%s\nFailed to run main() for %s hook; see traceback '
  382. 'above.' % (
  383. traceback.format_exc(), self._hook_type))
  384. finally:
  385. # Restore sys.path and CWD.
  386. sys.path = orig_syspath
  387. os.chdir(orig_path)
  388. def Run(self, user_allows_all_hooks, **kwargs):
  389. """Run the hook.
  390. If the hook doesn't exist (because there is no hooks project or because
  391. this particular hook is not enabled), this is a no-op.
  392. Args:
  393. user_allows_all_hooks: If True, we will never prompt about running the
  394. hook--we'll just assume it's OK to run it.
  395. kwargs: Keyword arguments to pass to the hook. These are often specific
  396. to the hook type. For instance, pre-upload hooks will contain
  397. a project_list.
  398. Raises:
  399. HookError: If there was a problem finding the hook or the user declined
  400. to run a required hook (from _CheckForHookApproval).
  401. """
  402. # No-op if there is no hooks project or if hook is disabled.
  403. if ((not self._hooks_project) or
  404. (self._hook_type not in self._hooks_project.enabled_repo_hooks)):
  405. return
  406. # Bail with a nice error if we can't find the hook.
  407. if not os.path.isfile(self._script_fullpath):
  408. raise HookError('Couldn\'t find repo hook: "%s"' % self._script_fullpath)
  409. # Make sure the user is OK with running the hook.
  410. if (not user_allows_all_hooks) and (not self._CheckForHookApproval()):
  411. return
  412. # Run the hook with the same version of python we're using.
  413. self._ExecuteHook(**kwargs)
  414. class Project(object):
  415. def __init__(self,
  416. manifest,
  417. name,
  418. remote,
  419. gitdir,
  420. worktree,
  421. relpath,
  422. revisionExpr,
  423. revisionId,
  424. rebase = True):
  425. self.manifest = manifest
  426. self.name = name
  427. self.remote = remote
  428. self.gitdir = gitdir.replace('\\', '/')
  429. if worktree:
  430. self.worktree = worktree.replace('\\', '/')
  431. else:
  432. self.worktree = None
  433. self.relpath = relpath
  434. self.revisionExpr = revisionExpr
  435. if revisionId is None \
  436. and revisionExpr \
  437. and IsId(revisionExpr):
  438. self.revisionId = revisionExpr
  439. else:
  440. self.revisionId = revisionId
  441. self.rebase = rebase
  442. self.snapshots = {}
  443. self.copyfiles = []
  444. self.config = GitConfig.ForRepository(
  445. gitdir = self.gitdir,
  446. defaults = self.manifest.globalConfig)
  447. if self.worktree:
  448. self.work_git = self._GitGetByExec(self, bare=False)
  449. else:
  450. self.work_git = None
  451. self.bare_git = self._GitGetByExec(self, bare=True)
  452. self.bare_ref = GitRefs(gitdir)
  453. # This will be filled in if a project is later identified to be the
  454. # project containing repo hooks.
  455. self.enabled_repo_hooks = []
  456. @property
  457. def Exists(self):
  458. return os.path.isdir(self.gitdir)
  459. @property
  460. def CurrentBranch(self):
  461. """Obtain the name of the currently checked out branch.
  462. The branch name omits the 'refs/heads/' prefix.
  463. None is returned if the project is on a detached HEAD.
  464. """
  465. b = self.work_git.GetHead()
  466. if b.startswith(R_HEADS):
  467. return b[len(R_HEADS):]
  468. return None
  469. def IsRebaseInProgress(self):
  470. w = self.worktree
  471. g = os.path.join(w, '.git')
  472. return os.path.exists(os.path.join(g, 'rebase-apply')) \
  473. or os.path.exists(os.path.join(g, 'rebase-merge')) \
  474. or os.path.exists(os.path.join(w, '.dotest'))
  475. def IsDirty(self, consider_untracked=True):
  476. """Is the working directory modified in some way?
  477. """
  478. self.work_git.update_index('-q',
  479. '--unmerged',
  480. '--ignore-missing',
  481. '--refresh')
  482. if self.work_git.DiffZ('diff-index','-M','--cached',HEAD):
  483. return True
  484. if self.work_git.DiffZ('diff-files'):
  485. return True
  486. if consider_untracked and self.work_git.LsOthers():
  487. return True
  488. return False
  489. _userident_name = None
  490. _userident_email = None
  491. @property
  492. def UserName(self):
  493. """Obtain the user's personal name.
  494. """
  495. if self._userident_name is None:
  496. self._LoadUserIdentity()
  497. return self._userident_name
  498. @property
  499. def UserEmail(self):
  500. """Obtain the user's email address. This is very likely
  501. to be their Gerrit login.
  502. """
  503. if self._userident_email is None:
  504. self._LoadUserIdentity()
  505. return self._userident_email
  506. def _LoadUserIdentity(self):
  507. u = self.bare_git.var('GIT_COMMITTER_IDENT')
  508. m = re.compile("^(.*) <([^>]*)> ").match(u)
  509. if m:
  510. self._userident_name = m.group(1)
  511. self._userident_email = m.group(2)
  512. else:
  513. self._userident_name = ''
  514. self._userident_email = ''
  515. def GetRemote(self, name):
  516. """Get the configuration for a single remote.
  517. """
  518. return self.config.GetRemote(name)
  519. def GetBranch(self, name):
  520. """Get the configuration for a single branch.
  521. """
  522. return self.config.GetBranch(name)
  523. def GetBranches(self):
  524. """Get all existing local branches.
  525. """
  526. current = self.CurrentBranch
  527. all = self._allrefs
  528. heads = {}
  529. pubd = {}
  530. for name, id in all.iteritems():
  531. if name.startswith(R_HEADS):
  532. name = name[len(R_HEADS):]
  533. b = self.GetBranch(name)
  534. b.current = name == current
  535. b.published = None
  536. b.revision = id
  537. heads[name] = b
  538. for name, id in all.iteritems():
  539. if name.startswith(R_PUB):
  540. name = name[len(R_PUB):]
  541. b = heads.get(name)
  542. if b:
  543. b.published = id
  544. return heads
  545. ## Status Display ##
  546. def HasChanges(self):
  547. """Returns true if there are uncommitted changes.
  548. """
  549. self.work_git.update_index('-q',
  550. '--unmerged',
  551. '--ignore-missing',
  552. '--refresh')
  553. if self.IsRebaseInProgress():
  554. return True
  555. if self.work_git.DiffZ('diff-index', '--cached', HEAD):
  556. return True
  557. if self.work_git.DiffZ('diff-files'):
  558. return True
  559. if self.work_git.LsOthers():
  560. return True
  561. return False
  562. def PrintWorkTreeStatus(self, output_redir=None):
  563. """Prints the status of the repository to stdout.
  564. Args:
  565. output: If specified, redirect the output to this object.
  566. """
  567. if not os.path.isdir(self.worktree):
  568. if output_redir == None:
  569. output_redir = sys.stdout
  570. print >>output_redir, ''
  571. print >>output_redir, 'project %s/' % self.relpath
  572. print >>output_redir, ' missing (run "repo sync")'
  573. return
  574. self.work_git.update_index('-q',
  575. '--unmerged',
  576. '--ignore-missing',
  577. '--refresh')
  578. rb = self.IsRebaseInProgress()
  579. di = self.work_git.DiffZ('diff-index', '-M', '--cached', HEAD)
  580. df = self.work_git.DiffZ('diff-files')
  581. do = self.work_git.LsOthers()
  582. if not rb and not di and not df and not do and not self.CurrentBranch:
  583. return 'CLEAN'
  584. out = StatusColoring(self.config)
  585. if not output_redir == None:
  586. out.redirect(output_redir)
  587. out.project('project %-40s', self.relpath + '/')
  588. branch = self.CurrentBranch
  589. if branch is None:
  590. out.nobranch('(*** NO BRANCH ***)')
  591. else:
  592. out.branch('branch %s', branch)
  593. out.nl()
  594. if rb:
  595. out.important('prior sync failed; rebase still in progress')
  596. out.nl()
  597. paths = list()
  598. paths.extend(di.keys())
  599. paths.extend(df.keys())
  600. paths.extend(do)
  601. paths = list(set(paths))
  602. paths.sort()
  603. for p in paths:
  604. try: i = di[p]
  605. except KeyError: i = None
  606. try: f = df[p]
  607. except KeyError: f = None
  608. if i: i_status = i.status.upper()
  609. else: i_status = '-'
  610. if f: f_status = f.status.lower()
  611. else: f_status = '-'
  612. if i and i.src_path:
  613. line = ' %s%s\t%s => %s (%s%%)' % (i_status, f_status,
  614. i.src_path, p, i.level)
  615. else:
  616. line = ' %s%s\t%s' % (i_status, f_status, p)
  617. if i and not f:
  618. out.added('%s', line)
  619. elif (i and f) or (not i and f):
  620. out.changed('%s', line)
  621. elif not i and not f:
  622. out.untracked('%s', line)
  623. else:
  624. out.write('%s', line)
  625. out.nl()
  626. return 'DIRTY'
  627. def PrintWorkTreeDiff(self):
  628. """Prints the status of the repository to stdout.
  629. """
  630. out = DiffColoring(self.config)
  631. cmd = ['diff']
  632. if out.is_on:
  633. cmd.append('--color')
  634. cmd.append(HEAD)
  635. cmd.append('--')
  636. p = GitCommand(self,
  637. cmd,
  638. capture_stdout = True,
  639. capture_stderr = True)
  640. has_diff = False
  641. for line in p.process.stdout:
  642. if not has_diff:
  643. out.nl()
  644. out.project('project %s/' % self.relpath)
  645. out.nl()
  646. has_diff = True
  647. print line[:-1]
  648. p.Wait()
  649. ## Publish / Upload ##
  650. def WasPublished(self, branch, all=None):
  651. """Was the branch published (uploaded) for code review?
  652. If so, returns the SHA-1 hash of the last published
  653. state for the branch.
  654. """
  655. key = R_PUB + branch
  656. if all is None:
  657. try:
  658. return self.bare_git.rev_parse(key)
  659. except GitError:
  660. return None
  661. else:
  662. try:
  663. return all[key]
  664. except KeyError:
  665. return None
  666. def CleanPublishedCache(self, all=None):
  667. """Prunes any stale published refs.
  668. """
  669. if all is None:
  670. all = self._allrefs
  671. heads = set()
  672. canrm = {}
  673. for name, id in all.iteritems():
  674. if name.startswith(R_HEADS):
  675. heads.add(name)
  676. elif name.startswith(R_PUB):
  677. canrm[name] = id
  678. for name, id in canrm.iteritems():
  679. n = name[len(R_PUB):]
  680. if R_HEADS + n not in heads:
  681. self.bare_git.DeleteRef(name, id)
  682. def GetUploadableBranches(self, selected_branch=None):
  683. """List any branches which can be uploaded for review.
  684. """
  685. heads = {}
  686. pubed = {}
  687. for name, id in self._allrefs.iteritems():
  688. if name.startswith(R_HEADS):
  689. heads[name[len(R_HEADS):]] = id
  690. elif name.startswith(R_PUB):
  691. pubed[name[len(R_PUB):]] = id
  692. ready = []
  693. for branch, id in heads.iteritems():
  694. if branch in pubed and pubed[branch] == id:
  695. continue
  696. if selected_branch and branch != selected_branch:
  697. continue
  698. rb = self.GetUploadableBranch(branch)
  699. if rb:
  700. ready.append(rb)
  701. return ready
  702. def GetUploadableBranch(self, branch_name):
  703. """Get a single uploadable branch, or None.
  704. """
  705. branch = self.GetBranch(branch_name)
  706. base = branch.LocalMerge
  707. if branch.LocalMerge:
  708. rb = ReviewableBranch(self, branch, base)
  709. if rb.commits:
  710. return rb
  711. return None
  712. def UploadForReview(self, branch=None,
  713. people=([],[]),
  714. auto_topic=False):
  715. """Uploads the named branch for code review.
  716. """
  717. if branch is None:
  718. branch = self.CurrentBranch
  719. if branch is None:
  720. raise GitError('not currently on a branch')
  721. branch = self.GetBranch(branch)
  722. if not branch.LocalMerge:
  723. raise GitError('branch %s does not track a remote' % branch.name)
  724. if not branch.remote.review:
  725. raise GitError('remote %s has no review url' % branch.remote.name)
  726. dest_branch = branch.merge
  727. if not dest_branch.startswith(R_HEADS):
  728. dest_branch = R_HEADS + dest_branch
  729. if not branch.remote.projectname:
  730. branch.remote.projectname = self.name
  731. branch.remote.Save()
  732. url = branch.remote.ReviewUrl(self.UserEmail)
  733. if url is None:
  734. raise UploadError('review not configured')
  735. cmd = ['push']
  736. if url.startswith('ssh://'):
  737. rp = ['gerrit receive-pack']
  738. for e in people[0]:
  739. rp.append('--reviewer=%s' % sq(e))
  740. for e in people[1]:
  741. rp.append('--cc=%s' % sq(e))
  742. cmd.append('--receive-pack=%s' % " ".join(rp))
  743. cmd.append(url)
  744. if dest_branch.startswith(R_HEADS):
  745. dest_branch = dest_branch[len(R_HEADS):]
  746. ref_spec = '%s:refs/for/%s' % (R_HEADS + branch.name, dest_branch)
  747. if auto_topic:
  748. ref_spec = ref_spec + '/' + branch.name
  749. cmd.append(ref_spec)
  750. if GitCommand(self, cmd, bare = True).Wait() != 0:
  751. raise UploadError('Upload failed')
  752. msg = "posted to %s for %s" % (branch.remote.review, dest_branch)
  753. self.bare_git.UpdateRef(R_PUB + branch.name,
  754. R_HEADS + branch.name,
  755. message = msg)
  756. ## Sync ##
  757. def Sync_NetworkHalf(self,
  758. quiet=False,
  759. is_new=None,
  760. current_branch_only=False,
  761. clone_bundle=True):
  762. """Perform only the network IO portion of the sync process.
  763. Local working directory/branch state is not affected.
  764. """
  765. if is_new is None:
  766. is_new = not self.Exists
  767. if is_new:
  768. self._InitGitDir()
  769. self._InitRemote()
  770. if is_new:
  771. alt = os.path.join(self.gitdir, 'objects/info/alternates')
  772. try:
  773. fd = open(alt, 'rb')
  774. try:
  775. alt_dir = fd.readline().rstrip()
  776. finally:
  777. fd.close()
  778. except IOError:
  779. alt_dir = None
  780. else:
  781. alt_dir = None
  782. if clone_bundle \
  783. and alt_dir is None \
  784. and self._ApplyCloneBundle(initial=is_new, quiet=quiet):
  785. is_new = False
  786. if not self._RemoteFetch(initial=is_new, quiet=quiet, alt_dir=alt_dir,
  787. current_branch_only=current_branch_only):
  788. return False
  789. if self.worktree:
  790. self._InitMRef()
  791. else:
  792. self._InitMirrorHead()
  793. try:
  794. os.remove(os.path.join(self.gitdir, 'FETCH_HEAD'))
  795. except OSError:
  796. pass
  797. return True
  798. def PostRepoUpgrade(self):
  799. self._InitHooks()
  800. def _CopyFiles(self):
  801. for file in self.copyfiles:
  802. file._Copy()
  803. def GetRevisionId(self, all=None):
  804. if self.revisionId:
  805. return self.revisionId
  806. rem = self.GetRemote(self.remote.name)
  807. rev = rem.ToLocal(self.revisionExpr)
  808. if all is not None and rev in all:
  809. return all[rev]
  810. try:
  811. return self.bare_git.rev_parse('--verify', '%s^0' % rev)
  812. except GitError:
  813. raise ManifestInvalidRevisionError(
  814. 'revision %s in %s not found' % (self.revisionExpr,
  815. self.name))
  816. def Sync_LocalHalf(self, syncbuf):
  817. """Perform only the local IO portion of the sync process.
  818. Network access is not required.
  819. """
  820. all = self.bare_ref.all
  821. self.CleanPublishedCache(all)
  822. revid = self.GetRevisionId(all)
  823. self._InitWorkTree()
  824. head = self.work_git.GetHead()
  825. if head.startswith(R_HEADS):
  826. branch = head[len(R_HEADS):]
  827. try:
  828. head = all[head]
  829. except KeyError:
  830. head = None
  831. else:
  832. branch = None
  833. if branch is None or syncbuf.detach_head:
  834. # Currently on a detached HEAD. The user is assumed to
  835. # not have any local modifications worth worrying about.
  836. #
  837. if self.IsRebaseInProgress():
  838. syncbuf.fail(self, _PriorSyncFailedError())
  839. return
  840. if head == revid:
  841. # No changes; don't do anything further.
  842. #
  843. return
  844. lost = self._revlist(not_rev(revid), HEAD)
  845. if lost:
  846. syncbuf.info(self, "discarding %d commits", len(lost))
  847. try:
  848. self._Checkout(revid, quiet=True)
  849. except GitError, e:
  850. syncbuf.fail(self, e)
  851. return
  852. self._CopyFiles()
  853. return
  854. if head == revid:
  855. # No changes; don't do anything further.
  856. #
  857. return
  858. branch = self.GetBranch(branch)
  859. if not branch.LocalMerge:
  860. # The current branch has no tracking configuration.
  861. # Jump off it to a detached HEAD.
  862. #
  863. syncbuf.info(self,
  864. "leaving %s; does not track upstream",
  865. branch.name)
  866. try:
  867. self._Checkout(revid, quiet=True)
  868. except GitError, e:
  869. syncbuf.fail(self, e)
  870. return
  871. self._CopyFiles()
  872. return
  873. upstream_gain = self._revlist(not_rev(HEAD), revid)
  874. pub = self.WasPublished(branch.name, all)
  875. if pub:
  876. not_merged = self._revlist(not_rev(revid), pub)
  877. if not_merged:
  878. if upstream_gain:
  879. # The user has published this branch and some of those
  880. # commits are not yet merged upstream. We do not want
  881. # to rewrite the published commits so we punt.
  882. #
  883. syncbuf.fail(self,
  884. "branch %s is published (but not merged) and is now %d commits behind"
  885. % (branch.name, len(upstream_gain)))
  886. return
  887. elif pub == head:
  888. # All published commits are merged, and thus we are a
  889. # strict subset. We can fast-forward safely.
  890. #
  891. def _doff():
  892. self._FastForward(revid)
  893. self._CopyFiles()
  894. syncbuf.later1(self, _doff)
  895. return
  896. # Examine the local commits not in the remote. Find the
  897. # last one attributed to this user, if any.
  898. #
  899. local_changes = self._revlist(not_rev(revid), HEAD, format='%H %ce')
  900. last_mine = None
  901. cnt_mine = 0
  902. for commit in local_changes:
  903. commit_id, committer_email = commit.split(' ', 1)
  904. if committer_email == self.UserEmail:
  905. last_mine = commit_id
  906. cnt_mine += 1
  907. if not upstream_gain and cnt_mine == len(local_changes):
  908. return
  909. if self.IsDirty(consider_untracked=False):
  910. syncbuf.fail(self, _DirtyError())
  911. return
  912. # If the upstream switched on us, warn the user.
  913. #
  914. if branch.merge != self.revisionExpr:
  915. if branch.merge and self.revisionExpr:
  916. syncbuf.info(self,
  917. 'manifest switched %s...%s',
  918. branch.merge,
  919. self.revisionExpr)
  920. elif branch.merge:
  921. syncbuf.info(self,
  922. 'manifest no longer tracks %s',
  923. branch.merge)
  924. if cnt_mine < len(local_changes):
  925. # Upstream rebased. Not everything in HEAD
  926. # was created by this user.
  927. #
  928. syncbuf.info(self,
  929. "discarding %d commits removed from upstream",
  930. len(local_changes) - cnt_mine)
  931. branch.remote = self.GetRemote(self.remote.name)
  932. if not ID_RE.match(self.revisionExpr):
  933. # in case of manifest sync the revisionExpr might be a SHA1
  934. branch.merge = self.revisionExpr
  935. branch.Save()
  936. if cnt_mine > 0 and self.rebase:
  937. def _dorebase():
  938. self._Rebase(upstream = '%s^1' % last_mine, onto = revid)
  939. self._CopyFiles()
  940. syncbuf.later2(self, _dorebase)
  941. elif local_changes:
  942. try:
  943. self._ResetHard(revid)
  944. self._CopyFiles()
  945. except GitError, e:
  946. syncbuf.fail(self, e)
  947. return
  948. else:
  949. def _doff():
  950. self._FastForward(revid)
  951. self._CopyFiles()
  952. syncbuf.later1(self, _doff)
  953. def AddCopyFile(self, src, dest, absdest):
  954. # dest should already be an absolute path, but src is project relative
  955. # make src an absolute path
  956. abssrc = os.path.join(self.worktree, src)
  957. self.copyfiles.append(_CopyFile(src, dest, abssrc, absdest))
  958. def DownloadPatchSet(self, change_id, patch_id):
  959. """Download a single patch set of a single change to FETCH_HEAD.
  960. """
  961. remote = self.GetRemote(self.remote.name)
  962. cmd = ['fetch', remote.name]
  963. cmd.append('refs/changes/%2.2d/%d/%d' \
  964. % (change_id % 100, change_id, patch_id))
  965. cmd.extend(map(lambda x: str(x), remote.fetch))
  966. if GitCommand(self, cmd, bare=True).Wait() != 0:
  967. return None
  968. return DownloadedChange(self,
  969. self.GetRevisionId(),
  970. change_id,
  971. patch_id,
  972. self.bare_git.rev_parse('FETCH_HEAD'))
  973. ## Branch Management ##
  974. def StartBranch(self, name):
  975. """Create a new branch off the manifest's revision.
  976. """
  977. head = self.work_git.GetHead()
  978. if head == (R_HEADS + name):
  979. return True
  980. all = self.bare_ref.all
  981. if (R_HEADS + name) in all:
  982. return GitCommand(self,
  983. ['checkout', name, '--'],
  984. capture_stdout = True,
  985. capture_stderr = True).Wait() == 0
  986. branch = self.GetBranch(name)
  987. branch.remote = self.GetRemote(self.remote.name)
  988. branch.merge = self.revisionExpr
  989. revid = self.GetRevisionId(all)
  990. if head.startswith(R_HEADS):
  991. try:
  992. head = all[head]
  993. except KeyError:
  994. head = None
  995. if revid and head and revid == head:
  996. ref = os.path.join(self.gitdir, R_HEADS + name)
  997. try:
  998. os.makedirs(os.path.dirname(ref))
  999. except OSError:
  1000. pass
  1001. _lwrite(ref, '%s\n' % revid)
  1002. _lwrite(os.path.join(self.worktree, '.git', HEAD),
  1003. 'ref: %s%s\n' % (R_HEADS, name))
  1004. branch.Save()
  1005. return True
  1006. if GitCommand(self,
  1007. ['checkout', '-b', branch.name, revid],
  1008. capture_stdout = True,
  1009. capture_stderr = True).Wait() == 0:
  1010. branch.Save()
  1011. return True
  1012. return False
  1013. def CheckoutBranch(self, name):
  1014. """Checkout a local topic branch.
  1015. Args:
  1016. name: The name of the branch to checkout.
  1017. Returns:
  1018. True if the checkout succeeded; False if it didn't; None if the branch
  1019. didn't exist.
  1020. """
  1021. rev = R_HEADS + name
  1022. head = self.work_git.GetHead()
  1023. if head == rev:
  1024. # Already on the branch
  1025. #
  1026. return True
  1027. all = self.bare_ref.all
  1028. try:
  1029. revid = all[rev]
  1030. except KeyError:
  1031. # Branch does not exist in this project
  1032. #
  1033. return None
  1034. if head.startswith(R_HEADS):
  1035. try:
  1036. head = all[head]
  1037. except KeyError:
  1038. head = None
  1039. if head == revid:
  1040. # Same revision; just update HEAD to point to the new
  1041. # target branch, but otherwise take no other action.
  1042. #
  1043. _lwrite(os.path.join(self.worktree, '.git', HEAD),
  1044. 'ref: %s%s\n' % (R_HEADS, name))
  1045. return True
  1046. return GitCommand(self,
  1047. ['checkout', name, '--'],
  1048. capture_stdout = True,
  1049. capture_stderr = True).Wait() == 0
  1050. def AbandonBranch(self, name):
  1051. """Destroy a local topic branch.
  1052. Args:
  1053. name: The name of the branch to abandon.
  1054. Returns:
  1055. True if the abandon succeeded; False if it didn't; None if the branch
  1056. didn't exist.
  1057. """
  1058. rev = R_HEADS + name
  1059. all = self.bare_ref.all
  1060. if rev not in all:
  1061. # Doesn't exist
  1062. return None
  1063. head = self.work_git.GetHead()
  1064. if head == rev:
  1065. # We can't destroy the branch while we are sitting
  1066. # on it. Switch to a detached HEAD.
  1067. #
  1068. head = all[head]
  1069. revid = self.GetRevisionId(all)
  1070. if head == revid:
  1071. _lwrite(os.path.join(self.worktree, '.git', HEAD),
  1072. '%s\n' % revid)
  1073. else:
  1074. self._Checkout(revid, quiet=True)
  1075. return GitCommand(self,
  1076. ['branch', '-D', name],
  1077. capture_stdout = True,
  1078. capture_stderr = True).Wait() == 0
  1079. def PruneHeads(self):
  1080. """Prune any topic branches already merged into upstream.
  1081. """
  1082. cb = self.CurrentBranch
  1083. kill = []
  1084. left = self._allrefs
  1085. for name in left.keys():
  1086. if name.startswith(R_HEADS):
  1087. name = name[len(R_HEADS):]
  1088. if cb is None or name != cb:
  1089. kill.append(name)
  1090. rev = self.GetRevisionId(left)
  1091. if cb is not None \
  1092. and not self._revlist(HEAD + '...' + rev) \
  1093. and not self.IsDirty(consider_untracked = False):
  1094. self.work_git.DetachHead(HEAD)
  1095. kill.append(cb)
  1096. if kill:
  1097. old = self.bare_git.GetHead()
  1098. if old is None:
  1099. old = 'refs/heads/please_never_use_this_as_a_branch_name'
  1100. try:
  1101. self.bare_git.DetachHead(rev)
  1102. b = ['branch', '-d']
  1103. b.extend(kill)
  1104. b = GitCommand(self, b, bare=True,
  1105. capture_stdout=True,
  1106. capture_stderr=True)
  1107. b.Wait()
  1108. finally:
  1109. self.bare_git.SetHead(old)
  1110. left = self._allrefs
  1111. for branch in kill:
  1112. if (R_HEADS + branch) not in left:
  1113. self.CleanPublishedCache()
  1114. break
  1115. if cb and cb not in kill:
  1116. kill.append(cb)
  1117. kill.sort()
  1118. kept = []
  1119. for branch in kill:
  1120. if (R_HEADS + branch) in left:
  1121. branch = self.GetBranch(branch)
  1122. base = branch.LocalMerge
  1123. if not base:
  1124. base = rev
  1125. kept.append(ReviewableBranch(self, branch, base))
  1126. return kept
  1127. ## Direct Git Commands ##
  1128. def _RemoteFetch(self, name=None,
  1129. current_branch_only=False,
  1130. initial=False,
  1131. quiet=False,
  1132. alt_dir=None):
  1133. is_sha1 = False
  1134. tag_name = None
  1135. if current_branch_only:
  1136. if ID_RE.match(self.revisionExpr) is not None:
  1137. is_sha1 = True
  1138. elif self.revisionExpr.startswith(R_TAGS):
  1139. # this is a tag and its sha1 value should never change
  1140. tag_name = self.revisionExpr[len(R_TAGS):]
  1141. if is_sha1 or tag_name is not None:
  1142. try:
  1143. self.GetRevisionId()
  1144. return True
  1145. except ManifestInvalidRevisionError:
  1146. # There is no such persistent revision. We have to fetch it.
  1147. pass
  1148. if not name:
  1149. name = self.remote.name
  1150. ssh_proxy = False
  1151. remote = self.GetRemote(name)
  1152. if remote.PreConnectFetch():
  1153. ssh_proxy = True
  1154. if initial:
  1155. if alt_dir and 'objects' == os.path.basename(alt_dir):
  1156. ref_dir = os.path.dirname(alt_dir)
  1157. packed_refs = os.path.join(self.gitdir, 'packed-refs')
  1158. remote = self.GetRemote(name)
  1159. all = self.bare_ref.all
  1160. ids = set(all.values())
  1161. tmp = set()
  1162. for r, id in GitRefs(ref_dir).all.iteritems():
  1163. if r not in all:
  1164. if r.startswith(R_TAGS) or remote.WritesTo(r):
  1165. all[r] = id
  1166. ids.add(id)
  1167. continue
  1168. if id in ids:
  1169. continue
  1170. r = 'refs/_alt/%s' % id
  1171. all[r] = id
  1172. ids.add(id)
  1173. tmp.add(r)
  1174. ref_names = list(all.keys())
  1175. ref_names.sort()
  1176. tmp_packed = ''
  1177. old_packed = ''
  1178. for r in ref_names:
  1179. line = '%s %s\n' % (all[r], r)
  1180. tmp_packed += line
  1181. if r not in tmp:
  1182. old_packed += line
  1183. _lwrite(packed_refs, tmp_packed)
  1184. else:
  1185. alt_dir = None
  1186. cmd = ['fetch']
  1187. # The --depth option only affects the initial fetch; after that we'll do
  1188. # full fetches of changes.
  1189. depth = self.manifest.manifestProject.config.GetString('repo.depth')
  1190. if depth and initial:
  1191. cmd.append('--depth=%s' % depth)
  1192. if quiet:
  1193. cmd.append('--quiet')
  1194. if not self.worktree:
  1195. cmd.append('--update-head-ok')
  1196. cmd.append(name)
  1197. if not current_branch_only or is_sha1:
  1198. # Fetch whole repo
  1199. cmd.append('--tags')
  1200. cmd.append((u'+refs/heads/*:') + remote.ToLocal('refs/heads/*'))
  1201. elif tag_name is not None:
  1202. cmd.append('tag')
  1203. cmd.append(tag_name)
  1204. else:
  1205. branch = self.revisionExpr
  1206. if branch.startswith(R_HEADS):
  1207. branch = branch[len(R_HEADS):]
  1208. cmd.append((u'+refs/heads/%s:' % branch) + remote.ToLocal('refs/heads/%s' % branch))
  1209. ok = False
  1210. for i in range(2):
  1211. if GitCommand(self, cmd, bare=True, ssh_proxy=ssh_proxy).Wait() == 0:
  1212. ok = True
  1213. break
  1214. time.sleep(random.randint(30, 45))
  1215. if initial:
  1216. if alt_dir:
  1217. if old_packed != '':
  1218. _lwrite(packed_refs, old_packed)
  1219. else:
  1220. os.remove(packed_refs)
  1221. self.bare_git.pack_refs('--all', '--prune')
  1222. return ok
  1223. def _ApplyCloneBundle(self, initial=False, quiet=False):
  1224. if initial and self.manifest.manifestProject.config.GetString('repo.depth'):
  1225. return False
  1226. remote = self.GetRemote(self.remote.name)
  1227. bundle_url = remote.url + '/clone.bundle'
  1228. bundle_url = GitConfig.ForUser().UrlInsteadOf(bundle_url)
  1229. if GetSchemeFromUrl(bundle_url) in ('persistent-http', 'persistent-https'):
  1230. bundle_url = bundle_url[len('persistent-'):]
  1231. if GetSchemeFromUrl(bundle_url) not in ('http', 'https'):
  1232. return False
  1233. bundle_dst = os.path.join(self.gitdir, 'clone.bundle')
  1234. bundle_tmp = os.path.join(self.gitdir, 'clone.bundle.tmp')
  1235. exist_dst = os.path.exists(bundle_dst)
  1236. exist_tmp = os.path.exists(bundle_tmp)
  1237. if not initial and not exist_dst and not exist_tmp:
  1238. return False
  1239. if not exist_dst:
  1240. exist_dst = self._FetchBundle(bundle_url, bundle_tmp, bundle_dst, quiet)
  1241. if not exist_dst:
  1242. return False
  1243. cmd = ['fetch']
  1244. if quiet:
  1245. cmd.append('--quiet')
  1246. if not self.worktree:
  1247. cmd.append('--update-head-ok')
  1248. cmd.append(bundle_dst)
  1249. for f in remote.fetch:
  1250. cmd.append(str(f))
  1251. cmd.append('refs/tags/*:refs/tags/*')
  1252. ok = GitCommand(self, cmd, bare=True).Wait() == 0
  1253. if os.path.exists(bundle_dst):
  1254. os.remove(bundle_dst)
  1255. if os.path.exists(bundle_tmp):
  1256. os.remove(bundle_tmp)
  1257. return ok
  1258. def _FetchBundle(self, srcUrl, tmpPath, dstPath, quiet):
  1259. keep = True
  1260. done = False
  1261. dest = open(tmpPath, 'a+b')
  1262. try:
  1263. dest.seek(0, SEEK_END)
  1264. pos = dest.tell()
  1265. _urllib_lock.acquire()
  1266. try:
  1267. req = urllib2.Request(srcUrl)
  1268. if pos > 0:
  1269. req.add_header('Range', 'bytes=%d-' % pos)
  1270. try:
  1271. r = urllib2.urlopen(req)
  1272. except urllib2.HTTPError, e:
  1273. def _content_type():
  1274. try:
  1275. return e.info()['content-type']
  1276. except:
  1277. return None
  1278. if e.code == 404:
  1279. keep = False
  1280. return False
  1281. elif _content_type() == 'text/plain':
  1282. try:
  1283. msg = e.read()
  1284. if len(msg) > 0 and msg[-1] == '\n':
  1285. msg = msg[0:-1]
  1286. msg = ' (%s)' % msg
  1287. except:
  1288. msg = ''
  1289. else:
  1290. try:
  1291. from BaseHTTPServer import BaseHTTPRequestHandler
  1292. res = BaseHTTPRequestHandler.responses[e.code]
  1293. msg = ' (%s: %s)' % (res[0], res[1])
  1294. except:
  1295. msg = ''
  1296. raise DownloadError('HTTP %s%s' % (e.code, msg))
  1297. except urllib2.URLError, e:
  1298. raise DownloadError('%s: %s ' % (req.get_host(), str(e)))
  1299. finally:
  1300. _urllib_lock.release()
  1301. p = None
  1302. try:
  1303. size = r.headers.get('content-length', 0)
  1304. unit = 1 << 10
  1305. if size and not quiet:
  1306. if size > 1024 * 1.3:
  1307. unit = 1 << 20
  1308. desc = 'MB'
  1309. else:
  1310. desc = 'KB'
  1311. p = Progress(
  1312. 'Downloading %s' % self.relpath,
  1313. int(size) / unit,
  1314. units=desc)
  1315. if pos > 0:
  1316. p.update(pos / unit)
  1317. s = 0
  1318. while True:
  1319. d = r.read(8192)
  1320. if d == '':
  1321. done = True
  1322. return True
  1323. dest.write(d)
  1324. if p:
  1325. s += len(d)
  1326. if s >= unit:
  1327. p.update(s / unit)
  1328. s = s % unit
  1329. if p:
  1330. if s >= unit:
  1331. p.update(s / unit)
  1332. else:
  1333. p.update(1)
  1334. finally:
  1335. r.close()
  1336. if p:
  1337. p.end()
  1338. finally:
  1339. dest.close()
  1340. if os.path.exists(dstPath):
  1341. os.remove(dstPath)
  1342. if done:
  1343. os.rename(tmpPath, dstPath)
  1344. elif not keep:
  1345. os.remove(tmpPath)
  1346. def _Checkout(self, rev, quiet=False):
  1347. cmd = ['checkout']
  1348. if quiet:
  1349. cmd.append('-q')
  1350. cmd.append(rev)
  1351. cmd.append('--')
  1352. if GitCommand(self, cmd).Wait() != 0:
  1353. if self._allrefs:
  1354. raise GitError('%s checkout %s ' % (self.name, rev))
  1355. def _ResetHard(self, rev, quiet=True):
  1356. cmd = ['reset', '--hard']
  1357. if quiet:
  1358. cmd.append('-q')
  1359. cmd.append(rev)
  1360. if GitCommand(self, cmd).Wait() != 0:
  1361. raise GitError('%s reset --hard %s ' % (self.name, rev))
  1362. def _Rebase(self, upstream, onto = None):
  1363. cmd = ['rebase']
  1364. if onto is not None:
  1365. cmd.extend(['--onto', onto])
  1366. cmd.append(upstream)
  1367. if GitCommand(self, cmd).Wait() != 0:
  1368. raise GitError('%s rebase %s ' % (self.name, upstream))
  1369. def _FastForward(self, head):
  1370. cmd = ['merge', head]
  1371. if GitCommand(self, cmd).Wait() != 0:
  1372. raise GitError('%s merge %s ' % (self.name, head))
  1373. def _InitGitDir(self):
  1374. if not os.path.exists(self.gitdir):
  1375. os.makedirs(self.gitdir)
  1376. self.bare_git.init()
  1377. mp = self.manifest.manifestProject
  1378. ref_dir = mp.config.GetString('repo.reference')
  1379. if ref_dir:
  1380. mirror_git = os.path.join(ref_dir, self.name + '.git')
  1381. repo_git = os.path.join(ref_dir, '.repo', 'projects',
  1382. self.relpath + '.git')
  1383. if os.path.exists(mirror_git):
  1384. ref_dir = mirror_git
  1385. elif os.path.exists(repo_git):
  1386. ref_dir = repo_git
  1387. else:
  1388. ref_dir = None
  1389. if ref_dir:
  1390. _lwrite(os.path.join(self.gitdir, 'objects/info/alternates'),
  1391. os.path.join(ref_dir, 'objects') + '\n')
  1392. if self.manifest.IsMirror:
  1393. self.config.SetString('core.bare', 'true')
  1394. else:
  1395. self.config.SetString('core.bare', None)
  1396. hooks = self._gitdir_path('hooks')
  1397. try:
  1398. to_rm = os.listdir(hooks)
  1399. except OSError:
  1400. to_rm = []
  1401. for old_hook in to_rm:
  1402. os.remove(os.path.join(hooks, old_hook))
  1403. self._InitHooks()
  1404. m = self.manifest.manifestProject.config
  1405. for key in ['user.name', 'user.email']:
  1406. if m.Has(key, include_defaults = False):
  1407. self.config.SetString(key, m.GetString(key))
  1408. def _InitHooks(self):
  1409. hooks = self._gitdir_path('hooks')
  1410. if not os.path.exists(hooks):
  1411. os.makedirs(hooks)
  1412. for stock_hook in _ProjectHooks():
  1413. name = os.path.basename(stock_hook)
  1414. if name in ('commit-msg',) and not self.remote.review \
  1415. and not self is self.manifest.manifestProject:
  1416. # Don't install a Gerrit Code Review hook if this
  1417. # project does not appear to use it for reviews.
  1418. #
  1419. # Since the manifest project is one of those, but also
  1420. # managed through gerrit, it's excluded
  1421. continue
  1422. dst = os.path.join(hooks, name)
  1423. if os.path.islink(dst):
  1424. continue
  1425. if os.path.exists(dst):
  1426. if filecmp.cmp(stock_hook, dst, shallow=False):
  1427. os.remove(dst)
  1428. else:
  1429. _error("%s: Not replacing %s hook", self.relpath, name)
  1430. continue
  1431. try:
  1432. os.symlink(relpath(stock_hook, dst), dst)
  1433. except OSError, e:
  1434. if e.errno == errno.EPERM:
  1435. raise GitError('filesystem must support symlinks')
  1436. else:
  1437. raise
  1438. def _InitRemote(self):
  1439. if self.remote.url:
  1440. remote = self.GetRemote(self.remote.name)
  1441. remote.url = self.remote.url
  1442. remote.review = self.remote.review
  1443. remote.projectname = self.name
  1444. if self.worktree:
  1445. remote.ResetFetch(mirror=False)
  1446. else:
  1447. remote.ResetFetch(mirror=True)
  1448. remote.Save()
  1449. def _InitMRef(self):
  1450. if self.manifest.branch:
  1451. self._InitAnyMRef(R_M + self.manifest.branch)
  1452. def _InitMirrorHead(self):
  1453. self._InitAnyMRef(HEAD)
  1454. def _InitAnyMRef(self, ref):
  1455. cur = self.bare_ref.symref(ref)
  1456. if self.revisionId:
  1457. if cur != '' or self.bare_ref.get(ref) != self.revisionId:
  1458. msg = 'manifest set to %s' % self.revisionId
  1459. dst = self.revisionId + '^0'
  1460. self.bare_git.UpdateRef(ref, dst, message = msg, detach = True)
  1461. else:
  1462. remote = self.GetRemote(self.remote.name)
  1463. dst = remote.ToLocal(self.revisionExpr)
  1464. if cur != dst:
  1465. msg = 'manifest set to %s' % self.revisionExpr
  1466. self.bare_git.symbolic_ref('-m', msg, ref, dst)
  1467. def _InitWorkTree(self):
  1468. dotgit = os.path.join(self.worktree, '.git')
  1469. if not os.path.exists(dotgit):
  1470. os.makedirs(dotgit)
  1471. for name in ['config',
  1472. 'description',
  1473. 'hooks',
  1474. 'info',
  1475. 'logs',
  1476. 'objects',
  1477. 'packed-refs',
  1478. 'refs',
  1479. 'rr-cache',
  1480. 'svn']:
  1481. try:
  1482. src = os.path.join(self.gitdir, name)
  1483. dst = os.path.join(dotgit, name)
  1484. if os.path.islink(dst) or not os.path.exists(dst):
  1485. os.symlink(relpath(src, dst), dst)
  1486. else:
  1487. raise GitError('cannot overwrite a local work tree')
  1488. except OSError, e:
  1489. if e.errno == errno.EPERM:
  1490. raise GitError('filesystem must support symlinks')
  1491. else:
  1492. raise
  1493. _lwrite(os.path.join(dotgit, HEAD), '%s\n' % self.GetRevisionId())
  1494. cmd = ['read-tree', '--reset', '-u']
  1495. cmd.append('-v')
  1496. cmd.append(HEAD)
  1497. if GitCommand(self, cmd).Wait() != 0:
  1498. raise GitError("cannot initialize work tree")
  1499. rr_cache = os.path.join(self.gitdir, 'rr-cache')
  1500. if not os.path.exists(rr_cache):
  1501. os.makedirs(rr_cache)
  1502. self._CopyFiles()
  1503. def _gitdir_path(self, path):
  1504. return os.path.join(self.gitdir, path)
  1505. def _revlist(self, *args, **kw):
  1506. a = []
  1507. a.extend(args)
  1508. a.append('--')
  1509. return self.work_git.rev_list(*a, **kw)
  1510. @property
  1511. def _allrefs(self):
  1512. return self.bare_ref.all
  1513. class _GitGetByExec(object):
  1514. def __init__(self, project, bare):
  1515. self._project = project
  1516. self._bare = bare
  1517. def LsOthers(self):
  1518. p = GitCommand(self._project,
  1519. ['ls-files',
  1520. '-z',
  1521. '--others',
  1522. '--exclude-standard'],
  1523. bare = False,
  1524. capture_stdout = True,
  1525. capture_stderr = True)
  1526. if p.Wait() == 0:
  1527. out = p.stdout
  1528. if out:
  1529. return out[:-1].split("\0")
  1530. return []
  1531. def DiffZ(self, name, *args):
  1532. cmd = [name]
  1533. cmd.append('-z')
  1534. cmd.extend(args)
  1535. p = GitCommand(self._project,
  1536. cmd,
  1537. bare = False,
  1538. capture_stdout = True,
  1539. capture_stderr = True)
  1540. try:
  1541. out = p.process.stdout.read()
  1542. r = {}
  1543. if out:
  1544. out = iter(out[:-1].split('\0'))
  1545. while out:
  1546. try:
  1547. info = out.next()
  1548. path = out.next()
  1549. except StopIteration:
  1550. break
  1551. class _Info(object):
  1552. def __init__(self, path, omode, nmode, oid, nid, state):
  1553. self.path = path
  1554. self.src_path = None
  1555. self.old_mode = omode
  1556. self.new_mode = nmode
  1557. self.old_id = oid
  1558. self.new_id = nid
  1559. if len(state) == 1:
  1560. self.status = state
  1561. self.level = None
  1562. else:
  1563. self.status = state[:1]
  1564. self.level = state[1:]
  1565. while self.level.startswith('0'):
  1566. self.level = self.level[1:]
  1567. info = info[1:].split(' ')
  1568. info =_Info(path, *info)
  1569. if info.status in ('R', 'C'):
  1570. info.src_path = info.path
  1571. info.path = out.next()
  1572. r[info.path] = info
  1573. return r
  1574. finally:
  1575. p.Wait()
  1576. def GetHead(self):
  1577. if self._bare:
  1578. path = os.path.join(self._project.gitdir, HEAD)
  1579. else:
  1580. path = os.path.join(self._project.worktree, '.git', HEAD)
  1581. fd = open(path, 'rb')
  1582. try:
  1583. line = fd.read()
  1584. finally:
  1585. fd.close()
  1586. if line.startswith('ref: '):
  1587. return line[5:-1]
  1588. return line[:-1]
  1589. def SetHead(self, ref, message=None):
  1590. cmdv = []
  1591. if message is not None:
  1592. cmdv.extend(['-m', message])
  1593. cmdv.append(HEAD)
  1594. cmdv.append(ref)
  1595. self.symbolic_ref(*cmdv)
  1596. def DetachHead(self, new, message=None):
  1597. cmdv = ['--no-deref']
  1598. if message is not None:
  1599. cmdv.extend(['-m', message])
  1600. cmdv.append(HEAD)
  1601. cmdv.append(new)
  1602. self.update_ref(*cmdv)
  1603. def UpdateRef(self, name, new, old=None,
  1604. message=None,
  1605. detach=False):
  1606. cmdv = []
  1607. if message is not None:
  1608. cmdv.extend(['-m', message])
  1609. if detach:
  1610. cmdv.append('--no-deref')
  1611. cmdv.append(name)
  1612. cmdv.append(new)
  1613. if old is not None:
  1614. cmdv.append(old)
  1615. self.update_ref(*cmdv)
  1616. def DeleteRef(self, name, old=None):
  1617. if not old:
  1618. old = self.rev_parse(name)
  1619. self.update_ref('-d', name, old)
  1620. self._project.bare_ref.deleted(name)
  1621. def rev_list(self, *args, **kw):
  1622. if 'format' in kw:
  1623. cmdv = ['log', '--pretty=format:%s' % kw['format']]
  1624. else:
  1625. cmdv = ['rev-list']
  1626. cmdv.extend(args)
  1627. p = GitCommand(self._project,
  1628. cmdv,
  1629. bare = self._bare,
  1630. capture_stdout = True,
  1631. capture_stderr = True)
  1632. r = []
  1633. for line in p.process.stdout:
  1634. if line[-1] == '\n':
  1635. line = line[:-1]
  1636. r.append(line)
  1637. if p.Wait() != 0:
  1638. raise GitError('%s rev-list %s: %s' % (
  1639. self._project.name,
  1640. str(args),
  1641. p.stderr))
  1642. return r
  1643. def __getattr__(self, name):
  1644. """Allow arbitrary git commands using pythonic syntax.
  1645. This allows you to do things like:
  1646. git_obj.rev_parse('HEAD')
  1647. Since we don't have a 'rev_parse' method defined, the __getattr__ will
  1648. run. We'll replace the '_' with a '-' and try to run a git command.
  1649. Any other arguments will be passed to the git command.
  1650. Args:
  1651. name: The name of the git command to call. Any '_' characters will
  1652. be replaced with '-'.
  1653. Returns:
  1654. A callable object that will try to call git with the named command.
  1655. """
  1656. name = name.replace('_', '-')
  1657. def runner(*args):
  1658. cmdv = [name]
  1659. cmdv.extend(args)
  1660. p = GitCommand(self._project,
  1661. cmdv,
  1662. bare = self._bare,
  1663. capture_stdout = True,
  1664. capture_stderr = True)
  1665. if p.Wait() != 0:
  1666. raise GitError('%s %s: %s' % (
  1667. self._project.name,
  1668. name,
  1669. p.stderr))
  1670. r = p.stdout
  1671. if r.endswith('\n') and r.index('\n') == len(r) - 1:
  1672. return r[:-1]
  1673. return r
  1674. return runner
  1675. class _PriorSyncFailedError(Exception):
  1676. def __str__(self):
  1677. return 'prior sync failed; rebase still in progress'
  1678. class _DirtyError(Exception):
  1679. def __str__(self):
  1680. return 'contains uncommitted changes'
  1681. class _InfoMessage(object):
  1682. def __init__(self, project, text):
  1683. self.project = project
  1684. self.text = text
  1685. def Print(self, syncbuf):
  1686. syncbuf.out.info('%s/: %s', self.project.relpath, self.text)
  1687. syncbuf.out.nl()
  1688. class _Failure(object):
  1689. def __init__(self, project, why):
  1690. self.project = project
  1691. self.why = why
  1692. def Print(self, syncbuf):
  1693. syncbuf.out.fail('error: %s/: %s',
  1694. self.project.relpath,
  1695. str(self.why))
  1696. syncbuf.out.nl()
  1697. class _Later(object):
  1698. def __init__(self, project, action):
  1699. self.project = project
  1700. self.action = action
  1701. def Run(self, syncbuf):
  1702. out = syncbuf.out
  1703. out.project('project %s/', self.project.relpath)
  1704. out.nl()
  1705. try:
  1706. self.action()
  1707. out.nl()
  1708. return True
  1709. except GitError, e:
  1710. out.nl()
  1711. return False
  1712. class _SyncColoring(Coloring):
  1713. def __init__(self, config):
  1714. Coloring.__init__(self, config, 'reposync')
  1715. self.project = self.printer('header', attr = 'bold')
  1716. self.info = self.printer('info')
  1717. self.fail = self.printer('fail', fg='red')
  1718. class SyncBuffer(object):
  1719. def __init__(self, config, detach_head=False):
  1720. self._messages = []
  1721. self._failures = []
  1722. self._later_queue1 = []
  1723. self._later_queue2 = []
  1724. self.out = _SyncColoring(config)
  1725. self.out.redirect(sys.stderr)
  1726. self.detach_head = detach_head
  1727. self.clean = True
  1728. def info(self, project, fmt, *args):
  1729. self._messages.append(_InfoMessage(project, fmt % args))
  1730. def fail(self, project, err=None):
  1731. self._failures.append(_Failure(project, err))
  1732. self.clean = False
  1733. def later1(self, project, what):
  1734. self._later_queue1.append(_Later(project, what))
  1735. def later2(self, project, what):
  1736. self._later_queue2.append(_Later(project, what))
  1737. def Finish(self):
  1738. self._PrintMessages()
  1739. self._RunLater()
  1740. self._PrintMessages()
  1741. return self.clean
  1742. def _RunLater(self):
  1743. for q in ['_later_queue1', '_later_queue2']:
  1744. if not self._RunQueue(q):
  1745. return
  1746. def _RunQueue(self, queue):
  1747. for m in getattr(self, queue):
  1748. if not m.Run(self):
  1749. self.clean = False
  1750. return False
  1751. setattr(self, queue, [])
  1752. return True
  1753. def _PrintMessages(self):
  1754. for m in self._messages:
  1755. m.Print(self)
  1756. for m in self._failures:
  1757. m.Print(self)
  1758. self._messages = []
  1759. self._failures = []
  1760. class MetaProject(Project):
  1761. """A special project housed under .repo.
  1762. """
  1763. def __init__(self, manifest, name, gitdir, worktree):
  1764. repodir = manifest.repodir
  1765. Project.__init__(self,
  1766. manifest = manifest,
  1767. name = name,
  1768. gitdir = gitdir,
  1769. worktree = worktree,
  1770. remote = RemoteSpec('origin'),
  1771. relpath = '.repo/%s' % name,
  1772. revisionExpr = 'refs/heads/master',
  1773. revisionId = None)
  1774. def PreSync(self):
  1775. if self.Exists:
  1776. cb = self.CurrentBranch
  1777. if cb:
  1778. base = self.GetBranch(cb).merge
  1779. if base:
  1780. self.revisionExpr = base
  1781. self.revisionId = None
  1782. @property
  1783. def LastFetch(self):
  1784. try:
  1785. fh = os.path.join(self.gitdir, 'FETCH_HEAD')
  1786. return os.path.getmtime(fh)
  1787. except OSError:
  1788. return 0
  1789. @property
  1790. def HasChanges(self):
  1791. """Has the remote received new commits not yet checked out?
  1792. """
  1793. if not self.remote or not self.revisionExpr:
  1794. return False
  1795. all = self.bare_ref.all
  1796. revid = self.GetRevisionId(all)
  1797. head = self.work_git.GetHead()
  1798. if head.startswith(R_HEADS):
  1799. try:
  1800. head = all[head]
  1801. except KeyError:
  1802. head = None
  1803. if revid == head:
  1804. return False
  1805. elif self._revlist(not_rev(HEAD), revid):
  1806. return True
  1807. return False