project.py 59 KB

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