project.py 87 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821
  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. from __future__ import print_function
  15. import errno
  16. import filecmp
  17. import glob
  18. import os
  19. import random
  20. import re
  21. import shutil
  22. import stat
  23. import subprocess
  24. import sys
  25. import tarfile
  26. import tempfile
  27. import time
  28. import traceback
  29. from color import Coloring
  30. from git_command import GitCommand, git_require
  31. from git_config import GitConfig, IsId, GetSchemeFromUrl, GetUrlCookieFile, ID_RE
  32. from error import GitError, HookError, UploadError, DownloadError
  33. from error import ManifestInvalidRevisionError
  34. from error import NoManifestException
  35. from trace import IsTrace, Trace
  36. from git_refs import GitRefs, HEAD, R_HEADS, R_TAGS, R_PUB, R_M
  37. from pyversion import is_python3
  38. if not is_python3():
  39. # pylint:disable=W0622
  40. input = raw_input
  41. # pylint:enable=W0622
  42. def _lwrite(path, content):
  43. lock = '%s.lock' % path
  44. fd = open(lock, 'w')
  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('error: %s' % msg, file=sys.stderr)
  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.realpath(os.path.abspath(os.path.dirname(__file__)))
  74. d = os.path.join(d, 'hooks')
  75. _project_hook_list = [os.path.join(d, x) for x in os.listdir(d)]
  76. return _project_hook_list
  77. class DownloadedChange(object):
  78. _commit_cache = None
  79. def __init__(self, project, base, change_id, ps_id, commit):
  80. self.project = project
  81. self.base = base
  82. self.change_id = change_id
  83. self.ps_id = ps_id
  84. self.commit = commit
  85. @property
  86. def commits(self):
  87. if self._commit_cache is None:
  88. self._commit_cache = self.project.bare_git.rev_list(
  89. '--abbrev=8',
  90. '--abbrev-commit',
  91. '--pretty=oneline',
  92. '--reverse',
  93. '--date-order',
  94. not_rev(self.base),
  95. self.commit,
  96. '--')
  97. return self._commit_cache
  98. class ReviewableBranch(object):
  99. _commit_cache = None
  100. def __init__(self, project, branch, base):
  101. self.project = project
  102. self.branch = branch
  103. self.base = base
  104. @property
  105. def name(self):
  106. return self.branch.name
  107. @property
  108. def commits(self):
  109. if self._commit_cache is None:
  110. self._commit_cache = self.project.bare_git.rev_list(
  111. '--abbrev=8',
  112. '--abbrev-commit',
  113. '--pretty=oneline',
  114. '--reverse',
  115. '--date-order',
  116. not_rev(self.base),
  117. R_HEADS + self.name,
  118. '--')
  119. return self._commit_cache
  120. @property
  121. def unabbrev_commits(self):
  122. r = dict()
  123. for commit in self.project.bare_git.rev_list(
  124. not_rev(self.base),
  125. R_HEADS + self.name,
  126. '--'):
  127. r[commit[0:8]] = commit
  128. return r
  129. @property
  130. def date(self):
  131. return self.project.bare_git.log(
  132. '--pretty=format:%cd',
  133. '-n', '1',
  134. R_HEADS + self.name,
  135. '--')
  136. def UploadForReview(self, people, auto_topic=False, draft=False, dest_branch=None):
  137. self.project.UploadForReview(self.name,
  138. people,
  139. auto_topic=auto_topic,
  140. draft=draft,
  141. dest_branch=dest_branch)
  142. def GetPublishedRefs(self):
  143. refs = {}
  144. output = self.project.bare_git.ls_remote(
  145. self.branch.remote.SshReviewUrl(self.project.UserEmail),
  146. 'refs/changes/*')
  147. for line in output.split('\n'):
  148. try:
  149. (sha, ref) = line.split()
  150. refs[sha] = ref
  151. except ValueError:
  152. pass
  153. return refs
  154. class StatusColoring(Coloring):
  155. def __init__(self, config):
  156. Coloring.__init__(self, config, 'status')
  157. self.project = self.printer('header', attr='bold')
  158. self.branch = self.printer('header', attr='bold')
  159. self.nobranch = self.printer('nobranch', fg='red')
  160. self.important = self.printer('important', fg='red')
  161. self.added = self.printer('added', fg='green')
  162. self.changed = self.printer('changed', fg='red')
  163. self.untracked = self.printer('untracked', fg='red')
  164. class DiffColoring(Coloring):
  165. def __init__(self, config):
  166. Coloring.__init__(self, config, 'diff')
  167. self.project = self.printer('header', attr='bold')
  168. class _Annotation(object):
  169. def __init__(self, name, value, keep):
  170. self.name = name
  171. self.value = value
  172. self.keep = keep
  173. class _CopyFile(object):
  174. def __init__(self, src, dest, abssrc, absdest):
  175. self.src = src
  176. self.dest = dest
  177. self.abs_src = abssrc
  178. self.abs_dest = absdest
  179. def _Copy(self):
  180. src = self.abs_src
  181. dest = self.abs_dest
  182. # copy file if it does not exist or is out of date
  183. if not os.path.exists(dest) or not filecmp.cmp(src, dest):
  184. try:
  185. # remove existing file first, since it might be read-only
  186. if os.path.exists(dest):
  187. os.remove(dest)
  188. else:
  189. dest_dir = os.path.dirname(dest)
  190. if not os.path.isdir(dest_dir):
  191. os.makedirs(dest_dir)
  192. shutil.copy(src, dest)
  193. # make the file read-only
  194. mode = os.stat(dest)[stat.ST_MODE]
  195. mode = mode & ~(stat.S_IWUSR | stat.S_IWGRP | stat.S_IWOTH)
  196. os.chmod(dest, mode)
  197. except IOError:
  198. _error('Cannot copy file %s to %s', src, dest)
  199. class _LinkFile(object):
  200. def __init__(self, git_worktree, src, dest, relsrc, absdest):
  201. self.git_worktree = git_worktree
  202. self.src = src
  203. self.dest = dest
  204. self.src_rel_to_dest = relsrc
  205. self.abs_dest = absdest
  206. def __linkIt(self, relSrc, absDest):
  207. # link file if it does not exist or is out of date
  208. if not os.path.islink(absDest) or (os.readlink(absDest) != relSrc):
  209. try:
  210. # remove existing file first, since it might be read-only
  211. if os.path.exists(absDest):
  212. os.remove(absDest)
  213. else:
  214. dest_dir = os.path.dirname(absDest)
  215. if not os.path.isdir(dest_dir):
  216. os.makedirs(dest_dir)
  217. os.symlink(relSrc, absDest)
  218. except IOError:
  219. _error('Cannot link file %s to %s', relSrc, absDest)
  220. def _Link(self):
  221. """Link the self.rel_src_to_dest and self.abs_dest. Handles wild cards
  222. on the src linking all of the files in the source in to the destination
  223. directory.
  224. """
  225. # We use the absSrc to handle the situation where the current directory
  226. # is not the root of the repo
  227. absSrc = os.path.join(self.git_worktree, self.src)
  228. if os.path.exists(absSrc):
  229. # Entity exists so just a simple one to one link operation
  230. self.__linkIt(self.src_rel_to_dest, self.abs_dest)
  231. else:
  232. # Entity doesn't exist assume there is a wild card
  233. absDestDir = self.abs_dest
  234. if os.path.exists(absDestDir) and not os.path.isdir(absDestDir):
  235. _error('Link error: src with wildcard, %s must be a directory',
  236. absDestDir)
  237. else:
  238. absSrcFiles = glob.glob(absSrc)
  239. for absSrcFile in absSrcFiles:
  240. # Create a releative path from source dir to destination dir
  241. absSrcDir = os.path.dirname(absSrcFile)
  242. relSrcDir = os.path.relpath(absSrcDir, absDestDir)
  243. # Get the source file name
  244. srcFile = os.path.basename(absSrcFile)
  245. # Now form the final full paths to srcFile. They will be
  246. # absolute for the desintaiton and relative for the srouce.
  247. absDest = os.path.join(absDestDir, srcFile)
  248. relSrc = os.path.join(relSrcDir, srcFile)
  249. self.__linkIt(relSrc, absDest)
  250. class RemoteSpec(object):
  251. def __init__(self,
  252. name,
  253. url=None,
  254. review=None,
  255. revision=None):
  256. self.name = name
  257. self.url = url
  258. self.review = review
  259. self.revision = revision
  260. class RepoHook(object):
  261. """A RepoHook contains information about a script to run as a hook.
  262. Hooks are used to run a python script before running an upload (for instance,
  263. to run presubmit checks). Eventually, we may have hooks for other actions.
  264. This shouldn't be confused with files in the 'repo/hooks' directory. Those
  265. files are copied into each '.git/hooks' folder for each project. Repo-level
  266. hooks are associated instead with repo actions.
  267. Hooks are always python. When a hook is run, we will load the hook into the
  268. interpreter and execute its main() function.
  269. """
  270. def __init__(self,
  271. hook_type,
  272. hooks_project,
  273. topdir,
  274. abort_if_user_denies=False):
  275. """RepoHook constructor.
  276. Params:
  277. hook_type: A string representing the type of hook. This is also used
  278. to figure out the name of the file containing the hook. For
  279. example: 'pre-upload'.
  280. hooks_project: The project containing the repo hooks. If you have a
  281. manifest, this is manifest.repo_hooks_project. OK if this is None,
  282. which will make the hook a no-op.
  283. topdir: Repo's top directory (the one containing the .repo directory).
  284. Scripts will run with CWD as this directory. If you have a manifest,
  285. this is manifest.topdir
  286. abort_if_user_denies: If True, we'll throw a HookError() if the user
  287. doesn't allow us to run the hook.
  288. """
  289. self._hook_type = hook_type
  290. self._hooks_project = hooks_project
  291. self._topdir = topdir
  292. self._abort_if_user_denies = abort_if_user_denies
  293. # Store the full path to the script for convenience.
  294. if self._hooks_project:
  295. self._script_fullpath = os.path.join(self._hooks_project.worktree,
  296. self._hook_type + '.py')
  297. else:
  298. self._script_fullpath = None
  299. def _GetHash(self):
  300. """Return a hash of the contents of the hooks directory.
  301. We'll just use git to do this. This hash has the property that if anything
  302. changes in the directory we will return a different has.
  303. SECURITY CONSIDERATION:
  304. This hash only represents the contents of files in the hook directory, not
  305. any other files imported or called by hooks. Changes to imported files
  306. can change the script behavior without affecting the hash.
  307. Returns:
  308. A string representing the hash. This will always be ASCII so that it can
  309. be printed to the user easily.
  310. """
  311. assert self._hooks_project, "Must have hooks to calculate their hash."
  312. # We will use the work_git object rather than just calling GetRevisionId().
  313. # That gives us a hash of the latest checked in version of the files that
  314. # the user will actually be executing. Specifically, GetRevisionId()
  315. # doesn't appear to change even if a user checks out a different version
  316. # of the hooks repo (via git checkout) nor if a user commits their own revs.
  317. #
  318. # NOTE: Local (non-committed) changes will not be factored into this hash.
  319. # I think this is OK, since we're really only worried about warning the user
  320. # about upstream changes.
  321. return self._hooks_project.work_git.rev_parse('HEAD')
  322. def _GetMustVerb(self):
  323. """Return 'must' if the hook is required; 'should' if not."""
  324. if self._abort_if_user_denies:
  325. return 'must'
  326. else:
  327. return 'should'
  328. def _CheckForHookApproval(self):
  329. """Check to see whether this hook has been approved.
  330. We'll look at the hash of all of the hooks. If this matches the hash that
  331. the user last approved, we're done. If it doesn't, we'll ask the user
  332. about approval.
  333. Note that we ask permission for each individual hook even though we use
  334. the hash of all hooks when detecting changes. We'd like the user to be
  335. able to approve / deny each hook individually. We only use the hash of all
  336. hooks because there is no other easy way to detect changes to local imports.
  337. Returns:
  338. True if this hook is approved to run; False otherwise.
  339. Raises:
  340. HookError: Raised if the user doesn't approve and abort_if_user_denies
  341. was passed to the consturctor.
  342. """
  343. hooks_config = self._hooks_project.config
  344. git_approval_key = 'repo.hooks.%s.approvedhash' % self._hook_type
  345. # Get the last hash that the user approved for this hook; may be None.
  346. old_hash = hooks_config.GetString(git_approval_key)
  347. # Get the current hash so we can tell if scripts changed since approval.
  348. new_hash = self._GetHash()
  349. if old_hash is not None:
  350. # User previously approved hook and asked not to be prompted again.
  351. if new_hash == old_hash:
  352. # Approval matched. We're done.
  353. return True
  354. else:
  355. # Give the user a reason why we're prompting, since they last told
  356. # us to "never ask again".
  357. prompt = 'WARNING: Scripts have changed since %s was allowed.\n\n' % (
  358. self._hook_type)
  359. else:
  360. prompt = ''
  361. # Prompt the user if we're not on a tty; on a tty we'll assume "no".
  362. if sys.stdout.isatty():
  363. prompt += ('Repo %s run the script:\n'
  364. ' %s\n'
  365. '\n'
  366. 'Do you want to allow this script to run '
  367. '(yes/yes-never-ask-again/NO)? ') % (
  368. self._GetMustVerb(), self._script_fullpath)
  369. response = input(prompt).lower()
  370. print()
  371. # User is doing a one-time approval.
  372. if response in ('y', 'yes'):
  373. return True
  374. elif response == 'yes-never-ask-again':
  375. hooks_config.SetString(git_approval_key, new_hash)
  376. return True
  377. # For anything else, we'll assume no approval.
  378. if self._abort_if_user_denies:
  379. raise HookError('You must allow the %s hook or use --no-verify.' %
  380. self._hook_type)
  381. return False
  382. def _ExecuteHook(self, **kwargs):
  383. """Actually execute the given hook.
  384. This will run the hook's 'main' function in our python interpreter.
  385. Args:
  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. """
  390. # Keep sys.path and CWD stashed away so that we can always restore them
  391. # upon function exit.
  392. orig_path = os.getcwd()
  393. orig_syspath = sys.path
  394. try:
  395. # Always run hooks with CWD as topdir.
  396. os.chdir(self._topdir)
  397. # Put the hook dir as the first item of sys.path so hooks can do
  398. # relative imports. We want to replace the repo dir as [0] so
  399. # hooks can't import repo files.
  400. sys.path = [os.path.dirname(self._script_fullpath)] + sys.path[1:]
  401. # Exec, storing global context in the context dict. We catch exceptions
  402. # and convert to a HookError w/ just the failing traceback.
  403. context = {}
  404. try:
  405. exec(compile(open(self._script_fullpath).read(),
  406. self._script_fullpath, 'exec'), context)
  407. except Exception:
  408. raise HookError('%s\nFailed to import %s hook; see traceback above.' % (
  409. traceback.format_exc(), self._hook_type))
  410. # Running the script should have defined a main() function.
  411. if 'main' not in context:
  412. raise HookError('Missing main() in: "%s"' % self._script_fullpath)
  413. # Add 'hook_should_take_kwargs' to the arguments to be passed to main.
  414. # We don't actually want hooks to define their main with this argument--
  415. # it's there to remind them that their hook should always take **kwargs.
  416. # For instance, a pre-upload hook should be defined like:
  417. # def main(project_list, **kwargs):
  418. #
  419. # This allows us to later expand the API without breaking old hooks.
  420. kwargs = kwargs.copy()
  421. kwargs['hook_should_take_kwargs'] = True
  422. # Call the main function in the hook. If the hook should cause the
  423. # build to fail, it will raise an Exception. We'll catch that convert
  424. # to a HookError w/ just the failing traceback.
  425. try:
  426. context['main'](**kwargs)
  427. except Exception:
  428. raise HookError('%s\nFailed to run main() for %s hook; see traceback '
  429. 'above.' % (
  430. traceback.format_exc(), self._hook_type))
  431. finally:
  432. # Restore sys.path and CWD.
  433. sys.path = orig_syspath
  434. os.chdir(orig_path)
  435. def Run(self, user_allows_all_hooks, **kwargs):
  436. """Run the hook.
  437. If the hook doesn't exist (because there is no hooks project or because
  438. this particular hook is not enabled), this is a no-op.
  439. Args:
  440. user_allows_all_hooks: If True, we will never prompt about running the
  441. hook--we'll just assume it's OK to run it.
  442. kwargs: Keyword arguments to pass to the hook. These are often specific
  443. to the hook type. For instance, pre-upload hooks will contain
  444. a project_list.
  445. Raises:
  446. HookError: If there was a problem finding the hook or the user declined
  447. to run a required hook (from _CheckForHookApproval).
  448. """
  449. # No-op if there is no hooks project or if hook is disabled.
  450. if ((not self._hooks_project) or
  451. (self._hook_type not in self._hooks_project.enabled_repo_hooks)):
  452. return
  453. # Bail with a nice error if we can't find the hook.
  454. if not os.path.isfile(self._script_fullpath):
  455. raise HookError('Couldn\'t find repo hook: "%s"' % self._script_fullpath)
  456. # Make sure the user is OK with running the hook.
  457. if (not user_allows_all_hooks) and (not self._CheckForHookApproval()):
  458. return
  459. # Run the hook with the same version of python we're using.
  460. self._ExecuteHook(**kwargs)
  461. class Project(object):
  462. # These objects can be shared between several working trees.
  463. shareable_files = ['description', 'info']
  464. shareable_dirs = ['hooks', 'objects', 'rr-cache', 'svn']
  465. # These objects can only be used by a single working tree.
  466. working_tree_files = ['config', 'packed-refs', 'shallow']
  467. working_tree_dirs = ['logs', 'refs']
  468. def __init__(self,
  469. manifest,
  470. name,
  471. remote,
  472. gitdir,
  473. objdir,
  474. worktree,
  475. relpath,
  476. revisionExpr,
  477. revisionId,
  478. rebase=True,
  479. groups=None,
  480. sync_c=False,
  481. sync_s=False,
  482. clone_depth=None,
  483. upstream=None,
  484. parent=None,
  485. is_derived=False,
  486. dest_branch=None,
  487. optimized_fetch=False):
  488. """Init a Project object.
  489. Args:
  490. manifest: The XmlManifest object.
  491. name: The `name` attribute of manifest.xml's project element.
  492. remote: RemoteSpec object specifying its remote's properties.
  493. gitdir: Absolute path of git directory.
  494. objdir: Absolute path of directory to store git objects.
  495. worktree: Absolute path of git working tree.
  496. relpath: Relative path of git working tree to repo's top directory.
  497. revisionExpr: The `revision` attribute of manifest.xml's project element.
  498. revisionId: git commit id for checking out.
  499. rebase: The `rebase` attribute of manifest.xml's project element.
  500. groups: The `groups` attribute of manifest.xml's project element.
  501. sync_c: The `sync-c` attribute of manifest.xml's project element.
  502. sync_s: The `sync-s` attribute of manifest.xml's project element.
  503. upstream: The `upstream` attribute of manifest.xml's project element.
  504. parent: The parent Project object.
  505. is_derived: False if the project was explicitly defined in the manifest;
  506. True if the project is a discovered submodule.
  507. dest_branch: The branch to which to push changes for review by default.
  508. optimized_fetch: If True, when a project is set to a sha1 revision, only
  509. fetch from the remote if the sha1 is not present locally.
  510. """
  511. self.manifest = manifest
  512. self.name = name
  513. self.remote = remote
  514. self.gitdir = gitdir.replace('\\', '/')
  515. self.objdir = objdir.replace('\\', '/')
  516. if worktree:
  517. self.worktree = worktree.replace('\\', '/')
  518. else:
  519. self.worktree = None
  520. self.relpath = relpath
  521. self.revisionExpr = revisionExpr
  522. if revisionId is None \
  523. and revisionExpr \
  524. and IsId(revisionExpr):
  525. self.revisionId = revisionExpr
  526. else:
  527. self.revisionId = revisionId
  528. self.rebase = rebase
  529. self.groups = groups
  530. self.sync_c = sync_c
  531. self.sync_s = sync_s
  532. self.clone_depth = clone_depth
  533. self.upstream = upstream
  534. self.parent = parent
  535. self.is_derived = is_derived
  536. self.optimized_fetch = optimized_fetch
  537. self.subprojects = []
  538. self.snapshots = {}
  539. self.copyfiles = []
  540. self.linkfiles = []
  541. self.annotations = []
  542. self.config = GitConfig.ForRepository(
  543. gitdir=self.gitdir,
  544. defaults=self.manifest.globalConfig)
  545. if self.worktree:
  546. self.work_git = self._GitGetByExec(self, bare=False, gitdir=gitdir)
  547. else:
  548. self.work_git = None
  549. self.bare_git = self._GitGetByExec(self, bare=True, gitdir=gitdir)
  550. self.bare_ref = GitRefs(gitdir)
  551. self.bare_objdir = self._GitGetByExec(self, bare=True, gitdir=objdir)
  552. self.dest_branch = dest_branch
  553. # This will be filled in if a project is later identified to be the
  554. # project containing repo hooks.
  555. self.enabled_repo_hooks = []
  556. @property
  557. def Derived(self):
  558. return self.is_derived
  559. @property
  560. def Exists(self):
  561. return os.path.isdir(self.gitdir) and os.path.isdir(self.objdir)
  562. @property
  563. def CurrentBranch(self):
  564. """Obtain the name of the currently checked out branch.
  565. The branch name omits the 'refs/heads/' prefix.
  566. None is returned if the project is on a detached HEAD.
  567. """
  568. b = self.work_git.GetHead()
  569. if b.startswith(R_HEADS):
  570. return b[len(R_HEADS):]
  571. return None
  572. def IsRebaseInProgress(self):
  573. w = self.worktree
  574. g = os.path.join(w, '.git')
  575. return os.path.exists(os.path.join(g, 'rebase-apply')) \
  576. or os.path.exists(os.path.join(g, 'rebase-merge')) \
  577. or os.path.exists(os.path.join(w, '.dotest'))
  578. def IsDirty(self, consider_untracked=True):
  579. """Is the working directory modified in some way?
  580. """
  581. self.work_git.update_index('-q',
  582. '--unmerged',
  583. '--ignore-missing',
  584. '--refresh')
  585. if self.work_git.DiffZ('diff-index', '-M', '--cached', HEAD):
  586. return True
  587. if self.work_git.DiffZ('diff-files'):
  588. return True
  589. if consider_untracked and self.work_git.LsOthers():
  590. return True
  591. return False
  592. _userident_name = None
  593. _userident_email = None
  594. @property
  595. def UserName(self):
  596. """Obtain the user's personal name.
  597. """
  598. if self._userident_name is None:
  599. self._LoadUserIdentity()
  600. return self._userident_name
  601. @property
  602. def UserEmail(self):
  603. """Obtain the user's email address. This is very likely
  604. to be their Gerrit login.
  605. """
  606. if self._userident_email is None:
  607. self._LoadUserIdentity()
  608. return self._userident_email
  609. def _LoadUserIdentity(self):
  610. u = self.bare_git.var('GIT_COMMITTER_IDENT')
  611. m = re.compile("^(.*) <([^>]*)> ").match(u)
  612. if m:
  613. self._userident_name = m.group(1)
  614. self._userident_email = m.group(2)
  615. else:
  616. self._userident_name = ''
  617. self._userident_email = ''
  618. def GetRemote(self, name):
  619. """Get the configuration for a single remote.
  620. """
  621. return self.config.GetRemote(name)
  622. def GetBranch(self, name):
  623. """Get the configuration for a single branch.
  624. """
  625. return self.config.GetBranch(name)
  626. def GetBranches(self):
  627. """Get all existing local branches.
  628. """
  629. current = self.CurrentBranch
  630. all_refs = self._allrefs
  631. heads = {}
  632. for name, ref_id in all_refs.items():
  633. if name.startswith(R_HEADS):
  634. name = name[len(R_HEADS):]
  635. b = self.GetBranch(name)
  636. b.current = name == current
  637. b.published = None
  638. b.revision = ref_id
  639. heads[name] = b
  640. for name, ref_id in all_refs.items():
  641. if name.startswith(R_PUB):
  642. name = name[len(R_PUB):]
  643. b = heads.get(name)
  644. if b:
  645. b.published = ref_id
  646. return heads
  647. def MatchesGroups(self, manifest_groups):
  648. """Returns true if the manifest groups specified at init should cause
  649. this project to be synced.
  650. Prefixing a manifest group with "-" inverts the meaning of a group.
  651. All projects are implicitly labelled with "all".
  652. labels are resolved in order. In the example case of
  653. project_groups: "all,group1,group2"
  654. manifest_groups: "-group1,group2"
  655. the project will be matched.
  656. The special manifest group "default" will match any project that
  657. does not have the special project group "notdefault"
  658. """
  659. expanded_manifest_groups = manifest_groups or ['default']
  660. expanded_project_groups = ['all'] + (self.groups or [])
  661. if not 'notdefault' in expanded_project_groups:
  662. expanded_project_groups += ['default']
  663. matched = False
  664. for group in expanded_manifest_groups:
  665. if group.startswith('-') and group[1:] in expanded_project_groups:
  666. matched = False
  667. elif group in expanded_project_groups:
  668. matched = True
  669. return matched
  670. ## Status Display ##
  671. def UncommitedFiles(self, get_all=True):
  672. """Returns a list of strings, uncommitted files in the git tree.
  673. Args:
  674. get_all: a boolean, if True - get information about all different
  675. uncommitted files. If False - return as soon as any kind of
  676. uncommitted files is detected.
  677. """
  678. details = []
  679. self.work_git.update_index('-q',
  680. '--unmerged',
  681. '--ignore-missing',
  682. '--refresh')
  683. if self.IsRebaseInProgress():
  684. details.append("rebase in progress")
  685. if not get_all:
  686. return details
  687. changes = self.work_git.DiffZ('diff-index', '--cached', HEAD).keys()
  688. if changes:
  689. details.extend(changes)
  690. if not get_all:
  691. return details
  692. changes = self.work_git.DiffZ('diff-files').keys()
  693. if changes:
  694. details.extend(changes)
  695. if not get_all:
  696. return details
  697. changes = self.work_git.LsOthers()
  698. if changes:
  699. details.extend(changes)
  700. return details
  701. def HasChanges(self):
  702. """Returns true if there are uncommitted changes.
  703. """
  704. if self.UncommitedFiles(get_all=False):
  705. return True
  706. else:
  707. return False
  708. def PrintWorkTreeStatus(self, output_redir=None):
  709. """Prints the status of the repository to stdout.
  710. Args:
  711. output: If specified, redirect the output to this object.
  712. """
  713. if not os.path.isdir(self.worktree):
  714. if output_redir == None:
  715. output_redir = sys.stdout
  716. print(file=output_redir)
  717. print('project %s/' % self.relpath, file=output_redir)
  718. print(' missing (run "repo sync")', file=output_redir)
  719. return
  720. self.work_git.update_index('-q',
  721. '--unmerged',
  722. '--ignore-missing',
  723. '--refresh')
  724. rb = self.IsRebaseInProgress()
  725. di = self.work_git.DiffZ('diff-index', '-M', '--cached', HEAD)
  726. df = self.work_git.DiffZ('diff-files')
  727. do = self.work_git.LsOthers()
  728. if not rb and not di and not df and not do and not self.CurrentBranch:
  729. return 'CLEAN'
  730. out = StatusColoring(self.config)
  731. if not output_redir == None:
  732. out.redirect(output_redir)
  733. out.project('project %-40s', self.relpath + '/ ')
  734. branch = self.CurrentBranch
  735. if branch is None:
  736. out.nobranch('(*** NO BRANCH ***)')
  737. else:
  738. out.branch('branch %s', branch)
  739. out.nl()
  740. if rb:
  741. out.important('prior sync failed; rebase still in progress')
  742. out.nl()
  743. paths = list()
  744. paths.extend(di.keys())
  745. paths.extend(df.keys())
  746. paths.extend(do)
  747. for p in sorted(set(paths)):
  748. try:
  749. i = di[p]
  750. except KeyError:
  751. i = None
  752. try:
  753. f = df[p]
  754. except KeyError:
  755. f = None
  756. if i:
  757. i_status = i.status.upper()
  758. else:
  759. i_status = '-'
  760. if f:
  761. f_status = f.status.lower()
  762. else:
  763. f_status = '-'
  764. if i and i.src_path:
  765. line = ' %s%s\t%s => %s (%s%%)' % (i_status, f_status,
  766. i.src_path, p, i.level)
  767. else:
  768. line = ' %s%s\t%s' % (i_status, f_status, p)
  769. if i and not f:
  770. out.added('%s', line)
  771. elif (i and f) or (not i and f):
  772. out.changed('%s', line)
  773. elif not i and not f:
  774. out.untracked('%s', line)
  775. else:
  776. out.write('%s', line)
  777. out.nl()
  778. return 'DIRTY'
  779. def PrintWorkTreeDiff(self, absolute_paths=False):
  780. """Prints the status of the repository to stdout.
  781. """
  782. out = DiffColoring(self.config)
  783. cmd = ['diff']
  784. if out.is_on:
  785. cmd.append('--color')
  786. cmd.append(HEAD)
  787. if absolute_paths:
  788. cmd.append('--src-prefix=a/%s/' % self.relpath)
  789. cmd.append('--dst-prefix=b/%s/' % self.relpath)
  790. cmd.append('--')
  791. p = GitCommand(self,
  792. cmd,
  793. capture_stdout=True,
  794. capture_stderr=True)
  795. has_diff = False
  796. for line in p.process.stdout:
  797. if not has_diff:
  798. out.nl()
  799. out.project('project %s/' % self.relpath)
  800. out.nl()
  801. has_diff = True
  802. print(line[:-1])
  803. p.Wait()
  804. ## Publish / Upload ##
  805. def WasPublished(self, branch, all_refs=None):
  806. """Was the branch published (uploaded) for code review?
  807. If so, returns the SHA-1 hash of the last published
  808. state for the branch.
  809. """
  810. key = R_PUB + branch
  811. if all_refs is None:
  812. try:
  813. return self.bare_git.rev_parse(key)
  814. except GitError:
  815. return None
  816. else:
  817. try:
  818. return all_refs[key]
  819. except KeyError:
  820. return None
  821. def CleanPublishedCache(self, all_refs=None):
  822. """Prunes any stale published refs.
  823. """
  824. if all_refs is None:
  825. all_refs = self._allrefs
  826. heads = set()
  827. canrm = {}
  828. for name, ref_id in all_refs.items():
  829. if name.startswith(R_HEADS):
  830. heads.add(name)
  831. elif name.startswith(R_PUB):
  832. canrm[name] = ref_id
  833. for name, ref_id in canrm.items():
  834. n = name[len(R_PUB):]
  835. if R_HEADS + n not in heads:
  836. self.bare_git.DeleteRef(name, ref_id)
  837. def GetUploadableBranches(self, selected_branch=None):
  838. """List any branches which can be uploaded for review.
  839. """
  840. heads = {}
  841. pubed = {}
  842. for name, ref_id in self._allrefs.items():
  843. if name.startswith(R_HEADS):
  844. heads[name[len(R_HEADS):]] = ref_id
  845. elif name.startswith(R_PUB):
  846. pubed[name[len(R_PUB):]] = ref_id
  847. ready = []
  848. for branch, ref_id in heads.items():
  849. if branch in pubed and pubed[branch] == ref_id:
  850. continue
  851. if selected_branch and branch != selected_branch:
  852. continue
  853. rb = self.GetUploadableBranch(branch)
  854. if rb:
  855. ready.append(rb)
  856. return ready
  857. def GetUploadableBranch(self, branch_name):
  858. """Get a single uploadable branch, or None.
  859. """
  860. branch = self.GetBranch(branch_name)
  861. base = branch.LocalMerge
  862. if branch.LocalMerge:
  863. rb = ReviewableBranch(self, branch, base)
  864. if rb.commits:
  865. return rb
  866. return None
  867. def UploadForReview(self, branch=None,
  868. people=([], []),
  869. auto_topic=False,
  870. draft=False,
  871. dest_branch=None):
  872. """Uploads the named branch for code review.
  873. """
  874. if branch is None:
  875. branch = self.CurrentBranch
  876. if branch is None:
  877. raise GitError('not currently on a branch')
  878. branch = self.GetBranch(branch)
  879. if not branch.LocalMerge:
  880. raise GitError('branch %s does not track a remote' % branch.name)
  881. if not branch.remote.review:
  882. raise GitError('remote %s has no review url' % branch.remote.name)
  883. if dest_branch is None:
  884. dest_branch = self.dest_branch
  885. if dest_branch is None:
  886. dest_branch = branch.merge
  887. if not dest_branch.startswith(R_HEADS):
  888. dest_branch = R_HEADS + dest_branch
  889. if not branch.remote.projectname:
  890. branch.remote.projectname = self.name
  891. branch.remote.Save()
  892. url = branch.remote.ReviewUrl(self.UserEmail)
  893. if url is None:
  894. raise UploadError('review not configured')
  895. cmd = ['push']
  896. if url.startswith('ssh://'):
  897. rp = ['gerrit receive-pack']
  898. for e in people[0]:
  899. rp.append('--reviewer=%s' % sq(e))
  900. for e in people[1]:
  901. rp.append('--cc=%s' % sq(e))
  902. cmd.append('--receive-pack=%s' % " ".join(rp))
  903. cmd.append(url)
  904. if dest_branch.startswith(R_HEADS):
  905. dest_branch = dest_branch[len(R_HEADS):]
  906. upload_type = 'for'
  907. if draft:
  908. upload_type = 'drafts'
  909. ref_spec = '%s:refs/%s/%s' % (R_HEADS + branch.name, upload_type,
  910. dest_branch)
  911. if auto_topic:
  912. ref_spec = ref_spec + '/' + branch.name
  913. if not url.startswith('ssh://'):
  914. rp = ['r=%s' % p for p in people[0]] + \
  915. ['cc=%s' % p for p in people[1]]
  916. if rp:
  917. ref_spec = ref_spec + '%' + ','.join(rp)
  918. cmd.append(ref_spec)
  919. if GitCommand(self, cmd, bare=True).Wait() != 0:
  920. raise UploadError('Upload failed')
  921. msg = "posted to %s for %s" % (branch.remote.review, dest_branch)
  922. self.bare_git.UpdateRef(R_PUB + branch.name,
  923. R_HEADS + branch.name,
  924. message=msg)
  925. ## Sync ##
  926. def _ExtractArchive(self, tarpath, path=None):
  927. """Extract the given tar on its current location
  928. Args:
  929. - tarpath: The path to the actual tar file
  930. """
  931. try:
  932. with tarfile.open(tarpath, 'r') as tar:
  933. tar.extractall(path=path)
  934. return True
  935. except (IOError, tarfile.TarError) as e:
  936. print("error: Cannot extract archive %s: "
  937. "%s" % (tarpath, str(e)), file=sys.stderr)
  938. return False
  939. def Sync_NetworkHalf(self,
  940. quiet=False,
  941. is_new=None,
  942. current_branch_only=False,
  943. force_sync=False,
  944. clone_bundle=True,
  945. no_tags=False,
  946. archive=False,
  947. optimized_fetch=False):
  948. """Perform only the network IO portion of the sync process.
  949. Local working directory/branch state is not affected.
  950. """
  951. if archive and not isinstance(self, MetaProject):
  952. if self.remote.url.startswith(('http://', 'https://')):
  953. print("error: %s: Cannot fetch archives from http/https "
  954. "remotes." % self.name, file=sys.stderr)
  955. return False
  956. name = self.relpath.replace('\\', '/')
  957. name = name.replace('/', '_')
  958. tarpath = '%s.tar' % name
  959. topdir = self.manifest.topdir
  960. try:
  961. self._FetchArchive(tarpath, cwd=topdir)
  962. except GitError as e:
  963. print('error: %s' % str(e), file=sys.stderr)
  964. return False
  965. # From now on, we only need absolute tarpath
  966. tarpath = os.path.join(topdir, tarpath)
  967. if not self._ExtractArchive(tarpath, path=topdir):
  968. return False
  969. try:
  970. os.remove(tarpath)
  971. except OSError as e:
  972. print("warn: Cannot remove archive %s: "
  973. "%s" % (tarpath, str(e)), file=sys.stderr)
  974. self._CopyAndLinkFiles()
  975. return True
  976. if is_new is None:
  977. is_new = not self.Exists
  978. if is_new:
  979. self._InitGitDir(force_sync=force_sync)
  980. else:
  981. self._UpdateHooks()
  982. self._InitRemote()
  983. if is_new:
  984. alt = os.path.join(self.gitdir, 'objects/info/alternates')
  985. try:
  986. fd = open(alt, 'rb')
  987. try:
  988. alt_dir = fd.readline().rstrip()
  989. finally:
  990. fd.close()
  991. except IOError:
  992. alt_dir = None
  993. else:
  994. alt_dir = None
  995. if clone_bundle \
  996. and alt_dir is None \
  997. and self._ApplyCloneBundle(initial=is_new, quiet=quiet):
  998. is_new = False
  999. if not current_branch_only:
  1000. if self.sync_c:
  1001. current_branch_only = True
  1002. elif not self.manifest._loaded:
  1003. # Manifest cannot check defaults until it syncs.
  1004. current_branch_only = False
  1005. elif self.manifest.default.sync_c:
  1006. current_branch_only = True
  1007. need_to_fetch = not (optimized_fetch and \
  1008. (ID_RE.match(self.revisionExpr) and self._CheckForSha1()))
  1009. if (need_to_fetch
  1010. and not self._RemoteFetch(initial=is_new, quiet=quiet, alt_dir=alt_dir,
  1011. current_branch_only=current_branch_only,
  1012. no_tags=no_tags)):
  1013. return False
  1014. if self.worktree:
  1015. self._InitMRef()
  1016. else:
  1017. self._InitMirrorHead()
  1018. try:
  1019. os.remove(os.path.join(self.gitdir, 'FETCH_HEAD'))
  1020. except OSError:
  1021. pass
  1022. return True
  1023. def PostRepoUpgrade(self):
  1024. self._InitHooks()
  1025. def _CopyAndLinkFiles(self):
  1026. for copyfile in self.copyfiles:
  1027. copyfile._Copy()
  1028. for linkfile in self.linkfiles:
  1029. linkfile._Link()
  1030. def GetCommitRevisionId(self):
  1031. """Get revisionId of a commit.
  1032. Use this method instead of GetRevisionId to get the id of the commit rather
  1033. than the id of the current git object (for example, a tag)
  1034. """
  1035. if not self.revisionExpr.startswith(R_TAGS):
  1036. return self.GetRevisionId(self._allrefs)
  1037. try:
  1038. return self.bare_git.rev_list(self.revisionExpr, '-1')[0]
  1039. except GitError:
  1040. raise ManifestInvalidRevisionError(
  1041. 'revision %s in %s not found' % (self.revisionExpr,
  1042. self.name))
  1043. def GetRevisionId(self, all_refs=None):
  1044. if self.revisionId:
  1045. return self.revisionId
  1046. rem = self.GetRemote(self.remote.name)
  1047. rev = rem.ToLocal(self.revisionExpr)
  1048. if all_refs is not None and rev in all_refs:
  1049. return all_refs[rev]
  1050. try:
  1051. return self.bare_git.rev_parse('--verify', '%s^0' % rev)
  1052. except GitError:
  1053. raise ManifestInvalidRevisionError(
  1054. 'revision %s in %s not found' % (self.revisionExpr,
  1055. self.name))
  1056. def Sync_LocalHalf(self, syncbuf, force_sync=False):
  1057. """Perform only the local IO portion of the sync process.
  1058. Network access is not required.
  1059. """
  1060. self._InitWorkTree(force_sync=force_sync)
  1061. all_refs = self.bare_ref.all
  1062. self.CleanPublishedCache(all_refs)
  1063. revid = self.GetRevisionId(all_refs)
  1064. def _doff():
  1065. self._FastForward(revid)
  1066. self._CopyAndLinkFiles()
  1067. head = self.work_git.GetHead()
  1068. if head.startswith(R_HEADS):
  1069. branch = head[len(R_HEADS):]
  1070. try:
  1071. head = all_refs[head]
  1072. except KeyError:
  1073. head = None
  1074. else:
  1075. branch = None
  1076. if branch is None or syncbuf.detach_head:
  1077. # Currently on a detached HEAD. The user is assumed to
  1078. # not have any local modifications worth worrying about.
  1079. #
  1080. if self.IsRebaseInProgress():
  1081. syncbuf.fail(self, _PriorSyncFailedError())
  1082. return
  1083. if head == revid:
  1084. # No changes; don't do anything further.
  1085. # Except if the head needs to be detached
  1086. #
  1087. if not syncbuf.detach_head:
  1088. return
  1089. else:
  1090. lost = self._revlist(not_rev(revid), HEAD)
  1091. if lost:
  1092. syncbuf.info(self, "discarding %d commits", len(lost))
  1093. try:
  1094. self._Checkout(revid, quiet=True)
  1095. except GitError as e:
  1096. syncbuf.fail(self, e)
  1097. return
  1098. self._CopyAndLinkFiles()
  1099. return
  1100. if head == revid:
  1101. # No changes; don't do anything further.
  1102. #
  1103. return
  1104. branch = self.GetBranch(branch)
  1105. if not branch.LocalMerge:
  1106. # The current branch has no tracking configuration.
  1107. # Jump off it to a detached HEAD.
  1108. #
  1109. syncbuf.info(self,
  1110. "leaving %s; does not track upstream",
  1111. branch.name)
  1112. try:
  1113. self._Checkout(revid, quiet=True)
  1114. except GitError as e:
  1115. syncbuf.fail(self, e)
  1116. return
  1117. self._CopyAndLinkFiles()
  1118. return
  1119. upstream_gain = self._revlist(not_rev(HEAD), revid)
  1120. pub = self.WasPublished(branch.name, all_refs)
  1121. if pub:
  1122. not_merged = self._revlist(not_rev(revid), pub)
  1123. if not_merged:
  1124. if upstream_gain:
  1125. # The user has published this branch and some of those
  1126. # commits are not yet merged upstream. We do not want
  1127. # to rewrite the published commits so we punt.
  1128. #
  1129. syncbuf.fail(self,
  1130. "branch %s is published (but not merged) and is now %d commits behind"
  1131. % (branch.name, len(upstream_gain)))
  1132. return
  1133. elif pub == head:
  1134. # All published commits are merged, and thus we are a
  1135. # strict subset. We can fast-forward safely.
  1136. #
  1137. syncbuf.later1(self, _doff)
  1138. return
  1139. # Examine the local commits not in the remote. Find the
  1140. # last one attributed to this user, if any.
  1141. #
  1142. local_changes = self._revlist(not_rev(revid), HEAD, format='%H %ce')
  1143. last_mine = None
  1144. cnt_mine = 0
  1145. for commit in local_changes:
  1146. commit_id, committer_email = commit.decode('utf-8').split(' ', 1)
  1147. if committer_email == self.UserEmail:
  1148. last_mine = commit_id
  1149. cnt_mine += 1
  1150. if not upstream_gain and cnt_mine == len(local_changes):
  1151. return
  1152. if self.IsDirty(consider_untracked=False):
  1153. syncbuf.fail(self, _DirtyError())
  1154. return
  1155. # If the upstream switched on us, warn the user.
  1156. #
  1157. if branch.merge != self.revisionExpr:
  1158. if branch.merge and self.revisionExpr:
  1159. syncbuf.info(self,
  1160. 'manifest switched %s...%s',
  1161. branch.merge,
  1162. self.revisionExpr)
  1163. elif branch.merge:
  1164. syncbuf.info(self,
  1165. 'manifest no longer tracks %s',
  1166. branch.merge)
  1167. if cnt_mine < len(local_changes):
  1168. # Upstream rebased. Not everything in HEAD
  1169. # was created by this user.
  1170. #
  1171. syncbuf.info(self,
  1172. "discarding %d commits removed from upstream",
  1173. len(local_changes) - cnt_mine)
  1174. branch.remote = self.GetRemote(self.remote.name)
  1175. if not ID_RE.match(self.revisionExpr):
  1176. # in case of manifest sync the revisionExpr might be a SHA1
  1177. branch.merge = self.revisionExpr
  1178. if not branch.merge.startswith('refs/'):
  1179. branch.merge = R_HEADS + branch.merge
  1180. branch.Save()
  1181. if cnt_mine > 0 and self.rebase:
  1182. def _dorebase():
  1183. self._Rebase(upstream='%s^1' % last_mine, onto=revid)
  1184. self._CopyAndLinkFiles()
  1185. syncbuf.later2(self, _dorebase)
  1186. elif local_changes:
  1187. try:
  1188. self._ResetHard(revid)
  1189. self._CopyAndLinkFiles()
  1190. except GitError as e:
  1191. syncbuf.fail(self, e)
  1192. return
  1193. else:
  1194. syncbuf.later1(self, _doff)
  1195. def AddCopyFile(self, src, dest, absdest):
  1196. # dest should already be an absolute path, but src is project relative
  1197. # make src an absolute path
  1198. abssrc = os.path.join(self.worktree, src)
  1199. self.copyfiles.append(_CopyFile(src, dest, abssrc, absdest))
  1200. def AddLinkFile(self, src, dest, absdest):
  1201. # dest should already be an absolute path, but src is project relative
  1202. # make src relative path to dest
  1203. absdestdir = os.path.dirname(absdest)
  1204. relsrc = os.path.relpath(os.path.join(self.worktree, src), absdestdir)
  1205. self.linkfiles.append(_LinkFile(self.worktree, src, dest, relsrc, absdest))
  1206. def AddAnnotation(self, name, value, keep):
  1207. self.annotations.append(_Annotation(name, value, keep))
  1208. def DownloadPatchSet(self, change_id, patch_id):
  1209. """Download a single patch set of a single change to FETCH_HEAD.
  1210. """
  1211. remote = self.GetRemote(self.remote.name)
  1212. cmd = ['fetch', remote.name]
  1213. cmd.append('refs/changes/%2.2d/%d/%d' \
  1214. % (change_id % 100, change_id, patch_id))
  1215. if GitCommand(self, cmd, bare=True).Wait() != 0:
  1216. return None
  1217. return DownloadedChange(self,
  1218. self.GetRevisionId(),
  1219. change_id,
  1220. patch_id,
  1221. self.bare_git.rev_parse('FETCH_HEAD'))
  1222. ## Branch Management ##
  1223. def StartBranch(self, name):
  1224. """Create a new branch off the manifest's revision.
  1225. """
  1226. head = self.work_git.GetHead()
  1227. if head == (R_HEADS + name):
  1228. return True
  1229. all_refs = self.bare_ref.all
  1230. if R_HEADS + name in all_refs:
  1231. return GitCommand(self,
  1232. ['checkout', name, '--'],
  1233. capture_stdout=True,
  1234. capture_stderr=True).Wait() == 0
  1235. branch = self.GetBranch(name)
  1236. branch.remote = self.GetRemote(self.remote.name)
  1237. branch.merge = self.revisionExpr
  1238. if not branch.merge.startswith('refs/') and not ID_RE.match(self.revisionExpr):
  1239. branch.merge = R_HEADS + self.revisionExpr
  1240. revid = self.GetRevisionId(all_refs)
  1241. if head.startswith(R_HEADS):
  1242. try:
  1243. head = all_refs[head]
  1244. except KeyError:
  1245. head = None
  1246. if revid and head and revid == head:
  1247. ref = os.path.join(self.gitdir, R_HEADS + name)
  1248. try:
  1249. os.makedirs(os.path.dirname(ref))
  1250. except OSError:
  1251. pass
  1252. _lwrite(ref, '%s\n' % revid)
  1253. _lwrite(os.path.join(self.worktree, '.git', HEAD),
  1254. 'ref: %s%s\n' % (R_HEADS, name))
  1255. branch.Save()
  1256. return True
  1257. if GitCommand(self,
  1258. ['checkout', '-b', branch.name, revid],
  1259. capture_stdout=True,
  1260. capture_stderr=True).Wait() == 0:
  1261. branch.Save()
  1262. return True
  1263. return False
  1264. def CheckoutBranch(self, name):
  1265. """Checkout a local topic branch.
  1266. Args:
  1267. name: The name of the branch to checkout.
  1268. Returns:
  1269. True if the checkout succeeded; False if it didn't; None if the branch
  1270. didn't exist.
  1271. """
  1272. rev = R_HEADS + name
  1273. head = self.work_git.GetHead()
  1274. if head == rev:
  1275. # Already on the branch
  1276. #
  1277. return True
  1278. all_refs = self.bare_ref.all
  1279. try:
  1280. revid = all_refs[rev]
  1281. except KeyError:
  1282. # Branch does not exist in this project
  1283. #
  1284. return None
  1285. if head.startswith(R_HEADS):
  1286. try:
  1287. head = all_refs[head]
  1288. except KeyError:
  1289. head = None
  1290. if head == revid:
  1291. # Same revision; just update HEAD to point to the new
  1292. # target branch, but otherwise take no other action.
  1293. #
  1294. _lwrite(os.path.join(self.worktree, '.git', HEAD),
  1295. 'ref: %s%s\n' % (R_HEADS, name))
  1296. return True
  1297. return GitCommand(self,
  1298. ['checkout', name, '--'],
  1299. capture_stdout=True,
  1300. capture_stderr=True).Wait() == 0
  1301. def AbandonBranch(self, name):
  1302. """Destroy a local topic branch.
  1303. Args:
  1304. name: The name of the branch to abandon.
  1305. Returns:
  1306. True if the abandon succeeded; False if it didn't; None if the branch
  1307. didn't exist.
  1308. """
  1309. rev = R_HEADS + name
  1310. all_refs = self.bare_ref.all
  1311. if rev not in all_refs:
  1312. # Doesn't exist
  1313. return None
  1314. head = self.work_git.GetHead()
  1315. if head == rev:
  1316. # We can't destroy the branch while we are sitting
  1317. # on it. Switch to a detached HEAD.
  1318. #
  1319. head = all_refs[head]
  1320. revid = self.GetRevisionId(all_refs)
  1321. if head == revid:
  1322. _lwrite(os.path.join(self.worktree, '.git', HEAD),
  1323. '%s\n' % revid)
  1324. else:
  1325. self._Checkout(revid, quiet=True)
  1326. return GitCommand(self,
  1327. ['branch', '-D', name],
  1328. capture_stdout=True,
  1329. capture_stderr=True).Wait() == 0
  1330. def PruneHeads(self):
  1331. """Prune any topic branches already merged into upstream.
  1332. """
  1333. cb = self.CurrentBranch
  1334. kill = []
  1335. left = self._allrefs
  1336. for name in left.keys():
  1337. if name.startswith(R_HEADS):
  1338. name = name[len(R_HEADS):]
  1339. if cb is None or name != cb:
  1340. kill.append(name)
  1341. rev = self.GetRevisionId(left)
  1342. if cb is not None \
  1343. and not self._revlist(HEAD + '...' + rev) \
  1344. and not self.IsDirty(consider_untracked=False):
  1345. self.work_git.DetachHead(HEAD)
  1346. kill.append(cb)
  1347. if kill:
  1348. old = self.bare_git.GetHead()
  1349. if old is None:
  1350. old = 'refs/heads/please_never_use_this_as_a_branch_name'
  1351. try:
  1352. self.bare_git.DetachHead(rev)
  1353. b = ['branch', '-d']
  1354. b.extend(kill)
  1355. b = GitCommand(self, b, bare=True,
  1356. capture_stdout=True,
  1357. capture_stderr=True)
  1358. b.Wait()
  1359. finally:
  1360. self.bare_git.SetHead(old)
  1361. left = self._allrefs
  1362. for branch in kill:
  1363. if (R_HEADS + branch) not in left:
  1364. self.CleanPublishedCache()
  1365. break
  1366. if cb and cb not in kill:
  1367. kill.append(cb)
  1368. kill.sort()
  1369. kept = []
  1370. for branch in kill:
  1371. if R_HEADS + branch in left:
  1372. branch = self.GetBranch(branch)
  1373. base = branch.LocalMerge
  1374. if not base:
  1375. base = rev
  1376. kept.append(ReviewableBranch(self, branch, base))
  1377. return kept
  1378. ## Submodule Management ##
  1379. def GetRegisteredSubprojects(self):
  1380. result = []
  1381. def rec(subprojects):
  1382. if not subprojects:
  1383. return
  1384. result.extend(subprojects)
  1385. for p in subprojects:
  1386. rec(p.subprojects)
  1387. rec(self.subprojects)
  1388. return result
  1389. def _GetSubmodules(self):
  1390. # Unfortunately we cannot call `git submodule status --recursive` here
  1391. # because the working tree might not exist yet, and it cannot be used
  1392. # without a working tree in its current implementation.
  1393. def get_submodules(gitdir, rev):
  1394. # Parse .gitmodules for submodule sub_paths and sub_urls
  1395. sub_paths, sub_urls = parse_gitmodules(gitdir, rev)
  1396. if not sub_paths:
  1397. return []
  1398. # Run `git ls-tree` to read SHAs of submodule object, which happen to be
  1399. # revision of submodule repository
  1400. sub_revs = git_ls_tree(gitdir, rev, sub_paths)
  1401. submodules = []
  1402. for sub_path, sub_url in zip(sub_paths, sub_urls):
  1403. try:
  1404. sub_rev = sub_revs[sub_path]
  1405. except KeyError:
  1406. # Ignore non-exist submodules
  1407. continue
  1408. submodules.append((sub_rev, sub_path, sub_url))
  1409. return submodules
  1410. re_path = re.compile(r'^submodule\.([^.]+)\.path=(.*)$')
  1411. re_url = re.compile(r'^submodule\.([^.]+)\.url=(.*)$')
  1412. def parse_gitmodules(gitdir, rev):
  1413. cmd = ['cat-file', 'blob', '%s:.gitmodules' % rev]
  1414. try:
  1415. p = GitCommand(None, cmd, capture_stdout=True, capture_stderr=True,
  1416. bare=True, gitdir=gitdir)
  1417. except GitError:
  1418. return [], []
  1419. if p.Wait() != 0:
  1420. return [], []
  1421. gitmodules_lines = []
  1422. fd, temp_gitmodules_path = tempfile.mkstemp()
  1423. try:
  1424. os.write(fd, p.stdout)
  1425. os.close(fd)
  1426. cmd = ['config', '--file', temp_gitmodules_path, '--list']
  1427. p = GitCommand(None, cmd, capture_stdout=True, capture_stderr=True,
  1428. bare=True, gitdir=gitdir)
  1429. if p.Wait() != 0:
  1430. return [], []
  1431. gitmodules_lines = p.stdout.split('\n')
  1432. except GitError:
  1433. return [], []
  1434. finally:
  1435. os.remove(temp_gitmodules_path)
  1436. names = set()
  1437. paths = {}
  1438. urls = {}
  1439. for line in gitmodules_lines:
  1440. if not line:
  1441. continue
  1442. m = re_path.match(line)
  1443. if m:
  1444. names.add(m.group(1))
  1445. paths[m.group(1)] = m.group(2)
  1446. continue
  1447. m = re_url.match(line)
  1448. if m:
  1449. names.add(m.group(1))
  1450. urls[m.group(1)] = m.group(2)
  1451. continue
  1452. names = sorted(names)
  1453. return ([paths.get(name, '') for name in names],
  1454. [urls.get(name, '') for name in names])
  1455. def git_ls_tree(gitdir, rev, paths):
  1456. cmd = ['ls-tree', rev, '--']
  1457. cmd.extend(paths)
  1458. try:
  1459. p = GitCommand(None, cmd, capture_stdout=True, capture_stderr=True,
  1460. bare=True, gitdir=gitdir)
  1461. except GitError:
  1462. return []
  1463. if p.Wait() != 0:
  1464. return []
  1465. objects = {}
  1466. for line in p.stdout.split('\n'):
  1467. if not line.strip():
  1468. continue
  1469. object_rev, object_path = line.split()[2:4]
  1470. objects[object_path] = object_rev
  1471. return objects
  1472. try:
  1473. rev = self.GetRevisionId()
  1474. except GitError:
  1475. return []
  1476. return get_submodules(self.gitdir, rev)
  1477. def GetDerivedSubprojects(self):
  1478. result = []
  1479. if not self.Exists:
  1480. # If git repo does not exist yet, querying its submodules will
  1481. # mess up its states; so return here.
  1482. return result
  1483. for rev, path, url in self._GetSubmodules():
  1484. name = self.manifest.GetSubprojectName(self, path)
  1485. relpath, worktree, gitdir, objdir = \
  1486. self.manifest.GetSubprojectPaths(self, name, path)
  1487. project = self.manifest.paths.get(relpath)
  1488. if project:
  1489. result.extend(project.GetDerivedSubprojects())
  1490. continue
  1491. remote = RemoteSpec(self.remote.name,
  1492. url=url,
  1493. review=self.remote.review,
  1494. revision=self.remote.revision)
  1495. subproject = Project(manifest=self.manifest,
  1496. name=name,
  1497. remote=remote,
  1498. gitdir=gitdir,
  1499. objdir=objdir,
  1500. worktree=worktree,
  1501. relpath=relpath,
  1502. revisionExpr=self.revisionExpr,
  1503. revisionId=rev,
  1504. rebase=self.rebase,
  1505. groups=self.groups,
  1506. sync_c=self.sync_c,
  1507. sync_s=self.sync_s,
  1508. parent=self,
  1509. is_derived=True)
  1510. result.append(subproject)
  1511. result.extend(subproject.GetDerivedSubprojects())
  1512. return result
  1513. ## Direct Git Commands ##
  1514. def _CheckForSha1(self):
  1515. try:
  1516. # if revision (sha or tag) is not present then following function
  1517. # throws an error.
  1518. self.bare_git.rev_parse('--verify', '%s^0' % self.revisionExpr)
  1519. return True
  1520. except GitError:
  1521. # There is no such persistent revision. We have to fetch it.
  1522. return False
  1523. def _FetchArchive(self, tarpath, cwd=None):
  1524. cmd = ['archive', '-v', '-o', tarpath]
  1525. cmd.append('--remote=%s' % self.remote.url)
  1526. cmd.append('--prefix=%s/' % self.relpath)
  1527. cmd.append(self.revisionExpr)
  1528. command = GitCommand(self, cmd, cwd=cwd,
  1529. capture_stdout=True,
  1530. capture_stderr=True)
  1531. if command.Wait() != 0:
  1532. raise GitError('git archive %s: %s' % (self.name, command.stderr))
  1533. def _RemoteFetch(self, name=None,
  1534. current_branch_only=False,
  1535. initial=False,
  1536. quiet=False,
  1537. alt_dir=None,
  1538. no_tags=False):
  1539. is_sha1 = False
  1540. tag_name = None
  1541. depth = None
  1542. # The depth should not be used when fetching to a mirror because
  1543. # it will result in a shallow repository that cannot be cloned or
  1544. # fetched from.
  1545. if not self.manifest.IsMirror:
  1546. if self.clone_depth:
  1547. depth = self.clone_depth
  1548. else:
  1549. depth = self.manifest.manifestProject.config.GetString('repo.depth')
  1550. # The repo project should never be synced with partial depth
  1551. if self.relpath == '.repo/repo':
  1552. depth = None
  1553. if depth:
  1554. current_branch_only = True
  1555. if ID_RE.match(self.revisionExpr) is not None:
  1556. is_sha1 = True
  1557. if current_branch_only:
  1558. if self.revisionExpr.startswith(R_TAGS):
  1559. # this is a tag and its sha1 value should never change
  1560. tag_name = self.revisionExpr[len(R_TAGS):]
  1561. if is_sha1 or tag_name is not None:
  1562. if self._CheckForSha1():
  1563. return True
  1564. if is_sha1 and not depth:
  1565. # When syncing a specific commit and --depth is not set:
  1566. # * if upstream is explicitly specified and is not a sha1, fetch only
  1567. # upstream as users expect only upstream to be fetch.
  1568. # Note: The commit might not be in upstream in which case the sync
  1569. # will fail.
  1570. # * otherwise, fetch all branches to make sure we end up with the
  1571. # specific commit.
  1572. current_branch_only = self.upstream and not ID_RE.match(self.upstream)
  1573. if not name:
  1574. name = self.remote.name
  1575. ssh_proxy = False
  1576. remote = self.GetRemote(name)
  1577. if remote.PreConnectFetch():
  1578. ssh_proxy = True
  1579. if initial:
  1580. if alt_dir and 'objects' == os.path.basename(alt_dir):
  1581. ref_dir = os.path.dirname(alt_dir)
  1582. packed_refs = os.path.join(self.gitdir, 'packed-refs')
  1583. remote = self.GetRemote(name)
  1584. all_refs = self.bare_ref.all
  1585. ids = set(all_refs.values())
  1586. tmp = set()
  1587. for r, ref_id in GitRefs(ref_dir).all.items():
  1588. if r not in all_refs:
  1589. if r.startswith(R_TAGS) or remote.WritesTo(r):
  1590. all_refs[r] = ref_id
  1591. ids.add(ref_id)
  1592. continue
  1593. if ref_id in ids:
  1594. continue
  1595. r = 'refs/_alt/%s' % ref_id
  1596. all_refs[r] = ref_id
  1597. ids.add(ref_id)
  1598. tmp.add(r)
  1599. tmp_packed = ''
  1600. old_packed = ''
  1601. for r in sorted(all_refs):
  1602. line = '%s %s\n' % (all_refs[r], r)
  1603. tmp_packed += line
  1604. if r not in tmp:
  1605. old_packed += line
  1606. _lwrite(packed_refs, tmp_packed)
  1607. else:
  1608. alt_dir = None
  1609. cmd = ['fetch']
  1610. if depth:
  1611. cmd.append('--depth=%s' % depth)
  1612. else:
  1613. # If this repo has shallow objects, then we don't know which refs have
  1614. # shallow objects or not. Tell git to unshallow all fetched refs. Don't
  1615. # do this with projects that don't have shallow objects, since it is less
  1616. # efficient.
  1617. if os.path.exists(os.path.join(self.gitdir, 'shallow')):
  1618. cmd.append('--depth=2147483647')
  1619. if quiet:
  1620. cmd.append('--quiet')
  1621. if not self.worktree:
  1622. cmd.append('--update-head-ok')
  1623. cmd.append(name)
  1624. # If using depth then we should not get all the tags since they may
  1625. # be outside of the depth.
  1626. if no_tags or depth:
  1627. cmd.append('--no-tags')
  1628. else:
  1629. cmd.append('--tags')
  1630. spec = []
  1631. if not current_branch_only:
  1632. # Fetch whole repo
  1633. spec.append(str((u'+refs/heads/*:') + remote.ToLocal('refs/heads/*')))
  1634. elif tag_name is not None:
  1635. spec.append('tag')
  1636. spec.append(tag_name)
  1637. if not self.manifest.IsMirror:
  1638. branch = self.revisionExpr
  1639. if is_sha1 and depth and git_require((1, 8, 3)):
  1640. # Shallow checkout of a specific commit, fetch from that commit and not
  1641. # the heads only as the commit might be deeper in the history.
  1642. spec.append(branch)
  1643. else:
  1644. if is_sha1:
  1645. branch = self.upstream
  1646. if branch is not None and branch.strip():
  1647. if not branch.startswith('refs/'):
  1648. branch = R_HEADS + branch
  1649. spec.append(str((u'+%s:' % branch) + remote.ToLocal(branch)))
  1650. cmd.extend(spec)
  1651. ok = False
  1652. for _i in range(2):
  1653. gitcmd = GitCommand(self, cmd, bare=True, ssh_proxy=ssh_proxy)
  1654. ret = gitcmd.Wait()
  1655. if ret == 0:
  1656. ok = True
  1657. break
  1658. # If needed, run the 'git remote prune' the first time through the loop
  1659. elif (not _i and
  1660. "error:" in gitcmd.stderr and
  1661. "git remote prune" in gitcmd.stderr):
  1662. prunecmd = GitCommand(self, ['remote', 'prune', name], bare=True,
  1663. ssh_proxy=ssh_proxy)
  1664. ret = prunecmd.Wait()
  1665. if ret:
  1666. break
  1667. continue
  1668. elif current_branch_only and is_sha1 and ret == 128:
  1669. # Exit code 128 means "couldn't find the ref you asked for"; if we're in sha1
  1670. # mode, we just tried sync'ing from the upstream field; it doesn't exist, thus
  1671. # abort the optimization attempt and do a full sync.
  1672. break
  1673. elif ret < 0:
  1674. # Git died with a signal, exit immediately
  1675. break
  1676. time.sleep(random.randint(30, 45))
  1677. if initial:
  1678. if alt_dir:
  1679. if old_packed != '':
  1680. _lwrite(packed_refs, old_packed)
  1681. else:
  1682. os.remove(packed_refs)
  1683. self.bare_git.pack_refs('--all', '--prune')
  1684. if is_sha1 and current_branch_only and self.upstream:
  1685. # We just synced the upstream given branch; verify we
  1686. # got what we wanted, else trigger a second run of all
  1687. # refs.
  1688. if not self._CheckForSha1():
  1689. if not depth:
  1690. # Avoid infinite recursion when depth is True (since depth implies
  1691. # current_branch_only)
  1692. return self._RemoteFetch(name=name, current_branch_only=False,
  1693. initial=False, quiet=quiet, alt_dir=alt_dir)
  1694. if self.clone_depth:
  1695. self.clone_depth = None
  1696. return self._RemoteFetch(name=name, current_branch_only=current_branch_only,
  1697. initial=False, quiet=quiet, alt_dir=alt_dir)
  1698. return ok
  1699. def _ApplyCloneBundle(self, initial=False, quiet=False):
  1700. if initial and (self.manifest.manifestProject.config.GetString('repo.depth') or self.clone_depth):
  1701. return False
  1702. remote = self.GetRemote(self.remote.name)
  1703. bundle_url = remote.url + '/clone.bundle'
  1704. bundle_url = GitConfig.ForUser().UrlInsteadOf(bundle_url)
  1705. if GetSchemeFromUrl(bundle_url) not in (
  1706. 'http', 'https', 'persistent-http', 'persistent-https'):
  1707. return False
  1708. bundle_dst = os.path.join(self.gitdir, 'clone.bundle')
  1709. bundle_tmp = os.path.join(self.gitdir, 'clone.bundle.tmp')
  1710. exist_dst = os.path.exists(bundle_dst)
  1711. exist_tmp = os.path.exists(bundle_tmp)
  1712. if not initial and not exist_dst and not exist_tmp:
  1713. return False
  1714. if not exist_dst:
  1715. exist_dst = self._FetchBundle(bundle_url, bundle_tmp, bundle_dst, quiet)
  1716. if not exist_dst:
  1717. return False
  1718. cmd = ['fetch']
  1719. if quiet:
  1720. cmd.append('--quiet')
  1721. if not self.worktree:
  1722. cmd.append('--update-head-ok')
  1723. cmd.append(bundle_dst)
  1724. for f in remote.fetch:
  1725. cmd.append(str(f))
  1726. cmd.append('refs/tags/*:refs/tags/*')
  1727. ok = GitCommand(self, cmd, bare=True).Wait() == 0
  1728. if os.path.exists(bundle_dst):
  1729. os.remove(bundle_dst)
  1730. if os.path.exists(bundle_tmp):
  1731. os.remove(bundle_tmp)
  1732. return ok
  1733. def _FetchBundle(self, srcUrl, tmpPath, dstPath, quiet):
  1734. if os.path.exists(dstPath):
  1735. os.remove(dstPath)
  1736. cmd = ['curl', '--fail', '--output', tmpPath, '--netrc', '--location']
  1737. if quiet:
  1738. cmd += ['--silent']
  1739. if os.path.exists(tmpPath):
  1740. size = os.stat(tmpPath).st_size
  1741. if size >= 1024:
  1742. cmd += ['--continue-at', '%d' % (size,)]
  1743. else:
  1744. os.remove(tmpPath)
  1745. if 'http_proxy' in os.environ and 'darwin' == sys.platform:
  1746. cmd += ['--proxy', os.environ['http_proxy']]
  1747. with GetUrlCookieFile(srcUrl, quiet) as (cookiefile, proxy):
  1748. if cookiefile:
  1749. cmd += ['--cookie', cookiefile, '--cookie-jar', cookiefile]
  1750. if srcUrl.startswith('persistent-'):
  1751. srcUrl = srcUrl[len('persistent-'):]
  1752. cmd += [srcUrl]
  1753. if IsTrace():
  1754. Trace('%s', ' '.join(cmd))
  1755. try:
  1756. proc = subprocess.Popen(cmd)
  1757. except OSError:
  1758. return False
  1759. curlret = proc.wait()
  1760. if curlret == 22:
  1761. # From curl man page:
  1762. # 22: HTTP page not retrieved. The requested url was not found or
  1763. # returned another error with the HTTP error code being 400 or above.
  1764. # This return code only appears if -f, --fail is used.
  1765. if not quiet:
  1766. print("Server does not provide clone.bundle; ignoring.",
  1767. file=sys.stderr)
  1768. return False
  1769. if os.path.exists(tmpPath):
  1770. if curlret == 0 and self._IsValidBundle(tmpPath, quiet):
  1771. os.rename(tmpPath, dstPath)
  1772. return True
  1773. else:
  1774. os.remove(tmpPath)
  1775. return False
  1776. else:
  1777. return False
  1778. def _IsValidBundle(self, path, quiet):
  1779. try:
  1780. with open(path) as f:
  1781. if f.read(16) == '# v2 git bundle\n':
  1782. return True
  1783. else:
  1784. if not quiet:
  1785. print("Invalid clone.bundle file; ignoring.", file=sys.stderr)
  1786. return False
  1787. except OSError:
  1788. return False
  1789. def _Checkout(self, rev, quiet=False):
  1790. cmd = ['checkout']
  1791. if quiet:
  1792. cmd.append('-q')
  1793. cmd.append(rev)
  1794. cmd.append('--')
  1795. if GitCommand(self, cmd).Wait() != 0:
  1796. if self._allrefs:
  1797. raise GitError('%s checkout %s ' % (self.name, rev))
  1798. def _CherryPick(self, rev):
  1799. cmd = ['cherry-pick']
  1800. cmd.append(rev)
  1801. cmd.append('--')
  1802. if GitCommand(self, cmd).Wait() != 0:
  1803. if self._allrefs:
  1804. raise GitError('%s cherry-pick %s ' % (self.name, rev))
  1805. def _Revert(self, rev):
  1806. cmd = ['revert']
  1807. cmd.append('--no-edit')
  1808. cmd.append(rev)
  1809. cmd.append('--')
  1810. if GitCommand(self, cmd).Wait() != 0:
  1811. if self._allrefs:
  1812. raise GitError('%s revert %s ' % (self.name, rev))
  1813. def _ResetHard(self, rev, quiet=True):
  1814. cmd = ['reset', '--hard']
  1815. if quiet:
  1816. cmd.append('-q')
  1817. cmd.append(rev)
  1818. if GitCommand(self, cmd).Wait() != 0:
  1819. raise GitError('%s reset --hard %s ' % (self.name, rev))
  1820. def _Rebase(self, upstream, onto=None):
  1821. cmd = ['rebase']
  1822. if onto is not None:
  1823. cmd.extend(['--onto', onto])
  1824. cmd.append(upstream)
  1825. if GitCommand(self, cmd).Wait() != 0:
  1826. raise GitError('%s rebase %s ' % (self.name, upstream))
  1827. def _FastForward(self, head, ffonly=False):
  1828. cmd = ['merge', head]
  1829. if ffonly:
  1830. cmd.append("--ff-only")
  1831. if GitCommand(self, cmd).Wait() != 0:
  1832. raise GitError('%s merge %s ' % (self.name, head))
  1833. def _InitGitDir(self, mirror_git=None, force_sync=False):
  1834. init_git_dir = not os.path.exists(self.gitdir)
  1835. init_obj_dir = not os.path.exists(self.objdir)
  1836. try:
  1837. # Initialize the bare repository, which contains all of the objects.
  1838. if init_obj_dir:
  1839. os.makedirs(self.objdir)
  1840. self.bare_objdir.init()
  1841. # If we have a separate directory to hold refs, initialize it as well.
  1842. if self.objdir != self.gitdir:
  1843. if init_git_dir:
  1844. os.makedirs(self.gitdir)
  1845. if init_obj_dir or init_git_dir:
  1846. self._ReferenceGitDir(self.objdir, self.gitdir, share_refs=False,
  1847. copy_all=True)
  1848. try:
  1849. self._CheckDirReference(self.objdir, self.gitdir, share_refs=False)
  1850. except GitError as e:
  1851. if force_sync:
  1852. print("Retrying clone after deleting %s" % self.gitdir, file=sys.stderr)
  1853. try:
  1854. shutil.rmtree(os.path.realpath(self.gitdir))
  1855. if self.worktree and os.path.exists(
  1856. os.path.realpath(self.worktree)):
  1857. shutil.rmtree(os.path.realpath(self.worktree))
  1858. return self._InitGitDir(mirror_git=mirror_git, force_sync=False)
  1859. except:
  1860. raise e
  1861. raise e
  1862. if init_git_dir:
  1863. mp = self.manifest.manifestProject
  1864. ref_dir = mp.config.GetString('repo.reference') or ''
  1865. if ref_dir or mirror_git:
  1866. if not mirror_git:
  1867. mirror_git = os.path.join(ref_dir, self.name + '.git')
  1868. repo_git = os.path.join(ref_dir, '.repo', 'projects',
  1869. self.relpath + '.git')
  1870. if os.path.exists(mirror_git):
  1871. ref_dir = mirror_git
  1872. elif os.path.exists(repo_git):
  1873. ref_dir = repo_git
  1874. else:
  1875. ref_dir = None
  1876. if ref_dir:
  1877. _lwrite(os.path.join(self.gitdir, 'objects/info/alternates'),
  1878. os.path.join(ref_dir, 'objects') + '\n')
  1879. self._UpdateHooks()
  1880. m = self.manifest.manifestProject.config
  1881. for key in ['user.name', 'user.email']:
  1882. if m.Has(key, include_defaults=False):
  1883. self.config.SetString(key, m.GetString(key))
  1884. if self.manifest.IsMirror:
  1885. self.config.SetString('core.bare', 'true')
  1886. else:
  1887. self.config.SetString('core.bare', None)
  1888. except Exception:
  1889. if init_obj_dir and os.path.exists(self.objdir):
  1890. shutil.rmtree(self.objdir)
  1891. if init_git_dir and os.path.exists(self.gitdir):
  1892. shutil.rmtree(self.gitdir)
  1893. raise
  1894. def _UpdateHooks(self):
  1895. if os.path.exists(self.gitdir):
  1896. self._InitHooks()
  1897. def _InitHooks(self):
  1898. hooks = os.path.realpath(self._gitdir_path('hooks'))
  1899. if not os.path.exists(hooks):
  1900. os.makedirs(hooks)
  1901. for stock_hook in _ProjectHooks():
  1902. name = os.path.basename(stock_hook)
  1903. if name in ('commit-msg',) and not self.remote.review \
  1904. and not self is self.manifest.manifestProject:
  1905. # Don't install a Gerrit Code Review hook if this
  1906. # project does not appear to use it for reviews.
  1907. #
  1908. # Since the manifest project is one of those, but also
  1909. # managed through gerrit, it's excluded
  1910. continue
  1911. dst = os.path.join(hooks, name)
  1912. if os.path.islink(dst):
  1913. continue
  1914. if os.path.exists(dst):
  1915. if filecmp.cmp(stock_hook, dst, shallow=False):
  1916. os.remove(dst)
  1917. else:
  1918. _error("%s: Not replacing %s hook", self.relpath, name)
  1919. continue
  1920. try:
  1921. os.symlink(os.path.relpath(stock_hook, os.path.dirname(dst)), dst)
  1922. except OSError as e:
  1923. if e.errno == errno.EPERM:
  1924. raise GitError('filesystem must support symlinks')
  1925. else:
  1926. raise
  1927. def _InitRemote(self):
  1928. if self.remote.url:
  1929. remote = self.GetRemote(self.remote.name)
  1930. remote.url = self.remote.url
  1931. remote.review = self.remote.review
  1932. remote.projectname = self.name
  1933. if self.worktree:
  1934. remote.ResetFetch(mirror=False)
  1935. else:
  1936. remote.ResetFetch(mirror=True)
  1937. remote.Save()
  1938. def _InitMRef(self):
  1939. if self.manifest.branch:
  1940. self._InitAnyMRef(R_M + self.manifest.branch)
  1941. def _InitMirrorHead(self):
  1942. self._InitAnyMRef(HEAD)
  1943. def _InitAnyMRef(self, ref):
  1944. cur = self.bare_ref.symref(ref)
  1945. if self.revisionId:
  1946. if cur != '' or self.bare_ref.get(ref) != self.revisionId:
  1947. msg = 'manifest set to %s' % self.revisionId
  1948. dst = self.revisionId + '^0'
  1949. self.bare_git.UpdateRef(ref, dst, message=msg, detach=True)
  1950. else:
  1951. remote = self.GetRemote(self.remote.name)
  1952. dst = remote.ToLocal(self.revisionExpr)
  1953. if cur != dst:
  1954. msg = 'manifest set to %s' % self.revisionExpr
  1955. self.bare_git.symbolic_ref('-m', msg, ref, dst)
  1956. def _CheckDirReference(self, srcdir, destdir, share_refs):
  1957. symlink_files = self.shareable_files
  1958. symlink_dirs = self.shareable_dirs
  1959. if share_refs:
  1960. symlink_files += self.working_tree_files
  1961. symlink_dirs += self.working_tree_dirs
  1962. to_symlink = symlink_files + symlink_dirs
  1963. for name in set(to_symlink):
  1964. dst = os.path.realpath(os.path.join(destdir, name))
  1965. if os.path.lexists(dst):
  1966. src = os.path.realpath(os.path.join(srcdir, name))
  1967. # Fail if the links are pointing to the wrong place
  1968. if src != dst:
  1969. raise GitError('--force-sync not enabled; cannot overwrite a local '
  1970. 'work tree. If you\'re comfortable with the '
  1971. 'possibility of losing the work tree\'s git metadata,'
  1972. ' use `repo sync --force-sync {0}` to '
  1973. 'proceed.'.format(self.relpath))
  1974. def _ReferenceGitDir(self, gitdir, dotgit, share_refs, copy_all):
  1975. """Update |dotgit| to reference |gitdir|, using symlinks where possible.
  1976. Args:
  1977. gitdir: The bare git repository. Must already be initialized.
  1978. dotgit: The repository you would like to initialize.
  1979. share_refs: If true, |dotgit| will store its refs under |gitdir|.
  1980. Only one work tree can store refs under a given |gitdir|.
  1981. copy_all: If true, copy all remaining files from |gitdir| -> |dotgit|.
  1982. This saves you the effort of initializing |dotgit| yourself.
  1983. """
  1984. symlink_files = self.shareable_files
  1985. symlink_dirs = self.shareable_dirs
  1986. if share_refs:
  1987. symlink_files += self.working_tree_files
  1988. symlink_dirs += self.working_tree_dirs
  1989. to_symlink = symlink_files + symlink_dirs
  1990. to_copy = []
  1991. if copy_all:
  1992. to_copy = os.listdir(gitdir)
  1993. dotgit = os.path.realpath(dotgit)
  1994. for name in set(to_copy).union(to_symlink):
  1995. try:
  1996. src = os.path.realpath(os.path.join(gitdir, name))
  1997. dst = os.path.join(dotgit, name)
  1998. if os.path.lexists(dst):
  1999. continue
  2000. # If the source dir doesn't exist, create an empty dir.
  2001. if name in symlink_dirs and not os.path.lexists(src):
  2002. os.makedirs(src)
  2003. # If the source file doesn't exist, ensure the destination
  2004. # file doesn't either.
  2005. if name in symlink_files and not os.path.lexists(src):
  2006. try:
  2007. os.remove(dst)
  2008. except OSError:
  2009. pass
  2010. if name in to_symlink:
  2011. os.symlink(os.path.relpath(src, os.path.dirname(dst)), dst)
  2012. elif copy_all and not os.path.islink(dst):
  2013. if os.path.isdir(src):
  2014. shutil.copytree(src, dst)
  2015. elif os.path.isfile(src):
  2016. shutil.copy(src, dst)
  2017. except OSError as e:
  2018. if e.errno == errno.EPERM:
  2019. raise DownloadError('filesystem must support symlinks')
  2020. else:
  2021. raise
  2022. def _InitWorkTree(self, force_sync=False):
  2023. dotgit = os.path.join(self.worktree, '.git')
  2024. init_dotgit = not os.path.exists(dotgit)
  2025. try:
  2026. if init_dotgit:
  2027. os.makedirs(dotgit)
  2028. self._ReferenceGitDir(self.gitdir, dotgit, share_refs=True,
  2029. copy_all=False)
  2030. try:
  2031. self._CheckDirReference(self.gitdir, dotgit, share_refs=True)
  2032. except GitError as e:
  2033. if force_sync:
  2034. try:
  2035. shutil.rmtree(dotgit)
  2036. return self._InitWorkTree(force_sync=False)
  2037. except:
  2038. raise e
  2039. raise e
  2040. if init_dotgit:
  2041. _lwrite(os.path.join(dotgit, HEAD), '%s\n' % self.GetRevisionId())
  2042. cmd = ['read-tree', '--reset', '-u']
  2043. cmd.append('-v')
  2044. cmd.append(HEAD)
  2045. if GitCommand(self, cmd).Wait() != 0:
  2046. raise GitError("cannot initialize work tree")
  2047. self._CopyAndLinkFiles()
  2048. except Exception:
  2049. if init_dotgit:
  2050. shutil.rmtree(dotgit)
  2051. raise
  2052. def _gitdir_path(self, path):
  2053. return os.path.realpath(os.path.join(self.gitdir, path))
  2054. def _revlist(self, *args, **kw):
  2055. a = []
  2056. a.extend(args)
  2057. a.append('--')
  2058. return self.work_git.rev_list(*a, **kw)
  2059. @property
  2060. def _allrefs(self):
  2061. return self.bare_ref.all
  2062. def _getLogs(self, rev1, rev2, oneline=False, color=True):
  2063. """Get logs between two revisions of this project."""
  2064. comp = '..'
  2065. if rev1:
  2066. revs = [rev1]
  2067. if rev2:
  2068. revs.extend([comp, rev2])
  2069. cmd = ['log', ''.join(revs)]
  2070. out = DiffColoring(self.config)
  2071. if out.is_on and color:
  2072. cmd.append('--color')
  2073. if oneline:
  2074. cmd.append('--oneline')
  2075. try:
  2076. log = GitCommand(self, cmd, capture_stdout=True, capture_stderr=True)
  2077. if log.Wait() == 0:
  2078. return log.stdout
  2079. except GitError:
  2080. # worktree may not exist if groups changed for example. In that case,
  2081. # try in gitdir instead.
  2082. if not os.path.exists(self.worktree):
  2083. return self.bare_git.log(*cmd[1:])
  2084. else:
  2085. raise
  2086. return None
  2087. def getAddedAndRemovedLogs(self, toProject, oneline=False, color=True):
  2088. """Get the list of logs from this revision to given revisionId"""
  2089. logs = {}
  2090. selfId = self.GetRevisionId(self._allrefs)
  2091. toId = toProject.GetRevisionId(toProject._allrefs)
  2092. logs['added'] = self._getLogs(selfId, toId, oneline=oneline, color=color)
  2093. logs['removed'] = self._getLogs(toId, selfId, oneline=oneline, color=color)
  2094. return logs
  2095. class _GitGetByExec(object):
  2096. def __init__(self, project, bare, gitdir):
  2097. self._project = project
  2098. self._bare = bare
  2099. self._gitdir = gitdir
  2100. def LsOthers(self):
  2101. p = GitCommand(self._project,
  2102. ['ls-files',
  2103. '-z',
  2104. '--others',
  2105. '--exclude-standard'],
  2106. bare=False,
  2107. gitdir=self._gitdir,
  2108. capture_stdout=True,
  2109. capture_stderr=True)
  2110. if p.Wait() == 0:
  2111. out = p.stdout
  2112. if out:
  2113. return out[:-1].split('\0') # pylint: disable=W1401
  2114. # Backslash is not anomalous
  2115. return []
  2116. def DiffZ(self, name, *args):
  2117. cmd = [name]
  2118. cmd.append('-z')
  2119. cmd.extend(args)
  2120. p = GitCommand(self._project,
  2121. cmd,
  2122. gitdir=self._gitdir,
  2123. bare=False,
  2124. capture_stdout=True,
  2125. capture_stderr=True)
  2126. try:
  2127. out = p.process.stdout.read()
  2128. r = {}
  2129. if out:
  2130. out = iter(out[:-1].split('\0')) # pylint: disable=W1401
  2131. while out:
  2132. try:
  2133. info = next(out)
  2134. path = next(out)
  2135. except StopIteration:
  2136. break
  2137. class _Info(object):
  2138. def __init__(self, path, omode, nmode, oid, nid, state):
  2139. self.path = path
  2140. self.src_path = None
  2141. self.old_mode = omode
  2142. self.new_mode = nmode
  2143. self.old_id = oid
  2144. self.new_id = nid
  2145. if len(state) == 1:
  2146. self.status = state
  2147. self.level = None
  2148. else:
  2149. self.status = state[:1]
  2150. self.level = state[1:]
  2151. while self.level.startswith('0'):
  2152. self.level = self.level[1:]
  2153. info = info[1:].split(' ')
  2154. info = _Info(path, *info)
  2155. if info.status in ('R', 'C'):
  2156. info.src_path = info.path
  2157. info.path = next(out)
  2158. r[info.path] = info
  2159. return r
  2160. finally:
  2161. p.Wait()
  2162. def GetHead(self):
  2163. if self._bare:
  2164. path = os.path.join(self._project.gitdir, HEAD)
  2165. else:
  2166. path = os.path.join(self._project.worktree, '.git', HEAD)
  2167. try:
  2168. fd = open(path, 'rb')
  2169. except IOError as e:
  2170. raise NoManifestException(path, str(e))
  2171. try:
  2172. line = fd.read()
  2173. finally:
  2174. fd.close()
  2175. try:
  2176. line = line.decode()
  2177. except AttributeError:
  2178. pass
  2179. if line.startswith('ref: '):
  2180. return line[5:-1]
  2181. return line[:-1]
  2182. def SetHead(self, ref, message=None):
  2183. cmdv = []
  2184. if message is not None:
  2185. cmdv.extend(['-m', message])
  2186. cmdv.append(HEAD)
  2187. cmdv.append(ref)
  2188. self.symbolic_ref(*cmdv)
  2189. def DetachHead(self, new, message=None):
  2190. cmdv = ['--no-deref']
  2191. if message is not None:
  2192. cmdv.extend(['-m', message])
  2193. cmdv.append(HEAD)
  2194. cmdv.append(new)
  2195. self.update_ref(*cmdv)
  2196. def UpdateRef(self, name, new, old=None,
  2197. message=None,
  2198. detach=False):
  2199. cmdv = []
  2200. if message is not None:
  2201. cmdv.extend(['-m', message])
  2202. if detach:
  2203. cmdv.append('--no-deref')
  2204. cmdv.append(name)
  2205. cmdv.append(new)
  2206. if old is not None:
  2207. cmdv.append(old)
  2208. self.update_ref(*cmdv)
  2209. def DeleteRef(self, name, old=None):
  2210. if not old:
  2211. old = self.rev_parse(name)
  2212. self.update_ref('-d', name, old)
  2213. self._project.bare_ref.deleted(name)
  2214. def rev_list(self, *args, **kw):
  2215. if 'format' in kw:
  2216. cmdv = ['log', '--pretty=format:%s' % kw['format']]
  2217. else:
  2218. cmdv = ['rev-list']
  2219. cmdv.extend(args)
  2220. p = GitCommand(self._project,
  2221. cmdv,
  2222. bare=self._bare,
  2223. gitdir=self._gitdir,
  2224. capture_stdout=True,
  2225. capture_stderr=True)
  2226. r = []
  2227. for line in p.process.stdout:
  2228. if line[-1] == '\n':
  2229. line = line[:-1]
  2230. r.append(line)
  2231. if p.Wait() != 0:
  2232. raise GitError('%s rev-list %s: %s' % (
  2233. self._project.name,
  2234. str(args),
  2235. p.stderr))
  2236. return r
  2237. def __getattr__(self, name):
  2238. """Allow arbitrary git commands using pythonic syntax.
  2239. This allows you to do things like:
  2240. git_obj.rev_parse('HEAD')
  2241. Since we don't have a 'rev_parse' method defined, the __getattr__ will
  2242. run. We'll replace the '_' with a '-' and try to run a git command.
  2243. Any other positional arguments will be passed to the git command, and the
  2244. following keyword arguments are supported:
  2245. config: An optional dict of git config options to be passed with '-c'.
  2246. Args:
  2247. name: The name of the git command to call. Any '_' characters will
  2248. be replaced with '-'.
  2249. Returns:
  2250. A callable object that will try to call git with the named command.
  2251. """
  2252. name = name.replace('_', '-')
  2253. def runner(*args, **kwargs):
  2254. cmdv = []
  2255. config = kwargs.pop('config', None)
  2256. for k in kwargs:
  2257. raise TypeError('%s() got an unexpected keyword argument %r'
  2258. % (name, k))
  2259. if config is not None:
  2260. if not git_require((1, 7, 2)):
  2261. raise ValueError('cannot set config on command line for %s()'
  2262. % name)
  2263. for k, v in config.items():
  2264. cmdv.append('-c')
  2265. cmdv.append('%s=%s' % (k, v))
  2266. cmdv.append(name)
  2267. cmdv.extend(args)
  2268. p = GitCommand(self._project,
  2269. cmdv,
  2270. bare=self._bare,
  2271. gitdir=self._gitdir,
  2272. capture_stdout=True,
  2273. capture_stderr=True)
  2274. if p.Wait() != 0:
  2275. raise GitError('%s %s: %s' % (
  2276. self._project.name,
  2277. name,
  2278. p.stderr))
  2279. r = p.stdout
  2280. try:
  2281. r = r.decode('utf-8')
  2282. except AttributeError:
  2283. pass
  2284. if r.endswith('\n') and r.index('\n') == len(r) - 1:
  2285. return r[:-1]
  2286. return r
  2287. return runner
  2288. class _PriorSyncFailedError(Exception):
  2289. def __str__(self):
  2290. return 'prior sync failed; rebase still in progress'
  2291. class _DirtyError(Exception):
  2292. def __str__(self):
  2293. return 'contains uncommitted changes'
  2294. class _InfoMessage(object):
  2295. def __init__(self, project, text):
  2296. self.project = project
  2297. self.text = text
  2298. def Print(self, syncbuf):
  2299. syncbuf.out.info('%s/: %s', self.project.relpath, self.text)
  2300. syncbuf.out.nl()
  2301. class _Failure(object):
  2302. def __init__(self, project, why):
  2303. self.project = project
  2304. self.why = why
  2305. def Print(self, syncbuf):
  2306. syncbuf.out.fail('error: %s/: %s',
  2307. self.project.relpath,
  2308. str(self.why))
  2309. syncbuf.out.nl()
  2310. class _Later(object):
  2311. def __init__(self, project, action):
  2312. self.project = project
  2313. self.action = action
  2314. def Run(self, syncbuf):
  2315. out = syncbuf.out
  2316. out.project('project %s/', self.project.relpath)
  2317. out.nl()
  2318. try:
  2319. self.action()
  2320. out.nl()
  2321. return True
  2322. except GitError:
  2323. out.nl()
  2324. return False
  2325. class _SyncColoring(Coloring):
  2326. def __init__(self, config):
  2327. Coloring.__init__(self, config, 'reposync')
  2328. self.project = self.printer('header', attr='bold')
  2329. self.info = self.printer('info')
  2330. self.fail = self.printer('fail', fg='red')
  2331. class SyncBuffer(object):
  2332. def __init__(self, config, detach_head=False):
  2333. self._messages = []
  2334. self._failures = []
  2335. self._later_queue1 = []
  2336. self._later_queue2 = []
  2337. self.out = _SyncColoring(config)
  2338. self.out.redirect(sys.stderr)
  2339. self.detach_head = detach_head
  2340. self.clean = True
  2341. def info(self, project, fmt, *args):
  2342. self._messages.append(_InfoMessage(project, fmt % args))
  2343. def fail(self, project, err=None):
  2344. self._failures.append(_Failure(project, err))
  2345. self.clean = False
  2346. def later1(self, project, what):
  2347. self._later_queue1.append(_Later(project, what))
  2348. def later2(self, project, what):
  2349. self._later_queue2.append(_Later(project, what))
  2350. def Finish(self):
  2351. self._PrintMessages()
  2352. self._RunLater()
  2353. self._PrintMessages()
  2354. return self.clean
  2355. def _RunLater(self):
  2356. for q in ['_later_queue1', '_later_queue2']:
  2357. if not self._RunQueue(q):
  2358. return
  2359. def _RunQueue(self, queue):
  2360. for m in getattr(self, queue):
  2361. if not m.Run(self):
  2362. self.clean = False
  2363. return False
  2364. setattr(self, queue, [])
  2365. return True
  2366. def _PrintMessages(self):
  2367. for m in self._messages:
  2368. m.Print(self)
  2369. for m in self._failures:
  2370. m.Print(self)
  2371. self._messages = []
  2372. self._failures = []
  2373. class MetaProject(Project):
  2374. """A special project housed under .repo.
  2375. """
  2376. def __init__(self, manifest, name, gitdir, worktree):
  2377. Project.__init__(self,
  2378. manifest=manifest,
  2379. name=name,
  2380. gitdir=gitdir,
  2381. objdir=gitdir,
  2382. worktree=worktree,
  2383. remote=RemoteSpec('origin'),
  2384. relpath='.repo/%s' % name,
  2385. revisionExpr='refs/heads/master',
  2386. revisionId=None,
  2387. groups=None)
  2388. def PreSync(self):
  2389. if self.Exists:
  2390. cb = self.CurrentBranch
  2391. if cb:
  2392. base = self.GetBranch(cb).merge
  2393. if base:
  2394. self.revisionExpr = base
  2395. self.revisionId = None
  2396. def MetaBranchSwitch(self):
  2397. """ Prepare MetaProject for manifest branch switch
  2398. """
  2399. # detach and delete manifest branch, allowing a new
  2400. # branch to take over
  2401. syncbuf = SyncBuffer(self.config, detach_head=True)
  2402. self.Sync_LocalHalf(syncbuf)
  2403. syncbuf.Finish()
  2404. return GitCommand(self,
  2405. ['update-ref', '-d', 'refs/heads/default'],
  2406. capture_stdout=True,
  2407. capture_stderr=True).Wait() == 0
  2408. @property
  2409. def LastFetch(self):
  2410. try:
  2411. fh = os.path.join(self.gitdir, 'FETCH_HEAD')
  2412. return os.path.getmtime(fh)
  2413. except OSError:
  2414. return 0
  2415. @property
  2416. def HasChanges(self):
  2417. """Has the remote received new commits not yet checked out?
  2418. """
  2419. if not self.remote or not self.revisionExpr:
  2420. return False
  2421. all_refs = self.bare_ref.all
  2422. revid = self.GetRevisionId(all_refs)
  2423. head = self.work_git.GetHead()
  2424. if head.startswith(R_HEADS):
  2425. try:
  2426. head = all_refs[head]
  2427. except KeyError:
  2428. head = None
  2429. if revid == head:
  2430. return False
  2431. elif self._revlist(not_rev(HEAD), revid):
  2432. return True
  2433. return False