project.py 59 KB

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