project.py 59 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099
  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
  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):
  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. return False
  780. #Check that the requested ref was found after fetch
  781. #
  782. try:
  783. self.GetRevisionId()
  784. except ManifestInvalidRevisionError:
  785. # if the ref is a tag. We can try fetching
  786. # the tag manually as a last resort
  787. #
  788. rev = self.revisionExpr
  789. if rev.startswith(R_TAGS):
  790. self._RemoteFetch(None, rev[len(R_TAGS):], quiet=quiet)
  791. if self.worktree:
  792. self._InitMRef()
  793. else:
  794. self._InitMirrorHead()
  795. try:
  796. os.remove(os.path.join(self.gitdir, 'FETCH_HEAD'))
  797. except OSError:
  798. pass
  799. return True
  800. def PostRepoUpgrade(self):
  801. self._InitHooks()
  802. def _CopyFiles(self):
  803. for file in self.copyfiles:
  804. file._Copy()
  805. def GetRevisionId(self, all=None):
  806. if self.revisionId:
  807. return self.revisionId
  808. rem = self.GetRemote(self.remote.name)
  809. rev = rem.ToLocal(self.revisionExpr)
  810. if all is not None and rev in all:
  811. return all[rev]
  812. try:
  813. return self.bare_git.rev_parse('--verify', '%s^0' % rev)
  814. except GitError:
  815. raise ManifestInvalidRevisionError(
  816. 'revision %s in %s not found' % (self.revisionExpr,
  817. self.name))
  818. def Sync_LocalHalf(self, syncbuf):
  819. """Perform only the local IO portion of the sync process.
  820. Network access is not required.
  821. """
  822. all = self.bare_ref.all
  823. self.CleanPublishedCache(all)
  824. revid = self.GetRevisionId(all)
  825. self._InitWorkTree()
  826. head = self.work_git.GetHead()
  827. if head.startswith(R_HEADS):
  828. branch = head[len(R_HEADS):]
  829. try:
  830. head = all[head]
  831. except KeyError:
  832. head = None
  833. else:
  834. branch = None
  835. if branch is None or syncbuf.detach_head:
  836. # Currently on a detached HEAD. The user is assumed to
  837. # not have any local modifications worth worrying about.
  838. #
  839. if self.IsRebaseInProgress():
  840. syncbuf.fail(self, _PriorSyncFailedError())
  841. return
  842. if head == revid:
  843. # No changes; don't do anything further.
  844. #
  845. return
  846. lost = self._revlist(not_rev(revid), HEAD)
  847. if lost:
  848. syncbuf.info(self, "discarding %d commits", len(lost))
  849. try:
  850. self._Checkout(revid, quiet=True)
  851. except GitError, e:
  852. syncbuf.fail(self, e)
  853. return
  854. self._CopyFiles()
  855. return
  856. if head == revid:
  857. # No changes; don't do anything further.
  858. #
  859. return
  860. branch = self.GetBranch(branch)
  861. if not branch.LocalMerge:
  862. # The current branch has no tracking configuration.
  863. # Jump off it to a deatched HEAD.
  864. #
  865. syncbuf.info(self,
  866. "leaving %s; does not track upstream",
  867. branch.name)
  868. try:
  869. self._Checkout(revid, quiet=True)
  870. except GitError, e:
  871. syncbuf.fail(self, e)
  872. return
  873. self._CopyFiles()
  874. return
  875. upstream_gain = self._revlist(not_rev(HEAD), revid)
  876. pub = self.WasPublished(branch.name, all)
  877. if pub:
  878. not_merged = self._revlist(not_rev(revid), pub)
  879. if not_merged:
  880. if upstream_gain:
  881. # The user has published this branch and some of those
  882. # commits are not yet merged upstream. We do not want
  883. # to rewrite the published commits so we punt.
  884. #
  885. syncbuf.fail(self,
  886. "branch %s is published (but not merged) and is now %d commits behind"
  887. % (branch.name, len(upstream_gain)))
  888. return
  889. elif pub == head:
  890. # All published commits are merged, and thus we are a
  891. # strict subset. We can fast-forward safely.
  892. #
  893. def _doff():
  894. self._FastForward(revid)
  895. self._CopyFiles()
  896. syncbuf.later1(self, _doff)
  897. return
  898. # Examine the local commits not in the remote. Find the
  899. # last one attributed to this user, if any.
  900. #
  901. local_changes = self._revlist(not_rev(revid), HEAD, format='%H %ce')
  902. last_mine = None
  903. cnt_mine = 0
  904. for commit in local_changes:
  905. commit_id, committer_email = commit.split(' ', 1)
  906. if committer_email == self.UserEmail:
  907. last_mine = commit_id
  908. cnt_mine += 1
  909. if not upstream_gain and cnt_mine == len(local_changes):
  910. return
  911. if self.IsDirty(consider_untracked=False):
  912. syncbuf.fail(self, _DirtyError())
  913. return
  914. # If the upstream switched on us, warn the user.
  915. #
  916. if branch.merge != self.revisionExpr:
  917. if branch.merge and self.revisionExpr:
  918. syncbuf.info(self,
  919. 'manifest switched %s...%s',
  920. branch.merge,
  921. self.revisionExpr)
  922. elif branch.merge:
  923. syncbuf.info(self,
  924. 'manifest no longer tracks %s',
  925. branch.merge)
  926. if cnt_mine < len(local_changes):
  927. # Upstream rebased. Not everything in HEAD
  928. # was created by this user.
  929. #
  930. syncbuf.info(self,
  931. "discarding %d commits removed from upstream",
  932. len(local_changes) - cnt_mine)
  933. branch.remote = self.GetRemote(self.remote.name)
  934. branch.merge = self.revisionExpr
  935. branch.Save()
  936. if cnt_mine > 0:
  937. def _dorebase():
  938. self._Rebase(upstream = '%s^1' % last_mine, onto = revid)
  939. self._CopyFiles()
  940. syncbuf.later2(self, _dorebase)
  941. elif local_changes:
  942. try:
  943. self._ResetHard(revid)
  944. self._CopyFiles()
  945. except GitError, e:
  946. syncbuf.fail(self, e)
  947. return
  948. else:
  949. def _doff():
  950. self._FastForward(revid)
  951. self._CopyFiles()
  952. syncbuf.later1(self, _doff)
  953. def AddCopyFile(self, src, dest, absdest):
  954. # dest should already be an absolute path, but src is project relative
  955. # make src an absolute path
  956. abssrc = os.path.join(self.worktree, src)
  957. self.copyfiles.append(_CopyFile(src, dest, abssrc, absdest))
  958. def DownloadPatchSet(self, change_id, patch_id):
  959. """Download a single patch set of a single change to FETCH_HEAD.
  960. """
  961. remote = self.GetRemote(self.remote.name)
  962. cmd = ['fetch', remote.name]
  963. cmd.append('refs/changes/%2.2d/%d/%d' \
  964. % (change_id % 100, change_id, patch_id))
  965. cmd.extend(map(lambda x: str(x), remote.fetch))
  966. if GitCommand(self, cmd, bare=True).Wait() != 0:
  967. return None
  968. return DownloadedChange(self,
  969. self.GetRevisionId(),
  970. change_id,
  971. patch_id,
  972. self.bare_git.rev_parse('FETCH_HEAD'))
  973. ## Branch Management ##
  974. def StartBranch(self, name):
  975. """Create a new branch off the manifest's revision.
  976. """
  977. head = self.work_git.GetHead()
  978. if head == (R_HEADS + name):
  979. return True
  980. all = self.bare_ref.all
  981. if (R_HEADS + name) in all:
  982. return GitCommand(self,
  983. ['checkout', name, '--'],
  984. capture_stdout = True,
  985. capture_stderr = True).Wait() == 0
  986. branch = self.GetBranch(name)
  987. branch.remote = self.GetRemote(self.remote.name)
  988. branch.merge = self.revisionExpr
  989. revid = self.GetRevisionId(all)
  990. if head.startswith(R_HEADS):
  991. try:
  992. head = all[head]
  993. except KeyError:
  994. head = None
  995. if revid and head and revid == head:
  996. ref = os.path.join(self.gitdir, R_HEADS + name)
  997. try:
  998. os.makedirs(os.path.dirname(ref))
  999. except OSError:
  1000. pass
  1001. _lwrite(ref, '%s\n' % revid)
  1002. _lwrite(os.path.join(self.worktree, '.git', HEAD),
  1003. 'ref: %s%s\n' % (R_HEADS, name))
  1004. branch.Save()
  1005. return True
  1006. if GitCommand(self,
  1007. ['checkout', '-b', branch.name, revid],
  1008. capture_stdout = True,
  1009. capture_stderr = True).Wait() == 0:
  1010. branch.Save()
  1011. return True
  1012. return False
  1013. def CheckoutBranch(self, name):
  1014. """Checkout a local topic branch.
  1015. Args:
  1016. name: The name of the branch to checkout.
  1017. Returns:
  1018. True if the checkout succeeded; False if it didn't; None if the branch
  1019. didn't exist.
  1020. """
  1021. rev = R_HEADS + name
  1022. head = self.work_git.GetHead()
  1023. if head == rev:
  1024. # Already on the branch
  1025. #
  1026. return True
  1027. all = self.bare_ref.all
  1028. try:
  1029. revid = all[rev]
  1030. except KeyError:
  1031. # Branch does not exist in this project
  1032. #
  1033. return None
  1034. if head.startswith(R_HEADS):
  1035. try:
  1036. head = all[head]
  1037. except KeyError:
  1038. head = None
  1039. if head == revid:
  1040. # Same revision; just update HEAD to point to the new
  1041. # target branch, but otherwise take no other action.
  1042. #
  1043. _lwrite(os.path.join(self.worktree, '.git', HEAD),
  1044. 'ref: %s%s\n' % (R_HEADS, name))
  1045. return True
  1046. return GitCommand(self,
  1047. ['checkout', name, '--'],
  1048. capture_stdout = True,
  1049. capture_stderr = True).Wait() == 0
  1050. def AbandonBranch(self, name):
  1051. """Destroy a local topic branch.
  1052. Args:
  1053. name: The name of the branch to abandon.
  1054. Returns:
  1055. True if the abandon succeeded; False if it didn't; None if the branch
  1056. didn't exist.
  1057. """
  1058. rev = R_HEADS + name
  1059. all = self.bare_ref.all
  1060. if rev not in all:
  1061. # Doesn't exist
  1062. return None
  1063. head = self.work_git.GetHead()
  1064. if head == rev:
  1065. # We can't destroy the branch while we are sitting
  1066. # on it. Switch to a detached HEAD.
  1067. #
  1068. head = all[head]
  1069. revid = self.GetRevisionId(all)
  1070. if head == revid:
  1071. _lwrite(os.path.join(self.worktree, '.git', HEAD),
  1072. '%s\n' % revid)
  1073. else:
  1074. self._Checkout(revid, quiet=True)
  1075. return GitCommand(self,
  1076. ['branch', '-D', name],
  1077. capture_stdout = True,
  1078. capture_stderr = True).Wait() == 0
  1079. def PruneHeads(self):
  1080. """Prune any topic branches already merged into upstream.
  1081. """
  1082. cb = self.CurrentBranch
  1083. kill = []
  1084. left = self._allrefs
  1085. for name in left.keys():
  1086. if name.startswith(R_HEADS):
  1087. name = name[len(R_HEADS):]
  1088. if cb is None or name != cb:
  1089. kill.append(name)
  1090. rev = self.GetRevisionId(left)
  1091. if cb is not None \
  1092. and not self._revlist(HEAD + '...' + rev) \
  1093. and not self.IsDirty(consider_untracked = False):
  1094. self.work_git.DetachHead(HEAD)
  1095. kill.append(cb)
  1096. if kill:
  1097. old = self.bare_git.GetHead()
  1098. if old is None:
  1099. old = 'refs/heads/please_never_use_this_as_a_branch_name'
  1100. try:
  1101. self.bare_git.DetachHead(rev)
  1102. b = ['branch', '-d']
  1103. b.extend(kill)
  1104. b = GitCommand(self, b, bare=True,
  1105. capture_stdout=True,
  1106. capture_stderr=True)
  1107. b.Wait()
  1108. finally:
  1109. self.bare_git.SetHead(old)
  1110. left = self._allrefs
  1111. for branch in kill:
  1112. if (R_HEADS + branch) not in left:
  1113. self.CleanPublishedCache()
  1114. break
  1115. if cb and cb not in kill:
  1116. kill.append(cb)
  1117. kill.sort()
  1118. kept = []
  1119. for branch in kill:
  1120. if (R_HEADS + branch) in left:
  1121. branch = self.GetBranch(branch)
  1122. base = branch.LocalMerge
  1123. if not base:
  1124. base = rev
  1125. kept.append(ReviewableBranch(self, branch, base))
  1126. return kept
  1127. ## Direct Git Commands ##
  1128. def _RemoteFetch(self, name=None, tag=None,
  1129. initial=False,
  1130. quiet=False,
  1131. alt_dir=None):
  1132. if not name:
  1133. name = self.remote.name
  1134. ssh_proxy = False
  1135. remote = self.GetRemote(name)
  1136. if remote.PreConnectFetch():
  1137. ssh_proxy = True
  1138. if initial:
  1139. if alt_dir and 'objects' == os.path.basename(alt_dir):
  1140. ref_dir = os.path.dirname(alt_dir)
  1141. packed_refs = os.path.join(self.gitdir, 'packed-refs')
  1142. remote = self.GetRemote(name)
  1143. all = self.bare_ref.all
  1144. ids = set(all.values())
  1145. tmp = set()
  1146. for r, id in GitRefs(ref_dir).all.iteritems():
  1147. if r not in all:
  1148. if r.startswith(R_TAGS) or remote.WritesTo(r):
  1149. all[r] = id
  1150. ids.add(id)
  1151. continue
  1152. if id in ids:
  1153. continue
  1154. r = 'refs/_alt/%s' % id
  1155. all[r] = id
  1156. ids.add(id)
  1157. tmp.add(r)
  1158. ref_names = list(all.keys())
  1159. ref_names.sort()
  1160. tmp_packed = ''
  1161. old_packed = ''
  1162. for r in ref_names:
  1163. line = '%s %s\n' % (all[r], r)
  1164. tmp_packed += line
  1165. if r not in tmp:
  1166. old_packed += line
  1167. _lwrite(packed_refs, tmp_packed)
  1168. else:
  1169. alt_dir = None
  1170. cmd = ['fetch']
  1171. # The --depth option only affects the initial fetch; after that we'll do
  1172. # full fetches of changes.
  1173. depth = self.manifest.manifestProject.config.GetString('repo.depth')
  1174. if depth and initial:
  1175. cmd.append('--depth=%s' % depth)
  1176. if quiet:
  1177. cmd.append('--quiet')
  1178. if not self.worktree:
  1179. cmd.append('--update-head-ok')
  1180. cmd.append(name)
  1181. if tag is not None:
  1182. cmd.append('tag')
  1183. cmd.append(tag)
  1184. ok = False
  1185. for i in range(2):
  1186. if GitCommand(self, cmd, bare=True, ssh_proxy=ssh_proxy).Wait() == 0:
  1187. ok = True
  1188. break
  1189. time.sleep(random.randint(30, 45))
  1190. if initial:
  1191. if alt_dir:
  1192. if old_packed != '':
  1193. _lwrite(packed_refs, old_packed)
  1194. else:
  1195. os.remove(packed_refs)
  1196. self.bare_git.pack_refs('--all', '--prune')
  1197. return ok
  1198. def _ApplyCloneBundle(self, initial=False, quiet=False):
  1199. if initial and self.manifest.manifestProject.config.GetString('repo.depth'):
  1200. return False
  1201. remote = self.GetRemote(self.remote.name)
  1202. bundle_url = remote.url + '/clone.bundle'
  1203. bundle_url = GitConfig.ForUser().UrlInsteadOf(bundle_url)
  1204. if GetSchemeFromUrl(bundle_url) not in ('http', 'https'):
  1205. return False
  1206. bundle_dst = os.path.join(self.gitdir, 'clone.bundle')
  1207. bundle_tmp = os.path.join(self.gitdir, 'clone.bundle.tmp')
  1208. exist_dst = os.path.exists(bundle_dst)
  1209. exist_tmp = os.path.exists(bundle_tmp)
  1210. if not initial and not exist_dst and not exist_tmp:
  1211. return False
  1212. if not exist_dst:
  1213. exist_dst = self._FetchBundle(bundle_url, bundle_tmp, bundle_dst, quiet)
  1214. if not exist_dst:
  1215. return False
  1216. cmd = ['fetch']
  1217. if quiet:
  1218. cmd.append('--quiet')
  1219. if not self.worktree:
  1220. cmd.append('--update-head-ok')
  1221. cmd.append(bundle_dst)
  1222. for f in remote.fetch:
  1223. cmd.append(str(f))
  1224. cmd.append('refs/tags/*:refs/tags/*')
  1225. ok = GitCommand(self, cmd, bare=True).Wait() == 0
  1226. if os.path.exists(bundle_dst):
  1227. os.remove(bundle_dst)
  1228. if os.path.exists(bundle_tmp):
  1229. os.remove(bundle_tmp)
  1230. return ok
  1231. def _FetchBundle(self, srcUrl, tmpPath, dstPath, quiet):
  1232. keep = True
  1233. done = False
  1234. dest = open(tmpPath, 'a+b')
  1235. try:
  1236. dest.seek(0, SEEK_END)
  1237. pos = dest.tell()
  1238. _urllib_lock.acquire()
  1239. try:
  1240. req = urllib2.Request(srcUrl)
  1241. if pos > 0:
  1242. req.add_header('Range', 'bytes=%d-' % pos)
  1243. try:
  1244. r = urllib2.urlopen(req)
  1245. except urllib2.HTTPError, e:
  1246. def _content_type():
  1247. try:
  1248. return e.info()['content-type']
  1249. except:
  1250. return None
  1251. if e.code == 404:
  1252. keep = False
  1253. return False
  1254. elif _content_type() == 'text/plain':
  1255. try:
  1256. msg = e.read()
  1257. if len(msg) > 0 and msg[-1] == '\n':
  1258. msg = msg[0:-1]
  1259. msg = ' (%s)' % msg
  1260. except:
  1261. msg = ''
  1262. else:
  1263. try:
  1264. from BaseHTTPServer import BaseHTTPRequestHandler
  1265. res = BaseHTTPRequestHandler.responses[e.code]
  1266. msg = ' (%s: %s)' % (res[0], res[1])
  1267. except:
  1268. msg = ''
  1269. raise DownloadError('HTTP %s%s' % (e.code, msg))
  1270. except urllib2.URLError, e:
  1271. raise DownloadError('%s: %s ' % (req.get_host(), str(e)))
  1272. finally:
  1273. _urllib_lock.release()
  1274. p = None
  1275. try:
  1276. size = r.headers['content-length']
  1277. unit = 1 << 10
  1278. if size and not quiet:
  1279. if size > 1024 * 1.3:
  1280. unit = 1 << 20
  1281. desc = 'MB'
  1282. else:
  1283. desc = 'KB'
  1284. p = Progress(
  1285. 'Downloading %s' % self.relpath,
  1286. int(size) / unit,
  1287. units=desc)
  1288. if pos > 0:
  1289. p.update(pos / unit)
  1290. s = 0
  1291. while True:
  1292. d = r.read(8192)
  1293. if d == '':
  1294. done = True
  1295. return True
  1296. dest.write(d)
  1297. if p:
  1298. s += len(d)
  1299. if s >= unit:
  1300. p.update(s / unit)
  1301. s = s % unit
  1302. if p:
  1303. if s >= unit:
  1304. p.update(s / unit)
  1305. else:
  1306. p.update(1)
  1307. finally:
  1308. r.close()
  1309. if p:
  1310. p.end()
  1311. finally:
  1312. dest.close()
  1313. if os.path.exists(dstPath):
  1314. os.remove(dstPath)
  1315. if done:
  1316. os.rename(tmpPath, dstPath)
  1317. elif not keep:
  1318. os.remove(tmpPath)
  1319. def _Checkout(self, rev, quiet=False):
  1320. cmd = ['checkout']
  1321. if quiet:
  1322. cmd.append('-q')
  1323. cmd.append(rev)
  1324. cmd.append('--')
  1325. if GitCommand(self, cmd).Wait() != 0:
  1326. if self._allrefs:
  1327. raise GitError('%s checkout %s ' % (self.name, rev))
  1328. def _ResetHard(self, rev, quiet=True):
  1329. cmd = ['reset', '--hard']
  1330. if quiet:
  1331. cmd.append('-q')
  1332. cmd.append(rev)
  1333. if GitCommand(self, cmd).Wait() != 0:
  1334. raise GitError('%s reset --hard %s ' % (self.name, rev))
  1335. def _Rebase(self, upstream, onto = None):
  1336. cmd = ['rebase']
  1337. if onto is not None:
  1338. cmd.extend(['--onto', onto])
  1339. cmd.append(upstream)
  1340. if GitCommand(self, cmd).Wait() != 0:
  1341. raise GitError('%s rebase %s ' % (self.name, upstream))
  1342. def _FastForward(self, head):
  1343. cmd = ['merge', head]
  1344. if GitCommand(self, cmd).Wait() != 0:
  1345. raise GitError('%s merge %s ' % (self.name, head))
  1346. def _InitGitDir(self):
  1347. if not os.path.exists(self.gitdir):
  1348. os.makedirs(self.gitdir)
  1349. self.bare_git.init()
  1350. mp = self.manifest.manifestProject
  1351. ref_dir = mp.config.GetString('repo.reference')
  1352. if ref_dir:
  1353. mirror_git = os.path.join(ref_dir, self.name + '.git')
  1354. repo_git = os.path.join(ref_dir, '.repo', 'projects',
  1355. self.relpath + '.git')
  1356. if os.path.exists(mirror_git):
  1357. ref_dir = mirror_git
  1358. elif os.path.exists(repo_git):
  1359. ref_dir = repo_git
  1360. else:
  1361. ref_dir = None
  1362. if ref_dir:
  1363. _lwrite(os.path.join(self.gitdir, 'objects/info/alternates'),
  1364. os.path.join(ref_dir, 'objects') + '\n')
  1365. if self.manifest.IsMirror:
  1366. self.config.SetString('core.bare', 'true')
  1367. else:
  1368. self.config.SetString('core.bare', None)
  1369. hooks = self._gitdir_path('hooks')
  1370. try:
  1371. to_rm = os.listdir(hooks)
  1372. except OSError:
  1373. to_rm = []
  1374. for old_hook in to_rm:
  1375. os.remove(os.path.join(hooks, old_hook))
  1376. self._InitHooks()
  1377. m = self.manifest.manifestProject.config
  1378. for key in ['user.name', 'user.email']:
  1379. if m.Has(key, include_defaults = False):
  1380. self.config.SetString(key, m.GetString(key))
  1381. def _InitHooks(self):
  1382. hooks = self._gitdir_path('hooks')
  1383. if not os.path.exists(hooks):
  1384. os.makedirs(hooks)
  1385. for stock_hook in _ProjectHooks():
  1386. name = os.path.basename(stock_hook)
  1387. if name in ('commit-msg',) and not self.remote.review \
  1388. and not self is self.manifest.manifestProject:
  1389. # Don't install a Gerrit Code Review hook if this
  1390. # project does not appear to use it for reviews.
  1391. #
  1392. # Since the manifest project is one of those, but also
  1393. # managed through gerrit, it's excluded
  1394. continue
  1395. dst = os.path.join(hooks, name)
  1396. if os.path.islink(dst):
  1397. continue
  1398. if os.path.exists(dst):
  1399. if filecmp.cmp(stock_hook, dst, shallow=False):
  1400. os.remove(dst)
  1401. else:
  1402. _error("%s: Not replacing %s hook", self.relpath, name)
  1403. continue
  1404. try:
  1405. os.symlink(relpath(stock_hook, dst), dst)
  1406. except OSError, e:
  1407. if e.errno == errno.EPERM:
  1408. raise GitError('filesystem must support symlinks')
  1409. else:
  1410. raise
  1411. def _InitRemote(self):
  1412. if self.remote.url:
  1413. remote = self.GetRemote(self.remote.name)
  1414. remote.url = self.remote.url
  1415. remote.review = self.remote.review
  1416. remote.projectname = self.name
  1417. if self.worktree:
  1418. remote.ResetFetch(mirror=False)
  1419. else:
  1420. remote.ResetFetch(mirror=True)
  1421. remote.Save()
  1422. def _InitMRef(self):
  1423. if self.manifest.branch:
  1424. self._InitAnyMRef(R_M + self.manifest.branch)
  1425. def _InitMirrorHead(self):
  1426. self._InitAnyMRef(HEAD)
  1427. def _InitAnyMRef(self, ref):
  1428. cur = self.bare_ref.symref(ref)
  1429. if self.revisionId:
  1430. if cur != '' or self.bare_ref.get(ref) != self.revisionId:
  1431. msg = 'manifest set to %s' % self.revisionId
  1432. dst = self.revisionId + '^0'
  1433. self.bare_git.UpdateRef(ref, dst, message = msg, detach = True)
  1434. else:
  1435. remote = self.GetRemote(self.remote.name)
  1436. dst = remote.ToLocal(self.revisionExpr)
  1437. if cur != dst:
  1438. msg = 'manifest set to %s' % self.revisionExpr
  1439. self.bare_git.symbolic_ref('-m', msg, ref, dst)
  1440. def _InitWorkTree(self):
  1441. dotgit = os.path.join(self.worktree, '.git')
  1442. if not os.path.exists(dotgit):
  1443. os.makedirs(dotgit)
  1444. for name in ['config',
  1445. 'description',
  1446. 'hooks',
  1447. 'info',
  1448. 'logs',
  1449. 'objects',
  1450. 'packed-refs',
  1451. 'refs',
  1452. 'rr-cache',
  1453. 'svn']:
  1454. try:
  1455. src = os.path.join(self.gitdir, name)
  1456. dst = os.path.join(dotgit, name)
  1457. if os.path.islink(dst) or not os.path.exists(dst):
  1458. os.symlink(relpath(src, dst), dst)
  1459. else:
  1460. raise GitError('cannot overwrite a local work tree')
  1461. except OSError, e:
  1462. if e.errno == errno.EPERM:
  1463. raise GitError('filesystem must support symlinks')
  1464. else:
  1465. raise
  1466. _lwrite(os.path.join(dotgit, HEAD), '%s\n' % self.GetRevisionId())
  1467. cmd = ['read-tree', '--reset', '-u']
  1468. cmd.append('-v')
  1469. cmd.append(HEAD)
  1470. if GitCommand(self, cmd).Wait() != 0:
  1471. raise GitError("cannot initialize work tree")
  1472. rr_cache = os.path.join(self.gitdir, 'rr-cache')
  1473. if not os.path.exists(rr_cache):
  1474. os.makedirs(rr_cache)
  1475. self._CopyFiles()
  1476. def _gitdir_path(self, path):
  1477. return os.path.join(self.gitdir, path)
  1478. def _revlist(self, *args, **kw):
  1479. a = []
  1480. a.extend(args)
  1481. a.append('--')
  1482. return self.work_git.rev_list(*a, **kw)
  1483. @property
  1484. def _allrefs(self):
  1485. return self.bare_ref.all
  1486. class _GitGetByExec(object):
  1487. def __init__(self, project, bare):
  1488. self._project = project
  1489. self._bare = bare
  1490. def LsOthers(self):
  1491. p = GitCommand(self._project,
  1492. ['ls-files',
  1493. '-z',
  1494. '--others',
  1495. '--exclude-standard'],
  1496. bare = False,
  1497. capture_stdout = True,
  1498. capture_stderr = True)
  1499. if p.Wait() == 0:
  1500. out = p.stdout
  1501. if out:
  1502. return out[:-1].split("\0")
  1503. return []
  1504. def DiffZ(self, name, *args):
  1505. cmd = [name]
  1506. cmd.append('-z')
  1507. cmd.extend(args)
  1508. p = GitCommand(self._project,
  1509. cmd,
  1510. bare = False,
  1511. capture_stdout = True,
  1512. capture_stderr = True)
  1513. try:
  1514. out = p.process.stdout.read()
  1515. r = {}
  1516. if out:
  1517. out = iter(out[:-1].split('\0'))
  1518. while out:
  1519. try:
  1520. info = out.next()
  1521. path = out.next()
  1522. except StopIteration:
  1523. break
  1524. class _Info(object):
  1525. def __init__(self, path, omode, nmode, oid, nid, state):
  1526. self.path = path
  1527. self.src_path = None
  1528. self.old_mode = omode
  1529. self.new_mode = nmode
  1530. self.old_id = oid
  1531. self.new_id = nid
  1532. if len(state) == 1:
  1533. self.status = state
  1534. self.level = None
  1535. else:
  1536. self.status = state[:1]
  1537. self.level = state[1:]
  1538. while self.level.startswith('0'):
  1539. self.level = self.level[1:]
  1540. info = info[1:].split(' ')
  1541. info =_Info(path, *info)
  1542. if info.status in ('R', 'C'):
  1543. info.src_path = info.path
  1544. info.path = out.next()
  1545. r[info.path] = info
  1546. return r
  1547. finally:
  1548. p.Wait()
  1549. def GetHead(self):
  1550. if self._bare:
  1551. path = os.path.join(self._project.gitdir, HEAD)
  1552. else:
  1553. path = os.path.join(self._project.worktree, '.git', HEAD)
  1554. fd = open(path, 'rb')
  1555. try:
  1556. line = fd.read()
  1557. finally:
  1558. fd.close()
  1559. if line.startswith('ref: '):
  1560. return line[5:-1]
  1561. return line[:-1]
  1562. def SetHead(self, ref, message=None):
  1563. cmdv = []
  1564. if message is not None:
  1565. cmdv.extend(['-m', message])
  1566. cmdv.append(HEAD)
  1567. cmdv.append(ref)
  1568. self.symbolic_ref(*cmdv)
  1569. def DetachHead(self, new, message=None):
  1570. cmdv = ['--no-deref']
  1571. if message is not None:
  1572. cmdv.extend(['-m', message])
  1573. cmdv.append(HEAD)
  1574. cmdv.append(new)
  1575. self.update_ref(*cmdv)
  1576. def UpdateRef(self, name, new, old=None,
  1577. message=None,
  1578. detach=False):
  1579. cmdv = []
  1580. if message is not None:
  1581. cmdv.extend(['-m', message])
  1582. if detach:
  1583. cmdv.append('--no-deref')
  1584. cmdv.append(name)
  1585. cmdv.append(new)
  1586. if old is not None:
  1587. cmdv.append(old)
  1588. self.update_ref(*cmdv)
  1589. def DeleteRef(self, name, old=None):
  1590. if not old:
  1591. old = self.rev_parse(name)
  1592. self.update_ref('-d', name, old)
  1593. self._project.bare_ref.deleted(name)
  1594. def rev_list(self, *args, **kw):
  1595. if 'format' in kw:
  1596. cmdv = ['log', '--pretty=format:%s' % kw['format']]
  1597. else:
  1598. cmdv = ['rev-list']
  1599. cmdv.extend(args)
  1600. p = GitCommand(self._project,
  1601. cmdv,
  1602. bare = self._bare,
  1603. capture_stdout = True,
  1604. capture_stderr = True)
  1605. r = []
  1606. for line in p.process.stdout:
  1607. if line[-1] == '\n':
  1608. line = line[:-1]
  1609. r.append(line)
  1610. if p.Wait() != 0:
  1611. raise GitError('%s rev-list %s: %s' % (
  1612. self._project.name,
  1613. str(args),
  1614. p.stderr))
  1615. return r
  1616. def __getattr__(self, name):
  1617. """Allow arbitrary git commands using pythonic syntax.
  1618. This allows you to do things like:
  1619. git_obj.rev_parse('HEAD')
  1620. Since we don't have a 'rev_parse' method defined, the __getattr__ will
  1621. run. We'll replace the '_' with a '-' and try to run a git command.
  1622. Any other arguments will be passed to the git command.
  1623. Args:
  1624. name: The name of the git command to call. Any '_' characters will
  1625. be replaced with '-'.
  1626. Returns:
  1627. A callable object that will try to call git with the named command.
  1628. """
  1629. name = name.replace('_', '-')
  1630. def runner(*args):
  1631. cmdv = [name]
  1632. cmdv.extend(args)
  1633. p = GitCommand(self._project,
  1634. cmdv,
  1635. bare = self._bare,
  1636. capture_stdout = True,
  1637. capture_stderr = True)
  1638. if p.Wait() != 0:
  1639. raise GitError('%s %s: %s' % (
  1640. self._project.name,
  1641. name,
  1642. p.stderr))
  1643. r = p.stdout
  1644. if r.endswith('\n') and r.index('\n') == len(r) - 1:
  1645. return r[:-1]
  1646. return r
  1647. return runner
  1648. class _PriorSyncFailedError(Exception):
  1649. def __str__(self):
  1650. return 'prior sync failed; rebase still in progress'
  1651. class _DirtyError(Exception):
  1652. def __str__(self):
  1653. return 'contains uncommitted changes'
  1654. class _InfoMessage(object):
  1655. def __init__(self, project, text):
  1656. self.project = project
  1657. self.text = text
  1658. def Print(self, syncbuf):
  1659. syncbuf.out.info('%s/: %s', self.project.relpath, self.text)
  1660. syncbuf.out.nl()
  1661. class _Failure(object):
  1662. def __init__(self, project, why):
  1663. self.project = project
  1664. self.why = why
  1665. def Print(self, syncbuf):
  1666. syncbuf.out.fail('error: %s/: %s',
  1667. self.project.relpath,
  1668. str(self.why))
  1669. syncbuf.out.nl()
  1670. class _Later(object):
  1671. def __init__(self, project, action):
  1672. self.project = project
  1673. self.action = action
  1674. def Run(self, syncbuf):
  1675. out = syncbuf.out
  1676. out.project('project %s/', self.project.relpath)
  1677. out.nl()
  1678. try:
  1679. self.action()
  1680. out.nl()
  1681. return True
  1682. except GitError, e:
  1683. out.nl()
  1684. return False
  1685. class _SyncColoring(Coloring):
  1686. def __init__(self, config):
  1687. Coloring.__init__(self, config, 'reposync')
  1688. self.project = self.printer('header', attr = 'bold')
  1689. self.info = self.printer('info')
  1690. self.fail = self.printer('fail', fg='red')
  1691. class SyncBuffer(object):
  1692. def __init__(self, config, detach_head=False):
  1693. self._messages = []
  1694. self._failures = []
  1695. self._later_queue1 = []
  1696. self._later_queue2 = []
  1697. self.out = _SyncColoring(config)
  1698. self.out.redirect(sys.stderr)
  1699. self.detach_head = detach_head
  1700. self.clean = True
  1701. def info(self, project, fmt, *args):
  1702. self._messages.append(_InfoMessage(project, fmt % args))
  1703. def fail(self, project, err=None):
  1704. self._failures.append(_Failure(project, err))
  1705. self.clean = False
  1706. def later1(self, project, what):
  1707. self._later_queue1.append(_Later(project, what))
  1708. def later2(self, project, what):
  1709. self._later_queue2.append(_Later(project, what))
  1710. def Finish(self):
  1711. self._PrintMessages()
  1712. self._RunLater()
  1713. self._PrintMessages()
  1714. return self.clean
  1715. def _RunLater(self):
  1716. for q in ['_later_queue1', '_later_queue2']:
  1717. if not self._RunQueue(q):
  1718. return
  1719. def _RunQueue(self, queue):
  1720. for m in getattr(self, queue):
  1721. if not m.Run(self):
  1722. self.clean = False
  1723. return False
  1724. setattr(self, queue, [])
  1725. return True
  1726. def _PrintMessages(self):
  1727. for m in self._messages:
  1728. m.Print(self)
  1729. for m in self._failures:
  1730. m.Print(self)
  1731. self._messages = []
  1732. self._failures = []
  1733. class MetaProject(Project):
  1734. """A special project housed under .repo.
  1735. """
  1736. def __init__(self, manifest, name, gitdir, worktree):
  1737. repodir = manifest.repodir
  1738. Project.__init__(self,
  1739. manifest = manifest,
  1740. name = name,
  1741. gitdir = gitdir,
  1742. worktree = worktree,
  1743. remote = RemoteSpec('origin'),
  1744. relpath = '.repo/%s' % name,
  1745. revisionExpr = 'refs/heads/master',
  1746. revisionId = None)
  1747. def PreSync(self):
  1748. if self.Exists:
  1749. cb = self.CurrentBranch
  1750. if cb:
  1751. base = self.GetBranch(cb).merge
  1752. if base:
  1753. self.revisionExpr = base
  1754. self.revisionId = None
  1755. @property
  1756. def LastFetch(self):
  1757. try:
  1758. fh = os.path.join(self.gitdir, 'FETCH_HEAD')
  1759. return os.path.getmtime(fh)
  1760. except OSError:
  1761. return 0
  1762. @property
  1763. def HasChanges(self):
  1764. """Has the remote received new commits not yet checked out?
  1765. """
  1766. if not self.remote or not self.revisionExpr:
  1767. return False
  1768. all = self.bare_ref.all
  1769. revid = self.GetRevisionId(all)
  1770. head = self.work_git.GetHead()
  1771. if head.startswith(R_HEADS):
  1772. try:
  1773. head = all[head]
  1774. except KeyError:
  1775. head = None
  1776. if revid == head:
  1777. return False
  1778. elif self._revlist(not_rev(HEAD), revid):
  1779. return True
  1780. return False