project.py 60 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118
  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. self.manifest = manifest
  425. self.name = name
  426. self.remote = remote
  427. self.gitdir = gitdir.replace('\\', '/')
  428. if worktree:
  429. self.worktree = worktree.replace('\\', '/')
  430. else:
  431. self.worktree = None
  432. self.relpath = relpath
  433. self.revisionExpr = revisionExpr
  434. if revisionId is None \
  435. and revisionExpr \
  436. and IsId(revisionExpr):
  437. self.revisionId = revisionExpr
  438. else:
  439. self.revisionId = revisionId
  440. self.snapshots = {}
  441. self.copyfiles = []
  442. self.config = GitConfig.ForRepository(
  443. gitdir = self.gitdir,
  444. defaults = self.manifest.globalConfig)
  445. if self.worktree:
  446. self.work_git = self._GitGetByExec(self, bare=False)
  447. else:
  448. self.work_git = None
  449. self.bare_git = self._GitGetByExec(self, bare=True)
  450. self.bare_ref = GitRefs(gitdir)
  451. # This will be filled in if a project is later identified to be the
  452. # project containing repo hooks.
  453. self.enabled_repo_hooks = []
  454. @property
  455. def Exists(self):
  456. return os.path.isdir(self.gitdir)
  457. @property
  458. def CurrentBranch(self):
  459. """Obtain the name of the currently checked out branch.
  460. The branch name omits the 'refs/heads/' prefix.
  461. None is returned if the project is on a detached HEAD.
  462. """
  463. b = self.work_git.GetHead()
  464. if b.startswith(R_HEADS):
  465. return b[len(R_HEADS):]
  466. return None
  467. def IsRebaseInProgress(self):
  468. w = self.worktree
  469. g = os.path.join(w, '.git')
  470. return os.path.exists(os.path.join(g, 'rebase-apply')) \
  471. or os.path.exists(os.path.join(g, 'rebase-merge')) \
  472. or os.path.exists(os.path.join(w, '.dotest'))
  473. def IsDirty(self, consider_untracked=True):
  474. """Is the working directory modified in some way?
  475. """
  476. self.work_git.update_index('-q',
  477. '--unmerged',
  478. '--ignore-missing',
  479. '--refresh')
  480. if self.work_git.DiffZ('diff-index','-M','--cached',HEAD):
  481. return True
  482. if self.work_git.DiffZ('diff-files'):
  483. return True
  484. if consider_untracked and self.work_git.LsOthers():
  485. return True
  486. return False
  487. _userident_name = None
  488. _userident_email = None
  489. @property
  490. def UserName(self):
  491. """Obtain the user's personal name.
  492. """
  493. if self._userident_name is None:
  494. self._LoadUserIdentity()
  495. return self._userident_name
  496. @property
  497. def UserEmail(self):
  498. """Obtain the user's email address. This is very likely
  499. to be their Gerrit login.
  500. """
  501. if self._userident_email is None:
  502. self._LoadUserIdentity()
  503. return self._userident_email
  504. def _LoadUserIdentity(self):
  505. u = self.bare_git.var('GIT_COMMITTER_IDENT')
  506. m = re.compile("^(.*) <([^>]*)> ").match(u)
  507. if m:
  508. self._userident_name = m.group(1)
  509. self._userident_email = m.group(2)
  510. else:
  511. self._userident_name = ''
  512. self._userident_email = ''
  513. def GetRemote(self, name):
  514. """Get the configuration for a single remote.
  515. """
  516. return self.config.GetRemote(name)
  517. def GetBranch(self, name):
  518. """Get the configuration for a single branch.
  519. """
  520. return self.config.GetBranch(name)
  521. def GetBranches(self):
  522. """Get all existing local branches.
  523. """
  524. current = self.CurrentBranch
  525. all = self._allrefs
  526. heads = {}
  527. pubd = {}
  528. for name, id in all.iteritems():
  529. if name.startswith(R_HEADS):
  530. name = name[len(R_HEADS):]
  531. b = self.GetBranch(name)
  532. b.current = name == current
  533. b.published = None
  534. b.revision = id
  535. heads[name] = b
  536. for name, id in all.iteritems():
  537. if name.startswith(R_PUB):
  538. name = name[len(R_PUB):]
  539. b = heads.get(name)
  540. if b:
  541. b.published = id
  542. return heads
  543. ## Status Display ##
  544. def HasChanges(self):
  545. """Returns true if there are uncommitted changes.
  546. """
  547. self.work_git.update_index('-q',
  548. '--unmerged',
  549. '--ignore-missing',
  550. '--refresh')
  551. if self.IsRebaseInProgress():
  552. return True
  553. if self.work_git.DiffZ('diff-index', '--cached', HEAD):
  554. return True
  555. if self.work_git.DiffZ('diff-files'):
  556. return True
  557. if self.work_git.LsOthers():
  558. return True
  559. return False
  560. def PrintWorkTreeStatus(self, output_redir=None):
  561. """Prints the status of the repository to stdout.
  562. Args:
  563. output: If specified, redirect the output to this object.
  564. """
  565. if not os.path.isdir(self.worktree):
  566. if output_redir == None:
  567. output_redir = sys.stdout
  568. print >>output_redir, ''
  569. print >>output_redir, 'project %s/' % self.relpath
  570. print >>output_redir, ' missing (run "repo sync")'
  571. return
  572. self.work_git.update_index('-q',
  573. '--unmerged',
  574. '--ignore-missing',
  575. '--refresh')
  576. rb = self.IsRebaseInProgress()
  577. di = self.work_git.DiffZ('diff-index', '-M', '--cached', HEAD)
  578. df = self.work_git.DiffZ('diff-files')
  579. do = self.work_git.LsOthers()
  580. if not rb and not di and not df and not do:
  581. return 'CLEAN'
  582. out = StatusColoring(self.config)
  583. if not output_redir == None:
  584. out.redirect(output_redir)
  585. out.project('project %-40s', self.relpath + '/')
  586. branch = self.CurrentBranch
  587. if branch is None:
  588. out.nobranch('(*** NO BRANCH ***)')
  589. else:
  590. out.branch('branch %s', branch)
  591. out.nl()
  592. if rb:
  593. out.important('prior sync failed; rebase still in progress')
  594. out.nl()
  595. paths = list()
  596. paths.extend(di.keys())
  597. paths.extend(df.keys())
  598. paths.extend(do)
  599. paths = list(set(paths))
  600. paths.sort()
  601. for p in paths:
  602. try: i = di[p]
  603. except KeyError: i = None
  604. try: f = df[p]
  605. except KeyError: f = None
  606. if i: i_status = i.status.upper()
  607. else: i_status = '-'
  608. if f: f_status = f.status.lower()
  609. else: f_status = '-'
  610. if i and i.src_path:
  611. line = ' %s%s\t%s => %s (%s%%)' % (i_status, f_status,
  612. i.src_path, p, i.level)
  613. else:
  614. line = ' %s%s\t%s' % (i_status, f_status, p)
  615. if i and not f:
  616. out.added('%s', line)
  617. elif (i and f) or (not i and f):
  618. out.changed('%s', line)
  619. elif not i and not f:
  620. out.untracked('%s', line)
  621. else:
  622. out.write('%s', line)
  623. out.nl()
  624. return 'DIRTY'
  625. def PrintWorkTreeDiff(self):
  626. """Prints the status of the repository to stdout.
  627. """
  628. out = DiffColoring(self.config)
  629. cmd = ['diff']
  630. if out.is_on:
  631. cmd.append('--color')
  632. cmd.append(HEAD)
  633. cmd.append('--')
  634. p = GitCommand(self,
  635. cmd,
  636. capture_stdout = True,
  637. capture_stderr = True)
  638. has_diff = False
  639. for line in p.process.stdout:
  640. if not has_diff:
  641. out.nl()
  642. out.project('project %s/' % self.relpath)
  643. out.nl()
  644. has_diff = True
  645. print line[:-1]
  646. p.Wait()
  647. ## Publish / Upload ##
  648. def WasPublished(self, branch, all=None):
  649. """Was the branch published (uploaded) for code review?
  650. If so, returns the SHA-1 hash of the last published
  651. state for the branch.
  652. """
  653. key = R_PUB + branch
  654. if all is None:
  655. try:
  656. return self.bare_git.rev_parse(key)
  657. except GitError:
  658. return None
  659. else:
  660. try:
  661. return all[key]
  662. except KeyError:
  663. return None
  664. def CleanPublishedCache(self, all=None):
  665. """Prunes any stale published refs.
  666. """
  667. if all is None:
  668. all = self._allrefs
  669. heads = set()
  670. canrm = {}
  671. for name, id in all.iteritems():
  672. if name.startswith(R_HEADS):
  673. heads.add(name)
  674. elif name.startswith(R_PUB):
  675. canrm[name] = id
  676. for name, id in canrm.iteritems():
  677. n = name[len(R_PUB):]
  678. if R_HEADS + n not in heads:
  679. self.bare_git.DeleteRef(name, id)
  680. def GetUploadableBranches(self, selected_branch=None):
  681. """List any branches which can be uploaded for review.
  682. """
  683. heads = {}
  684. pubed = {}
  685. for name, id in self._allrefs.iteritems():
  686. if name.startswith(R_HEADS):
  687. heads[name[len(R_HEADS):]] = id
  688. elif name.startswith(R_PUB):
  689. pubed[name[len(R_PUB):]] = id
  690. ready = []
  691. for branch, id in heads.iteritems():
  692. if branch in pubed and pubed[branch] == id:
  693. continue
  694. if selected_branch and branch != selected_branch:
  695. continue
  696. rb = self.GetUploadableBranch(branch)
  697. if rb:
  698. ready.append(rb)
  699. return ready
  700. def GetUploadableBranch(self, branch_name):
  701. """Get a single uploadable branch, or None.
  702. """
  703. branch = self.GetBranch(branch_name)
  704. base = branch.LocalMerge
  705. if branch.LocalMerge:
  706. rb = ReviewableBranch(self, branch, base)
  707. if rb.commits:
  708. return rb
  709. return None
  710. def UploadForReview(self, branch=None,
  711. people=([],[]),
  712. auto_topic=False):
  713. """Uploads the named branch for code review.
  714. """
  715. if branch is None:
  716. branch = self.CurrentBranch
  717. if branch is None:
  718. raise GitError('not currently on a branch')
  719. branch = self.GetBranch(branch)
  720. if not branch.LocalMerge:
  721. raise GitError('branch %s does not track a remote' % branch.name)
  722. if not branch.remote.review:
  723. raise GitError('remote %s has no review url' % branch.remote.name)
  724. dest_branch = branch.merge
  725. if not dest_branch.startswith(R_HEADS):
  726. dest_branch = R_HEADS + dest_branch
  727. if not branch.remote.projectname:
  728. branch.remote.projectname = self.name
  729. branch.remote.Save()
  730. if branch.remote.ReviewProtocol == 'ssh':
  731. if dest_branch.startswith(R_HEADS):
  732. dest_branch = dest_branch[len(R_HEADS):]
  733. rp = ['gerrit receive-pack']
  734. for e in people[0]:
  735. rp.append('--reviewer=%s' % sq(e))
  736. for e in people[1]:
  737. rp.append('--cc=%s' % sq(e))
  738. ref_spec = '%s:refs/for/%s' % (R_HEADS + branch.name, dest_branch)
  739. if auto_topic:
  740. ref_spec = ref_spec + '/' + branch.name
  741. cmd = ['push']
  742. cmd.append('--receive-pack=%s' % " ".join(rp))
  743. cmd.append(branch.remote.SshReviewUrl(self.UserEmail))
  744. cmd.append(ref_spec)
  745. if GitCommand(self, cmd, bare = True).Wait() != 0:
  746. raise UploadError('Upload failed')
  747. else:
  748. raise UploadError('Unsupported protocol %s' \
  749. % branch.remote.review)
  750. msg = "posted to %s for %s" % (branch.remote.review, dest_branch)
  751. self.bare_git.UpdateRef(R_PUB + branch.name,
  752. R_HEADS + branch.name,
  753. message = msg)
  754. ## Sync ##
  755. def Sync_NetworkHalf(self, quiet=False, is_new=None, current_branch_only=False):
  756. """Perform only the network IO portion of the sync process.
  757. Local working directory/branch state is not affected.
  758. """
  759. if is_new is None:
  760. is_new = not self.Exists
  761. if is_new:
  762. self._InitGitDir()
  763. self._InitRemote()
  764. if is_new:
  765. alt = os.path.join(self.gitdir, 'objects/info/alternates')
  766. try:
  767. fd = open(alt, 'rb')
  768. try:
  769. alt_dir = fd.readline().rstrip()
  770. finally:
  771. fd.close()
  772. except IOError:
  773. alt_dir = None
  774. else:
  775. alt_dir = None
  776. if alt_dir is None and self._ApplyCloneBundle(initial=is_new, quiet=quiet):
  777. is_new = False
  778. if not self._RemoteFetch(initial=is_new, quiet=quiet, alt_dir=alt_dir,
  779. current_branch_only=current_branch_only):
  780. return False
  781. if self.worktree:
  782. self._InitMRef()
  783. else:
  784. self._InitMirrorHead()
  785. try:
  786. os.remove(os.path.join(self.gitdir, 'FETCH_HEAD'))
  787. except OSError:
  788. pass
  789. return True
  790. def PostRepoUpgrade(self):
  791. self._InitHooks()
  792. def _CopyFiles(self):
  793. for file in self.copyfiles:
  794. file._Copy()
  795. def GetRevisionId(self, all=None):
  796. if self.revisionId:
  797. return self.revisionId
  798. rem = self.GetRemote(self.remote.name)
  799. rev = rem.ToLocal(self.revisionExpr)
  800. if all is not None and rev in all:
  801. return all[rev]
  802. try:
  803. return self.bare_git.rev_parse('--verify', '%s^0' % rev)
  804. except GitError:
  805. raise ManifestInvalidRevisionError(
  806. 'revision %s in %s not found' % (self.revisionExpr,
  807. self.name))
  808. def Sync_LocalHalf(self, syncbuf):
  809. """Perform only the local IO portion of the sync process.
  810. Network access is not required.
  811. """
  812. all = self.bare_ref.all
  813. self.CleanPublishedCache(all)
  814. revid = self.GetRevisionId(all)
  815. self._InitWorkTree()
  816. head = self.work_git.GetHead()
  817. if head.startswith(R_HEADS):
  818. branch = head[len(R_HEADS):]
  819. try:
  820. head = all[head]
  821. except KeyError:
  822. head = None
  823. else:
  824. branch = None
  825. if branch is None or syncbuf.detach_head:
  826. # Currently on a detached HEAD. The user is assumed to
  827. # not have any local modifications worth worrying about.
  828. #
  829. if self.IsRebaseInProgress():
  830. syncbuf.fail(self, _PriorSyncFailedError())
  831. return
  832. if head == revid:
  833. # No changes; don't do anything further.
  834. #
  835. return
  836. lost = self._revlist(not_rev(revid), HEAD)
  837. if lost:
  838. syncbuf.info(self, "discarding %d commits", len(lost))
  839. try:
  840. self._Checkout(revid, quiet=True)
  841. except GitError, e:
  842. syncbuf.fail(self, e)
  843. return
  844. self._CopyFiles()
  845. return
  846. if head == revid:
  847. # No changes; don't do anything further.
  848. #
  849. return
  850. branch = self.GetBranch(branch)
  851. if not branch.LocalMerge:
  852. # The current branch has no tracking configuration.
  853. # Jump off it to a detached HEAD.
  854. #
  855. syncbuf.info(self,
  856. "leaving %s; does not track upstream",
  857. branch.name)
  858. try:
  859. self._Checkout(revid, quiet=True)
  860. except GitError, e:
  861. syncbuf.fail(self, e)
  862. return
  863. self._CopyFiles()
  864. return
  865. upstream_gain = self._revlist(not_rev(HEAD), revid)
  866. pub = self.WasPublished(branch.name, all)
  867. if pub:
  868. not_merged = self._revlist(not_rev(revid), pub)
  869. if not_merged:
  870. if upstream_gain:
  871. # The user has published this branch and some of those
  872. # commits are not yet merged upstream. We do not want
  873. # to rewrite the published commits so we punt.
  874. #
  875. syncbuf.fail(self,
  876. "branch %s is published (but not merged) and is now %d commits behind"
  877. % (branch.name, len(upstream_gain)))
  878. return
  879. elif pub == head:
  880. # All published commits are merged, and thus we are a
  881. # strict subset. We can fast-forward safely.
  882. #
  883. def _doff():
  884. self._FastForward(revid)
  885. self._CopyFiles()
  886. syncbuf.later1(self, _doff)
  887. return
  888. # Examine the local commits not in the remote. Find the
  889. # last one attributed to this user, if any.
  890. #
  891. local_changes = self._revlist(not_rev(revid), HEAD, format='%H %ce')
  892. last_mine = None
  893. cnt_mine = 0
  894. for commit in local_changes:
  895. commit_id, committer_email = commit.split(' ', 1)
  896. if committer_email == self.UserEmail:
  897. last_mine = commit_id
  898. cnt_mine += 1
  899. if not upstream_gain and cnt_mine == len(local_changes):
  900. return
  901. if self.IsDirty(consider_untracked=False):
  902. syncbuf.fail(self, _DirtyError())
  903. return
  904. # If the upstream switched on us, warn the user.
  905. #
  906. if branch.merge != self.revisionExpr:
  907. if branch.merge and self.revisionExpr:
  908. syncbuf.info(self,
  909. 'manifest switched %s...%s',
  910. branch.merge,
  911. self.revisionExpr)
  912. elif branch.merge:
  913. syncbuf.info(self,
  914. 'manifest no longer tracks %s',
  915. branch.merge)
  916. if cnt_mine < len(local_changes):
  917. # Upstream rebased. Not everything in HEAD
  918. # was created by this user.
  919. #
  920. syncbuf.info(self,
  921. "discarding %d commits removed from upstream",
  922. len(local_changes) - cnt_mine)
  923. branch.remote = self.GetRemote(self.remote.name)
  924. branch.merge = self.revisionExpr
  925. branch.Save()
  926. if cnt_mine > 0:
  927. def _dorebase():
  928. self._Rebase(upstream = '%s^1' % last_mine, onto = revid)
  929. self._CopyFiles()
  930. syncbuf.later2(self, _dorebase)
  931. elif local_changes:
  932. try:
  933. self._ResetHard(revid)
  934. self._CopyFiles()
  935. except GitError, e:
  936. syncbuf.fail(self, e)
  937. return
  938. else:
  939. def _doff():
  940. self._FastForward(revid)
  941. self._CopyFiles()
  942. syncbuf.later1(self, _doff)
  943. def AddCopyFile(self, src, dest, absdest):
  944. # dest should already be an absolute path, but src is project relative
  945. # make src an absolute path
  946. abssrc = os.path.join(self.worktree, src)
  947. self.copyfiles.append(_CopyFile(src, dest, abssrc, absdest))
  948. def DownloadPatchSet(self, change_id, patch_id):
  949. """Download a single patch set of a single change to FETCH_HEAD.
  950. """
  951. remote = self.GetRemote(self.remote.name)
  952. cmd = ['fetch', remote.name]
  953. cmd.append('refs/changes/%2.2d/%d/%d' \
  954. % (change_id % 100, change_id, patch_id))
  955. cmd.extend(map(lambda x: str(x), remote.fetch))
  956. if GitCommand(self, cmd, bare=True).Wait() != 0:
  957. return None
  958. return DownloadedChange(self,
  959. self.GetRevisionId(),
  960. change_id,
  961. patch_id,
  962. self.bare_git.rev_parse('FETCH_HEAD'))
  963. ## Branch Management ##
  964. def StartBranch(self, name):
  965. """Create a new branch off the manifest's revision.
  966. """
  967. head = self.work_git.GetHead()
  968. if head == (R_HEADS + name):
  969. return True
  970. all = self.bare_ref.all
  971. if (R_HEADS + name) in all:
  972. return GitCommand(self,
  973. ['checkout', name, '--'],
  974. capture_stdout = True,
  975. capture_stderr = True).Wait() == 0
  976. branch = self.GetBranch(name)
  977. branch.remote = self.GetRemote(self.remote.name)
  978. branch.merge = self.revisionExpr
  979. revid = self.GetRevisionId(all)
  980. if head.startswith(R_HEADS):
  981. try:
  982. head = all[head]
  983. except KeyError:
  984. head = None
  985. if revid and head and revid == head:
  986. ref = os.path.join(self.gitdir, R_HEADS + name)
  987. try:
  988. os.makedirs(os.path.dirname(ref))
  989. except OSError:
  990. pass
  991. _lwrite(ref, '%s\n' % revid)
  992. _lwrite(os.path.join(self.worktree, '.git', HEAD),
  993. 'ref: %s%s\n' % (R_HEADS, name))
  994. branch.Save()
  995. return True
  996. if GitCommand(self,
  997. ['checkout', '-b', branch.name, revid],
  998. capture_stdout = True,
  999. capture_stderr = True).Wait() == 0:
  1000. branch.Save()
  1001. return True
  1002. return False
  1003. def CheckoutBranch(self, name):
  1004. """Checkout a local topic branch.
  1005. Args:
  1006. name: The name of the branch to checkout.
  1007. Returns:
  1008. True if the checkout succeeded; False if it didn't; None if the branch
  1009. didn't exist.
  1010. """
  1011. rev = R_HEADS + name
  1012. head = self.work_git.GetHead()
  1013. if head == rev:
  1014. # Already on the branch
  1015. #
  1016. return True
  1017. all = self.bare_ref.all
  1018. try:
  1019. revid = all[rev]
  1020. except KeyError:
  1021. # Branch does not exist in this project
  1022. #
  1023. return None
  1024. if head.startswith(R_HEADS):
  1025. try:
  1026. head = all[head]
  1027. except KeyError:
  1028. head = None
  1029. if head == revid:
  1030. # Same revision; just update HEAD to point to the new
  1031. # target branch, but otherwise take no other action.
  1032. #
  1033. _lwrite(os.path.join(self.worktree, '.git', HEAD),
  1034. 'ref: %s%s\n' % (R_HEADS, name))
  1035. return True
  1036. return GitCommand(self,
  1037. ['checkout', name, '--'],
  1038. capture_stdout = True,
  1039. capture_stderr = True).Wait() == 0
  1040. def AbandonBranch(self, name):
  1041. """Destroy a local topic branch.
  1042. Args:
  1043. name: The name of the branch to abandon.
  1044. Returns:
  1045. True if the abandon succeeded; False if it didn't; None if the branch
  1046. didn't exist.
  1047. """
  1048. rev = R_HEADS + name
  1049. all = self.bare_ref.all
  1050. if rev not in all:
  1051. # Doesn't exist
  1052. return None
  1053. head = self.work_git.GetHead()
  1054. if head == rev:
  1055. # We can't destroy the branch while we are sitting
  1056. # on it. Switch to a detached HEAD.
  1057. #
  1058. head = all[head]
  1059. revid = self.GetRevisionId(all)
  1060. if head == revid:
  1061. _lwrite(os.path.join(self.worktree, '.git', HEAD),
  1062. '%s\n' % revid)
  1063. else:
  1064. self._Checkout(revid, quiet=True)
  1065. return GitCommand(self,
  1066. ['branch', '-D', name],
  1067. capture_stdout = True,
  1068. capture_stderr = True).Wait() == 0
  1069. def PruneHeads(self):
  1070. """Prune any topic branches already merged into upstream.
  1071. """
  1072. cb = self.CurrentBranch
  1073. kill = []
  1074. left = self._allrefs
  1075. for name in left.keys():
  1076. if name.startswith(R_HEADS):
  1077. name = name[len(R_HEADS):]
  1078. if cb is None or name != cb:
  1079. kill.append(name)
  1080. rev = self.GetRevisionId(left)
  1081. if cb is not None \
  1082. and not self._revlist(HEAD + '...' + rev) \
  1083. and not self.IsDirty(consider_untracked = False):
  1084. self.work_git.DetachHead(HEAD)
  1085. kill.append(cb)
  1086. if kill:
  1087. old = self.bare_git.GetHead()
  1088. if old is None:
  1089. old = 'refs/heads/please_never_use_this_as_a_branch_name'
  1090. try:
  1091. self.bare_git.DetachHead(rev)
  1092. b = ['branch', '-d']
  1093. b.extend(kill)
  1094. b = GitCommand(self, b, bare=True,
  1095. capture_stdout=True,
  1096. capture_stderr=True)
  1097. b.Wait()
  1098. finally:
  1099. self.bare_git.SetHead(old)
  1100. left = self._allrefs
  1101. for branch in kill:
  1102. if (R_HEADS + branch) not in left:
  1103. self.CleanPublishedCache()
  1104. break
  1105. if cb and cb not in kill:
  1106. kill.append(cb)
  1107. kill.sort()
  1108. kept = []
  1109. for branch in kill:
  1110. if (R_HEADS + branch) in left:
  1111. branch = self.GetBranch(branch)
  1112. base = branch.LocalMerge
  1113. if not base:
  1114. base = rev
  1115. kept.append(ReviewableBranch(self, branch, base))
  1116. return kept
  1117. ## Direct Git Commands ##
  1118. def _RemoteFetch(self, name=None,
  1119. current_branch_only=False,
  1120. initial=False,
  1121. quiet=False,
  1122. alt_dir=None):
  1123. is_sha1 = False
  1124. tag_name = None
  1125. if current_branch_only:
  1126. if ID_RE.match(self.revisionExpr) is not None:
  1127. is_sha1 = True
  1128. elif self.revisionExpr.startswith(R_TAGS):
  1129. # this is a tag and its sha1 value should never change
  1130. tag_name = self.revisionExpr[len(R_TAGS):]
  1131. if is_sha1 or tag_name is not None:
  1132. try:
  1133. self.GetRevisionId()
  1134. return True
  1135. except ManifestInvalidRevisionError:
  1136. # There is no such persistent revision. We have to fetch it.
  1137. pass
  1138. if not name:
  1139. name = self.remote.name
  1140. ssh_proxy = False
  1141. remote = self.GetRemote(name)
  1142. if remote.PreConnectFetch():
  1143. ssh_proxy = True
  1144. if initial:
  1145. if alt_dir and 'objects' == os.path.basename(alt_dir):
  1146. ref_dir = os.path.dirname(alt_dir)
  1147. packed_refs = os.path.join(self.gitdir, 'packed-refs')
  1148. remote = self.GetRemote(name)
  1149. all = self.bare_ref.all
  1150. ids = set(all.values())
  1151. tmp = set()
  1152. for r, id in GitRefs(ref_dir).all.iteritems():
  1153. if r not in all:
  1154. if r.startswith(R_TAGS) or remote.WritesTo(r):
  1155. all[r] = id
  1156. ids.add(id)
  1157. continue
  1158. if id in ids:
  1159. continue
  1160. r = 'refs/_alt/%s' % id
  1161. all[r] = id
  1162. ids.add(id)
  1163. tmp.add(r)
  1164. ref_names = list(all.keys())
  1165. ref_names.sort()
  1166. tmp_packed = ''
  1167. old_packed = ''
  1168. for r in ref_names:
  1169. line = '%s %s\n' % (all[r], r)
  1170. tmp_packed += line
  1171. if r not in tmp:
  1172. old_packed += line
  1173. _lwrite(packed_refs, tmp_packed)
  1174. else:
  1175. alt_dir = None
  1176. cmd = ['fetch']
  1177. # The --depth option only affects the initial fetch; after that we'll do
  1178. # full fetches of changes.
  1179. depth = self.manifest.manifestProject.config.GetString('repo.depth')
  1180. if depth and initial:
  1181. cmd.append('--depth=%s' % depth)
  1182. if quiet:
  1183. cmd.append('--quiet')
  1184. if not self.worktree:
  1185. cmd.append('--update-head-ok')
  1186. cmd.append(name)
  1187. if not current_branch_only or is_sha1:
  1188. # Fetch whole repo
  1189. cmd.append('--tags')
  1190. cmd.append((u'+refs/heads/*:') + remote.ToLocal('refs/heads/*'))
  1191. elif tag_name is not None:
  1192. cmd.append('tag')
  1193. cmd.append(tag_name)
  1194. else:
  1195. branch = self.revisionExpr
  1196. if branch.startswith(R_HEADS):
  1197. branch = branch[len(R_HEADS):]
  1198. cmd.append((u'+refs/heads/%s:' % branch) + remote.ToLocal('refs/heads/%s' % branch))
  1199. ok = False
  1200. for i in range(2):
  1201. if GitCommand(self, cmd, bare=True, ssh_proxy=ssh_proxy).Wait() == 0:
  1202. ok = True
  1203. break
  1204. time.sleep(random.randint(30, 45))
  1205. if initial:
  1206. if alt_dir:
  1207. if old_packed != '':
  1208. _lwrite(packed_refs, old_packed)
  1209. else:
  1210. os.remove(packed_refs)
  1211. self.bare_git.pack_refs('--all', '--prune')
  1212. return ok
  1213. def _ApplyCloneBundle(self, initial=False, quiet=False):
  1214. if initial and self.manifest.manifestProject.config.GetString('repo.depth'):
  1215. return False
  1216. remote = self.GetRemote(self.remote.name)
  1217. bundle_url = remote.url + '/clone.bundle'
  1218. bundle_url = GitConfig.ForUser().UrlInsteadOf(bundle_url)
  1219. if GetSchemeFromUrl(bundle_url) not in ('http', 'https'):
  1220. return False
  1221. bundle_dst = os.path.join(self.gitdir, 'clone.bundle')
  1222. bundle_tmp = os.path.join(self.gitdir, 'clone.bundle.tmp')
  1223. exist_dst = os.path.exists(bundle_dst)
  1224. exist_tmp = os.path.exists(bundle_tmp)
  1225. if not initial and not exist_dst and not exist_tmp:
  1226. return False
  1227. if not exist_dst:
  1228. exist_dst = self._FetchBundle(bundle_url, bundle_tmp, bundle_dst, quiet)
  1229. if not exist_dst:
  1230. return False
  1231. cmd = ['fetch']
  1232. if quiet:
  1233. cmd.append('--quiet')
  1234. if not self.worktree:
  1235. cmd.append('--update-head-ok')
  1236. cmd.append(bundle_dst)
  1237. for f in remote.fetch:
  1238. cmd.append(str(f))
  1239. cmd.append('refs/tags/*:refs/tags/*')
  1240. ok = GitCommand(self, cmd, bare=True).Wait() == 0
  1241. if os.path.exists(bundle_dst):
  1242. os.remove(bundle_dst)
  1243. if os.path.exists(bundle_tmp):
  1244. os.remove(bundle_tmp)
  1245. return ok
  1246. def _FetchBundle(self, srcUrl, tmpPath, dstPath, quiet):
  1247. keep = True
  1248. done = False
  1249. dest = open(tmpPath, 'a+b')
  1250. try:
  1251. dest.seek(0, SEEK_END)
  1252. pos = dest.tell()
  1253. _urllib_lock.acquire()
  1254. try:
  1255. req = urllib2.Request(srcUrl)
  1256. if pos > 0:
  1257. req.add_header('Range', 'bytes=%d-' % pos)
  1258. try:
  1259. r = urllib2.urlopen(req)
  1260. except urllib2.HTTPError, e:
  1261. def _content_type():
  1262. try:
  1263. return e.info()['content-type']
  1264. except:
  1265. return None
  1266. if e.code == 404:
  1267. keep = False
  1268. return False
  1269. elif _content_type() == 'text/plain':
  1270. try:
  1271. msg = e.read()
  1272. if len(msg) > 0 and msg[-1] == '\n':
  1273. msg = msg[0:-1]
  1274. msg = ' (%s)' % msg
  1275. except:
  1276. msg = ''
  1277. else:
  1278. try:
  1279. from BaseHTTPServer import BaseHTTPRequestHandler
  1280. res = BaseHTTPRequestHandler.responses[e.code]
  1281. msg = ' (%s: %s)' % (res[0], res[1])
  1282. except:
  1283. msg = ''
  1284. raise DownloadError('HTTP %s%s' % (e.code, msg))
  1285. except urllib2.URLError, e:
  1286. raise DownloadError('%s: %s ' % (req.get_host(), str(e)))
  1287. finally:
  1288. _urllib_lock.release()
  1289. p = None
  1290. try:
  1291. size = r.headers['content-length']
  1292. unit = 1 << 10
  1293. if size and not quiet:
  1294. if size > 1024 * 1.3:
  1295. unit = 1 << 20
  1296. desc = 'MB'
  1297. else:
  1298. desc = 'KB'
  1299. p = Progress(
  1300. 'Downloading %s' % self.relpath,
  1301. int(size) / unit,
  1302. units=desc)
  1303. if pos > 0:
  1304. p.update(pos / unit)
  1305. s = 0
  1306. while True:
  1307. d = r.read(8192)
  1308. if d == '':
  1309. done = True
  1310. return True
  1311. dest.write(d)
  1312. if p:
  1313. s += len(d)
  1314. if s >= unit:
  1315. p.update(s / unit)
  1316. s = s % unit
  1317. if p:
  1318. if s >= unit:
  1319. p.update(s / unit)
  1320. else:
  1321. p.update(1)
  1322. finally:
  1323. r.close()
  1324. if p:
  1325. p.end()
  1326. finally:
  1327. dest.close()
  1328. if os.path.exists(dstPath):
  1329. os.remove(dstPath)
  1330. if done:
  1331. os.rename(tmpPath, dstPath)
  1332. elif not keep:
  1333. os.remove(tmpPath)
  1334. def _Checkout(self, rev, quiet=False):
  1335. cmd = ['checkout']
  1336. if quiet:
  1337. cmd.append('-q')
  1338. cmd.append(rev)
  1339. cmd.append('--')
  1340. if GitCommand(self, cmd).Wait() != 0:
  1341. if self._allrefs:
  1342. raise GitError('%s checkout %s ' % (self.name, rev))
  1343. def _ResetHard(self, rev, quiet=True):
  1344. cmd = ['reset', '--hard']
  1345. if quiet:
  1346. cmd.append('-q')
  1347. cmd.append(rev)
  1348. if GitCommand(self, cmd).Wait() != 0:
  1349. raise GitError('%s reset --hard %s ' % (self.name, rev))
  1350. def _Rebase(self, upstream, onto = None):
  1351. cmd = ['rebase']
  1352. if onto is not None:
  1353. cmd.extend(['--onto', onto])
  1354. cmd.append(upstream)
  1355. if GitCommand(self, cmd).Wait() != 0:
  1356. raise GitError('%s rebase %s ' % (self.name, upstream))
  1357. def _FastForward(self, head):
  1358. cmd = ['merge', head]
  1359. if GitCommand(self, cmd).Wait() != 0:
  1360. raise GitError('%s merge %s ' % (self.name, head))
  1361. def _InitGitDir(self):
  1362. if not os.path.exists(self.gitdir):
  1363. os.makedirs(self.gitdir)
  1364. self.bare_git.init()
  1365. mp = self.manifest.manifestProject
  1366. ref_dir = mp.config.GetString('repo.reference')
  1367. if ref_dir:
  1368. mirror_git = os.path.join(ref_dir, self.name + '.git')
  1369. repo_git = os.path.join(ref_dir, '.repo', 'projects',
  1370. self.relpath + '.git')
  1371. if os.path.exists(mirror_git):
  1372. ref_dir = mirror_git
  1373. elif os.path.exists(repo_git):
  1374. ref_dir = repo_git
  1375. else:
  1376. ref_dir = None
  1377. if ref_dir:
  1378. _lwrite(os.path.join(self.gitdir, 'objects/info/alternates'),
  1379. os.path.join(ref_dir, 'objects') + '\n')
  1380. if self.manifest.IsMirror:
  1381. self.config.SetString('core.bare', 'true')
  1382. else:
  1383. self.config.SetString('core.bare', None)
  1384. hooks = self._gitdir_path('hooks')
  1385. try:
  1386. to_rm = os.listdir(hooks)
  1387. except OSError:
  1388. to_rm = []
  1389. for old_hook in to_rm:
  1390. os.remove(os.path.join(hooks, old_hook))
  1391. self._InitHooks()
  1392. m = self.manifest.manifestProject.config
  1393. for key in ['user.name', 'user.email']:
  1394. if m.Has(key, include_defaults = False):
  1395. self.config.SetString(key, m.GetString(key))
  1396. def _InitHooks(self):
  1397. hooks = self._gitdir_path('hooks')
  1398. if not os.path.exists(hooks):
  1399. os.makedirs(hooks)
  1400. for stock_hook in _ProjectHooks():
  1401. name = os.path.basename(stock_hook)
  1402. if name in ('commit-msg',) and not self.remote.review \
  1403. and not self is self.manifest.manifestProject:
  1404. # Don't install a Gerrit Code Review hook if this
  1405. # project does not appear to use it for reviews.
  1406. #
  1407. # Since the manifest project is one of those, but also
  1408. # managed through gerrit, it's excluded
  1409. continue
  1410. dst = os.path.join(hooks, name)
  1411. if os.path.islink(dst):
  1412. continue
  1413. if os.path.exists(dst):
  1414. if filecmp.cmp(stock_hook, dst, shallow=False):
  1415. os.remove(dst)
  1416. else:
  1417. _error("%s: Not replacing %s hook", self.relpath, name)
  1418. continue
  1419. try:
  1420. os.symlink(relpath(stock_hook, dst), dst)
  1421. except OSError, e:
  1422. if e.errno == errno.EPERM:
  1423. raise GitError('filesystem must support symlinks')
  1424. else:
  1425. raise
  1426. def _InitRemote(self):
  1427. if self.remote.url:
  1428. remote = self.GetRemote(self.remote.name)
  1429. remote.url = self.remote.url
  1430. remote.review = self.remote.review
  1431. remote.projectname = self.name
  1432. if self.worktree:
  1433. remote.ResetFetch(mirror=False)
  1434. else:
  1435. remote.ResetFetch(mirror=True)
  1436. remote.Save()
  1437. def _InitMRef(self):
  1438. if self.manifest.branch:
  1439. self._InitAnyMRef(R_M + self.manifest.branch)
  1440. def _InitMirrorHead(self):
  1441. self._InitAnyMRef(HEAD)
  1442. def _InitAnyMRef(self, ref):
  1443. cur = self.bare_ref.symref(ref)
  1444. if self.revisionId:
  1445. if cur != '' or self.bare_ref.get(ref) != self.revisionId:
  1446. msg = 'manifest set to %s' % self.revisionId
  1447. dst = self.revisionId + '^0'
  1448. self.bare_git.UpdateRef(ref, dst, message = msg, detach = True)
  1449. else:
  1450. remote = self.GetRemote(self.remote.name)
  1451. dst = remote.ToLocal(self.revisionExpr)
  1452. if cur != dst:
  1453. msg = 'manifest set to %s' % self.revisionExpr
  1454. self.bare_git.symbolic_ref('-m', msg, ref, dst)
  1455. def _InitWorkTree(self):
  1456. dotgit = os.path.join(self.worktree, '.git')
  1457. if not os.path.exists(dotgit):
  1458. os.makedirs(dotgit)
  1459. for name in ['config',
  1460. 'description',
  1461. 'hooks',
  1462. 'info',
  1463. 'logs',
  1464. 'objects',
  1465. 'packed-refs',
  1466. 'refs',
  1467. 'rr-cache',
  1468. 'svn']:
  1469. try:
  1470. src = os.path.join(self.gitdir, name)
  1471. dst = os.path.join(dotgit, name)
  1472. if os.path.islink(dst) or not os.path.exists(dst):
  1473. os.symlink(relpath(src, dst), dst)
  1474. else:
  1475. raise GitError('cannot overwrite a local work tree')
  1476. except OSError, e:
  1477. if e.errno == errno.EPERM:
  1478. raise GitError('filesystem must support symlinks')
  1479. else:
  1480. raise
  1481. _lwrite(os.path.join(dotgit, HEAD), '%s\n' % self.GetRevisionId())
  1482. cmd = ['read-tree', '--reset', '-u']
  1483. cmd.append('-v')
  1484. cmd.append(HEAD)
  1485. if GitCommand(self, cmd).Wait() != 0:
  1486. raise GitError("cannot initialize work tree")
  1487. rr_cache = os.path.join(self.gitdir, 'rr-cache')
  1488. if not os.path.exists(rr_cache):
  1489. os.makedirs(rr_cache)
  1490. self._CopyFiles()
  1491. def _gitdir_path(self, path):
  1492. return os.path.join(self.gitdir, path)
  1493. def _revlist(self, *args, **kw):
  1494. a = []
  1495. a.extend(args)
  1496. a.append('--')
  1497. return self.work_git.rev_list(*a, **kw)
  1498. @property
  1499. def _allrefs(self):
  1500. return self.bare_ref.all
  1501. class _GitGetByExec(object):
  1502. def __init__(self, project, bare):
  1503. self._project = project
  1504. self._bare = bare
  1505. def LsOthers(self):
  1506. p = GitCommand(self._project,
  1507. ['ls-files',
  1508. '-z',
  1509. '--others',
  1510. '--exclude-standard'],
  1511. bare = False,
  1512. capture_stdout = True,
  1513. capture_stderr = True)
  1514. if p.Wait() == 0:
  1515. out = p.stdout
  1516. if out:
  1517. return out[:-1].split("\0")
  1518. return []
  1519. def DiffZ(self, name, *args):
  1520. cmd = [name]
  1521. cmd.append('-z')
  1522. cmd.extend(args)
  1523. p = GitCommand(self._project,
  1524. cmd,
  1525. bare = False,
  1526. capture_stdout = True,
  1527. capture_stderr = True)
  1528. try:
  1529. out = p.process.stdout.read()
  1530. r = {}
  1531. if out:
  1532. out = iter(out[:-1].split('\0'))
  1533. while out:
  1534. try:
  1535. info = out.next()
  1536. path = out.next()
  1537. except StopIteration:
  1538. break
  1539. class _Info(object):
  1540. def __init__(self, path, omode, nmode, oid, nid, state):
  1541. self.path = path
  1542. self.src_path = None
  1543. self.old_mode = omode
  1544. self.new_mode = nmode
  1545. self.old_id = oid
  1546. self.new_id = nid
  1547. if len(state) == 1:
  1548. self.status = state
  1549. self.level = None
  1550. else:
  1551. self.status = state[:1]
  1552. self.level = state[1:]
  1553. while self.level.startswith('0'):
  1554. self.level = self.level[1:]
  1555. info = info[1:].split(' ')
  1556. info =_Info(path, *info)
  1557. if info.status in ('R', 'C'):
  1558. info.src_path = info.path
  1559. info.path = out.next()
  1560. r[info.path] = info
  1561. return r
  1562. finally:
  1563. p.Wait()
  1564. def GetHead(self):
  1565. if self._bare:
  1566. path = os.path.join(self._project.gitdir, HEAD)
  1567. else:
  1568. path = os.path.join(self._project.worktree, '.git', HEAD)
  1569. fd = open(path, 'rb')
  1570. try:
  1571. line = fd.read()
  1572. finally:
  1573. fd.close()
  1574. if line.startswith('ref: '):
  1575. return line[5:-1]
  1576. return line[:-1]
  1577. def SetHead(self, ref, message=None):
  1578. cmdv = []
  1579. if message is not None:
  1580. cmdv.extend(['-m', message])
  1581. cmdv.append(HEAD)
  1582. cmdv.append(ref)
  1583. self.symbolic_ref(*cmdv)
  1584. def DetachHead(self, new, message=None):
  1585. cmdv = ['--no-deref']
  1586. if message is not None:
  1587. cmdv.extend(['-m', message])
  1588. cmdv.append(HEAD)
  1589. cmdv.append(new)
  1590. self.update_ref(*cmdv)
  1591. def UpdateRef(self, name, new, old=None,
  1592. message=None,
  1593. detach=False):
  1594. cmdv = []
  1595. if message is not None:
  1596. cmdv.extend(['-m', message])
  1597. if detach:
  1598. cmdv.append('--no-deref')
  1599. cmdv.append(name)
  1600. cmdv.append(new)
  1601. if old is not None:
  1602. cmdv.append(old)
  1603. self.update_ref(*cmdv)
  1604. def DeleteRef(self, name, old=None):
  1605. if not old:
  1606. old = self.rev_parse(name)
  1607. self.update_ref('-d', name, old)
  1608. self._project.bare_ref.deleted(name)
  1609. def rev_list(self, *args, **kw):
  1610. if 'format' in kw:
  1611. cmdv = ['log', '--pretty=format:%s' % kw['format']]
  1612. else:
  1613. cmdv = ['rev-list']
  1614. cmdv.extend(args)
  1615. p = GitCommand(self._project,
  1616. cmdv,
  1617. bare = self._bare,
  1618. capture_stdout = True,
  1619. capture_stderr = True)
  1620. r = []
  1621. for line in p.process.stdout:
  1622. if line[-1] == '\n':
  1623. line = line[:-1]
  1624. r.append(line)
  1625. if p.Wait() != 0:
  1626. raise GitError('%s rev-list %s: %s' % (
  1627. self._project.name,
  1628. str(args),
  1629. p.stderr))
  1630. return r
  1631. def __getattr__(self, name):
  1632. """Allow arbitrary git commands using pythonic syntax.
  1633. This allows you to do things like:
  1634. git_obj.rev_parse('HEAD')
  1635. Since we don't have a 'rev_parse' method defined, the __getattr__ will
  1636. run. We'll replace the '_' with a '-' and try to run a git command.
  1637. Any other arguments will be passed to the git command.
  1638. Args:
  1639. name: The name of the git command to call. Any '_' characters will
  1640. be replaced with '-'.
  1641. Returns:
  1642. A callable object that will try to call git with the named command.
  1643. """
  1644. name = name.replace('_', '-')
  1645. def runner(*args):
  1646. cmdv = [name]
  1647. cmdv.extend(args)
  1648. p = GitCommand(self._project,
  1649. cmdv,
  1650. bare = self._bare,
  1651. capture_stdout = True,
  1652. capture_stderr = True)
  1653. if p.Wait() != 0:
  1654. raise GitError('%s %s: %s' % (
  1655. self._project.name,
  1656. name,
  1657. p.stderr))
  1658. r = p.stdout
  1659. if r.endswith('\n') and r.index('\n') == len(r) - 1:
  1660. return r[:-1]
  1661. return r
  1662. return runner
  1663. class _PriorSyncFailedError(Exception):
  1664. def __str__(self):
  1665. return 'prior sync failed; rebase still in progress'
  1666. class _DirtyError(Exception):
  1667. def __str__(self):
  1668. return 'contains uncommitted changes'
  1669. class _InfoMessage(object):
  1670. def __init__(self, project, text):
  1671. self.project = project
  1672. self.text = text
  1673. def Print(self, syncbuf):
  1674. syncbuf.out.info('%s/: %s', self.project.relpath, self.text)
  1675. syncbuf.out.nl()
  1676. class _Failure(object):
  1677. def __init__(self, project, why):
  1678. self.project = project
  1679. self.why = why
  1680. def Print(self, syncbuf):
  1681. syncbuf.out.fail('error: %s/: %s',
  1682. self.project.relpath,
  1683. str(self.why))
  1684. syncbuf.out.nl()
  1685. class _Later(object):
  1686. def __init__(self, project, action):
  1687. self.project = project
  1688. self.action = action
  1689. def Run(self, syncbuf):
  1690. out = syncbuf.out
  1691. out.project('project %s/', self.project.relpath)
  1692. out.nl()
  1693. try:
  1694. self.action()
  1695. out.nl()
  1696. return True
  1697. except GitError, e:
  1698. out.nl()
  1699. return False
  1700. class _SyncColoring(Coloring):
  1701. def __init__(self, config):
  1702. Coloring.__init__(self, config, 'reposync')
  1703. self.project = self.printer('header', attr = 'bold')
  1704. self.info = self.printer('info')
  1705. self.fail = self.printer('fail', fg='red')
  1706. class SyncBuffer(object):
  1707. def __init__(self, config, detach_head=False):
  1708. self._messages = []
  1709. self._failures = []
  1710. self._later_queue1 = []
  1711. self._later_queue2 = []
  1712. self.out = _SyncColoring(config)
  1713. self.out.redirect(sys.stderr)
  1714. self.detach_head = detach_head
  1715. self.clean = True
  1716. def info(self, project, fmt, *args):
  1717. self._messages.append(_InfoMessage(project, fmt % args))
  1718. def fail(self, project, err=None):
  1719. self._failures.append(_Failure(project, err))
  1720. self.clean = False
  1721. def later1(self, project, what):
  1722. self._later_queue1.append(_Later(project, what))
  1723. def later2(self, project, what):
  1724. self._later_queue2.append(_Later(project, what))
  1725. def Finish(self):
  1726. self._PrintMessages()
  1727. self._RunLater()
  1728. self._PrintMessages()
  1729. return self.clean
  1730. def _RunLater(self):
  1731. for q in ['_later_queue1', '_later_queue2']:
  1732. if not self._RunQueue(q):
  1733. return
  1734. def _RunQueue(self, queue):
  1735. for m in getattr(self, queue):
  1736. if not m.Run(self):
  1737. self.clean = False
  1738. return False
  1739. setattr(self, queue, [])
  1740. return True
  1741. def _PrintMessages(self):
  1742. for m in self._messages:
  1743. m.Print(self)
  1744. for m in self._failures:
  1745. m.Print(self)
  1746. self._messages = []
  1747. self._failures = []
  1748. class MetaProject(Project):
  1749. """A special project housed under .repo.
  1750. """
  1751. def __init__(self, manifest, name, gitdir, worktree):
  1752. repodir = manifest.repodir
  1753. Project.__init__(self,
  1754. manifest = manifest,
  1755. name = name,
  1756. gitdir = gitdir,
  1757. worktree = worktree,
  1758. remote = RemoteSpec('origin'),
  1759. relpath = '.repo/%s' % name,
  1760. revisionExpr = 'refs/heads/master',
  1761. revisionId = None)
  1762. def PreSync(self):
  1763. if self.Exists:
  1764. cb = self.CurrentBranch
  1765. if cb:
  1766. base = self.GetBranch(cb).merge
  1767. if base:
  1768. self.revisionExpr = base
  1769. self.revisionId = None
  1770. @property
  1771. def LastFetch(self):
  1772. try:
  1773. fh = os.path.join(self.gitdir, 'FETCH_HEAD')
  1774. return os.path.getmtime(fh)
  1775. except OSError:
  1776. return 0
  1777. @property
  1778. def HasChanges(self):
  1779. """Has the remote received new commits not yet checked out?
  1780. """
  1781. if not self.remote or not self.revisionExpr:
  1782. return False
  1783. all = self.bare_ref.all
  1784. revid = self.GetRevisionId(all)
  1785. head = self.work_git.GetHead()
  1786. if head.startswith(R_HEADS):
  1787. try:
  1788. head = all[head]
  1789. except KeyError:
  1790. head = None
  1791. if revid == head:
  1792. return False
  1793. elif self._revlist(not_rev(HEAD), revid):
  1794. return True
  1795. return False