project.py 86 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819
  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 contextlib
  16. import errno
  17. import filecmp
  18. import glob
  19. import os
  20. import random
  21. import re
  22. import shutil
  23. import stat
  24. import subprocess
  25. import sys
  26. import tarfile
  27. import tempfile
  28. import time
  29. import traceback
  30. from color import Coloring
  31. from git_command import GitCommand, git_require
  32. from git_config import GitConfig, IsId, GetSchemeFromUrl, ID_RE
  33. from error import GitError, HookError, UploadError
  34. from error import ManifestInvalidRevisionError
  35. from error import NoManifestException
  36. from trace import IsTrace, Trace
  37. from git_refs import GitRefs, HEAD, R_HEADS, R_TAGS, R_PUB, R_M
  38. from pyversion import is_python3
  39. if not is_python3():
  40. # pylint:disable=W0622
  41. input = raw_input
  42. # pylint:enable=W0622
  43. def _lwrite(path, content):
  44. lock = '%s.lock' % path
  45. fd = open(lock, 'w')
  46. try:
  47. fd.write(content)
  48. finally:
  49. fd.close()
  50. try:
  51. os.rename(lock, path)
  52. except OSError:
  53. os.remove(lock)
  54. raise
  55. def _error(fmt, *args):
  56. msg = fmt % args
  57. print('error: %s' % msg, file=sys.stderr)
  58. def not_rev(r):
  59. return '^' + r
  60. def sq(r):
  61. return "'" + r.replace("'", "'\''") + "'"
  62. _project_hook_list = None
  63. def _ProjectHooks():
  64. """List the hooks present in the 'hooks' directory.
  65. These hooks are project hooks and are copied to the '.git/hooks' directory
  66. of all subprojects.
  67. This function caches the list of hooks (based on the contents of the
  68. 'repo/hooks' directory) on the first call.
  69. Returns:
  70. A list of absolute paths to all of the files in the hooks directory.
  71. """
  72. global _project_hook_list
  73. if _project_hook_list is None:
  74. d = os.path.realpath(os.path.abspath(os.path.dirname(__file__)))
  75. d = os.path.join(d, 'hooks')
  76. _project_hook_list = [os.path.join(d, x) for x in os.listdir(d)]
  77. return _project_hook_list
  78. class DownloadedChange(object):
  79. _commit_cache = None
  80. def __init__(self, project, base, change_id, ps_id, commit):
  81. self.project = project
  82. self.base = base
  83. self.change_id = change_id
  84. self.ps_id = ps_id
  85. self.commit = commit
  86. @property
  87. def commits(self):
  88. if self._commit_cache is None:
  89. self._commit_cache = self.project.bare_git.rev_list(
  90. '--abbrev=8',
  91. '--abbrev-commit',
  92. '--pretty=oneline',
  93. '--reverse',
  94. '--date-order',
  95. not_rev(self.base),
  96. self.commit,
  97. '--')
  98. return self._commit_cache
  99. class ReviewableBranch(object):
  100. _commit_cache = None
  101. def __init__(self, project, branch, base):
  102. self.project = project
  103. self.branch = branch
  104. self.base = base
  105. @property
  106. def name(self):
  107. return self.branch.name
  108. @property
  109. def commits(self):
  110. if self._commit_cache is None:
  111. self._commit_cache = self.project.bare_git.rev_list(
  112. '--abbrev=8',
  113. '--abbrev-commit',
  114. '--pretty=oneline',
  115. '--reverse',
  116. '--date-order',
  117. not_rev(self.base),
  118. R_HEADS + self.name,
  119. '--')
  120. return self._commit_cache
  121. @property
  122. def unabbrev_commits(self):
  123. r = dict()
  124. for commit in self.project.bare_git.rev_list(
  125. not_rev(self.base),
  126. R_HEADS + self.name,
  127. '--'):
  128. r[commit[0:8]] = commit
  129. return r
  130. @property
  131. def date(self):
  132. return self.project.bare_git.log(
  133. '--pretty=format:%cd',
  134. '-n', '1',
  135. R_HEADS + self.name,
  136. '--')
  137. def UploadForReview(self, people, auto_topic=False, draft=False, dest_branch=None):
  138. self.project.UploadForReview(self.name,
  139. people,
  140. auto_topic=auto_topic,
  141. draft=draft,
  142. dest_branch=dest_branch)
  143. def GetPublishedRefs(self):
  144. refs = {}
  145. output = self.project.bare_git.ls_remote(
  146. self.branch.remote.SshReviewUrl(self.project.UserEmail),
  147. 'refs/changes/*')
  148. for line in output.split('\n'):
  149. try:
  150. (sha, ref) = line.split()
  151. refs[sha] = ref
  152. except ValueError:
  153. pass
  154. return refs
  155. class StatusColoring(Coloring):
  156. def __init__(self, config):
  157. Coloring.__init__(self, config, 'status')
  158. self.project = self.printer('header', attr='bold')
  159. self.branch = self.printer('header', attr='bold')
  160. self.nobranch = self.printer('nobranch', fg='red')
  161. self.important = self.printer('important', fg='red')
  162. self.added = self.printer('added', fg='green')
  163. self.changed = self.printer('changed', fg='red')
  164. self.untracked = self.printer('untracked', fg='red')
  165. class DiffColoring(Coloring):
  166. def __init__(self, config):
  167. Coloring.__init__(self, config, 'diff')
  168. self.project = self.printer('header', attr='bold')
  169. class _Annotation(object):
  170. def __init__(self, name, value, keep):
  171. self.name = name
  172. self.value = value
  173. self.keep = keep
  174. class _CopyFile(object):
  175. def __init__(self, src, dest, abssrc, absdest):
  176. self.src = src
  177. self.dest = dest
  178. self.abs_src = abssrc
  179. self.abs_dest = absdest
  180. def _Copy(self):
  181. src = self.abs_src
  182. dest = self.abs_dest
  183. # copy file if it does not exist or is out of date
  184. if not os.path.exists(dest) or not filecmp.cmp(src, dest):
  185. try:
  186. # remove existing file first, since it might be read-only
  187. if os.path.exists(dest):
  188. os.remove(dest)
  189. else:
  190. dest_dir = os.path.dirname(dest)
  191. if not os.path.isdir(dest_dir):
  192. os.makedirs(dest_dir)
  193. shutil.copy(src, dest)
  194. # make the file read-only
  195. mode = os.stat(dest)[stat.ST_MODE]
  196. mode = mode & ~(stat.S_IWUSR | stat.S_IWGRP | stat.S_IWOTH)
  197. os.chmod(dest, mode)
  198. except IOError:
  199. _error('Cannot copy file %s to %s', src, dest)
  200. class _LinkFile(object):
  201. def __init__(self, git_worktree, src, dest, relsrc, absdest):
  202. self.git_worktree = git_worktree
  203. self.src = src
  204. self.dest = dest
  205. self.src_rel_to_dest = relsrc
  206. self.abs_dest = absdest
  207. def __linkIt(self, relSrc, absDest):
  208. # link file if it does not exist or is out of date
  209. if not os.path.islink(absDest) or (os.readlink(absDest) != relSrc):
  210. try:
  211. # remove existing file first, since it might be read-only
  212. if os.path.exists(absDest):
  213. os.remove(absDest)
  214. else:
  215. dest_dir = os.path.dirname(absDest)
  216. if not os.path.isdir(dest_dir):
  217. os.makedirs(dest_dir)
  218. os.symlink(relSrc, absDest)
  219. except IOError:
  220. _error('Cannot link file %s to %s', relSrc, absDest)
  221. def _Link(self):
  222. """Link the self.rel_src_to_dest and self.abs_dest. Handles wild cards
  223. on the src linking all of the files in the source in to the destination
  224. directory.
  225. """
  226. # We use the absSrc to handle the situation where the current directory
  227. # is not the root of the repo
  228. absSrc = os.path.join(self.git_worktree, self.src)
  229. if os.path.exists(absSrc):
  230. # Entity exists so just a simple one to one link operation
  231. self.__linkIt(self.src_rel_to_dest, self.abs_dest)
  232. else:
  233. # Entity doesn't exist assume there is a wild card
  234. absDestDir = self.abs_dest
  235. if os.path.exists(absDestDir) and not os.path.isdir(absDestDir):
  236. _error('Link error: src with wildcard, %s must be a directory',
  237. absDestDir)
  238. else:
  239. absSrcFiles = glob.glob(absSrc)
  240. for absSrcFile in absSrcFiles:
  241. # Create a releative path from source dir to destination dir
  242. absSrcDir = os.path.dirname(absSrcFile)
  243. relSrcDir = os.path.relpath(absSrcDir, absDestDir)
  244. # Get the source file name
  245. srcFile = os.path.basename(absSrcFile)
  246. # Now form the final full paths to srcFile. They will be
  247. # absolute for the desintaiton and relative for the srouce.
  248. absDest = os.path.join(absDestDir, srcFile)
  249. relSrc = os.path.join(relSrcDir, srcFile)
  250. self.__linkIt(relSrc, absDest)
  251. class RemoteSpec(object):
  252. def __init__(self,
  253. name,
  254. url=None,
  255. review=None,
  256. revision=None):
  257. self.name = name
  258. self.url = url
  259. self.review = review
  260. self.revision = revision
  261. class RepoHook(object):
  262. """A RepoHook contains information about a script to run as a hook.
  263. Hooks are used to run a python script before running an upload (for instance,
  264. to run presubmit checks). Eventually, we may have hooks for other actions.
  265. This shouldn't be confused with files in the 'repo/hooks' directory. Those
  266. files are copied into each '.git/hooks' folder for each project. Repo-level
  267. hooks are associated instead with repo actions.
  268. Hooks are always python. When a hook is run, we will load the hook into the
  269. interpreter and execute its main() function.
  270. """
  271. def __init__(self,
  272. hook_type,
  273. hooks_project,
  274. topdir,
  275. abort_if_user_denies=False):
  276. """RepoHook constructor.
  277. Params:
  278. hook_type: A string representing the type of hook. This is also used
  279. to figure out the name of the file containing the hook. For
  280. example: 'pre-upload'.
  281. hooks_project: The project containing the repo hooks. If you have a
  282. manifest, this is manifest.repo_hooks_project. OK if this is None,
  283. which will make the hook a no-op.
  284. topdir: Repo's top directory (the one containing the .repo directory).
  285. Scripts will run with CWD as this directory. If you have a manifest,
  286. this is manifest.topdir
  287. abort_if_user_denies: If True, we'll throw a HookError() if the user
  288. doesn't allow us to run the hook.
  289. """
  290. self._hook_type = hook_type
  291. self._hooks_project = hooks_project
  292. self._topdir = topdir
  293. self._abort_if_user_denies = abort_if_user_denies
  294. # Store the full path to the script for convenience.
  295. if self._hooks_project:
  296. self._script_fullpath = os.path.join(self._hooks_project.worktree,
  297. self._hook_type + '.py')
  298. else:
  299. self._script_fullpath = None
  300. def _GetHash(self):
  301. """Return a hash of the contents of the hooks directory.
  302. We'll just use git to do this. This hash has the property that if anything
  303. changes in the directory we will return a different has.
  304. SECURITY CONSIDERATION:
  305. This hash only represents the contents of files in the hook directory, not
  306. any other files imported or called by hooks. Changes to imported files
  307. can change the script behavior without affecting the hash.
  308. Returns:
  309. A string representing the hash. This will always be ASCII so that it can
  310. be printed to the user easily.
  311. """
  312. assert self._hooks_project, "Must have hooks to calculate their hash."
  313. # We will use the work_git object rather than just calling GetRevisionId().
  314. # That gives us a hash of the latest checked in version of the files that
  315. # the user will actually be executing. Specifically, GetRevisionId()
  316. # doesn't appear to change even if a user checks out a different version
  317. # of the hooks repo (via git checkout) nor if a user commits their own revs.
  318. #
  319. # NOTE: Local (non-committed) changes will not be factored into this hash.
  320. # I think this is OK, since we're really only worried about warning the user
  321. # about upstream changes.
  322. return self._hooks_project.work_git.rev_parse('HEAD')
  323. def _GetMustVerb(self):
  324. """Return 'must' if the hook is required; 'should' if not."""
  325. if self._abort_if_user_denies:
  326. return 'must'
  327. else:
  328. return 'should'
  329. def _CheckForHookApproval(self):
  330. """Check to see whether this hook has been approved.
  331. We'll look at the hash of all of the hooks. If this matches the hash that
  332. the user last approved, we're done. If it doesn't, we'll ask the user
  333. about approval.
  334. Note that we ask permission for each individual hook even though we use
  335. the hash of all hooks when detecting changes. We'd like the user to be
  336. able to approve / deny each hook individually. We only use the hash of all
  337. hooks because there is no other easy way to detect changes to local imports.
  338. Returns:
  339. True if this hook is approved to run; False otherwise.
  340. Raises:
  341. HookError: Raised if the user doesn't approve and abort_if_user_denies
  342. was passed to the consturctor.
  343. """
  344. hooks_config = self._hooks_project.config
  345. git_approval_key = 'repo.hooks.%s.approvedhash' % self._hook_type
  346. # Get the last hash that the user approved for this hook; may be None.
  347. old_hash = hooks_config.GetString(git_approval_key)
  348. # Get the current hash so we can tell if scripts changed since approval.
  349. new_hash = self._GetHash()
  350. if old_hash is not None:
  351. # User previously approved hook and asked not to be prompted again.
  352. if new_hash == old_hash:
  353. # Approval matched. We're done.
  354. return True
  355. else:
  356. # Give the user a reason why we're prompting, since they last told
  357. # us to "never ask again".
  358. prompt = 'WARNING: Scripts have changed since %s was allowed.\n\n' % (
  359. self._hook_type)
  360. else:
  361. prompt = ''
  362. # Prompt the user if we're not on a tty; on a tty we'll assume "no".
  363. if sys.stdout.isatty():
  364. prompt += ('Repo %s run the script:\n'
  365. ' %s\n'
  366. '\n'
  367. 'Do you want to allow this script to run '
  368. '(yes/yes-never-ask-again/NO)? ') % (
  369. self._GetMustVerb(), self._script_fullpath)
  370. response = input(prompt).lower()
  371. print()
  372. # User is doing a one-time approval.
  373. if response in ('y', 'yes'):
  374. return True
  375. elif response == 'yes-never-ask-again':
  376. hooks_config.SetString(git_approval_key, new_hash)
  377. return True
  378. # For anything else, we'll assume no approval.
  379. if self._abort_if_user_denies:
  380. raise HookError('You must allow the %s hook or use --no-verify.' %
  381. self._hook_type)
  382. return False
  383. def _ExecuteHook(self, **kwargs):
  384. """Actually execute the given hook.
  385. This will run the hook's 'main' function in our python interpreter.
  386. Args:
  387. kwargs: Keyword arguments to pass to the hook. These are often specific
  388. to the hook type. For instance, pre-upload hooks will contain
  389. a project_list.
  390. """
  391. # Keep sys.path and CWD stashed away so that we can always restore them
  392. # upon function exit.
  393. orig_path = os.getcwd()
  394. orig_syspath = sys.path
  395. try:
  396. # Always run hooks with CWD as topdir.
  397. os.chdir(self._topdir)
  398. # Put the hook dir as the first item of sys.path so hooks can do
  399. # relative imports. We want to replace the repo dir as [0] so
  400. # hooks can't import repo files.
  401. sys.path = [os.path.dirname(self._script_fullpath)] + sys.path[1:]
  402. # Exec, storing global context in the context dict. We catch exceptions
  403. # and convert to a HookError w/ just the failing traceback.
  404. context = {}
  405. try:
  406. exec(compile(open(self._script_fullpath).read(),
  407. self._script_fullpath, 'exec'), context)
  408. except Exception:
  409. raise HookError('%s\nFailed to import %s hook; see traceback above.' % (
  410. traceback.format_exc(), self._hook_type))
  411. # Running the script should have defined a main() function.
  412. if 'main' not in context:
  413. raise HookError('Missing main() in: "%s"' % self._script_fullpath)
  414. # Add 'hook_should_take_kwargs' to the arguments to be passed to main.
  415. # We don't actually want hooks to define their main with this argument--
  416. # it's there to remind them that their hook should always take **kwargs.
  417. # For instance, a pre-upload hook should be defined like:
  418. # def main(project_list, **kwargs):
  419. #
  420. # This allows us to later expand the API without breaking old hooks.
  421. kwargs = kwargs.copy()
  422. kwargs['hook_should_take_kwargs'] = True
  423. # Call the main function in the hook. If the hook should cause the
  424. # build to fail, it will raise an Exception. We'll catch that convert
  425. # to a HookError w/ just the failing traceback.
  426. try:
  427. context['main'](**kwargs)
  428. except Exception:
  429. raise HookError('%s\nFailed to run main() for %s hook; see traceback '
  430. 'above.' % (
  431. traceback.format_exc(), self._hook_type))
  432. finally:
  433. # Restore sys.path and CWD.
  434. sys.path = orig_syspath
  435. os.chdir(orig_path)
  436. def Run(self, user_allows_all_hooks, **kwargs):
  437. """Run the hook.
  438. If the hook doesn't exist (because there is no hooks project or because
  439. this particular hook is not enabled), this is a no-op.
  440. Args:
  441. user_allows_all_hooks: If True, we will never prompt about running the
  442. hook--we'll just assume it's OK to run it.
  443. kwargs: Keyword arguments to pass to the hook. These are often specific
  444. to the hook type. For instance, pre-upload hooks will contain
  445. a project_list.
  446. Raises:
  447. HookError: If there was a problem finding the hook or the user declined
  448. to run a required hook (from _CheckForHookApproval).
  449. """
  450. # No-op if there is no hooks project or if hook is disabled.
  451. if ((not self._hooks_project) or
  452. (self._hook_type not in self._hooks_project.enabled_repo_hooks)):
  453. return
  454. # Bail with a nice error if we can't find the hook.
  455. if not os.path.isfile(self._script_fullpath):
  456. raise HookError('Couldn\'t find repo hook: "%s"' % self._script_fullpath)
  457. # Make sure the user is OK with running the hook.
  458. if (not user_allows_all_hooks) and (not self._CheckForHookApproval()):
  459. return
  460. # Run the hook with the same version of python we're using.
  461. self._ExecuteHook(**kwargs)
  462. class Project(object):
  463. # These objects can be shared between several working trees.
  464. shareable_files = ['description', 'info']
  465. shareable_dirs = ['hooks', 'objects', 'rr-cache', 'svn']
  466. # These objects can only be used by a single working tree.
  467. working_tree_files = ['config', 'packed-refs', 'shallow']
  468. working_tree_dirs = ['logs', 'refs']
  469. def __init__(self,
  470. manifest,
  471. name,
  472. remote,
  473. gitdir,
  474. objdir,
  475. worktree,
  476. relpath,
  477. revisionExpr,
  478. revisionId,
  479. rebase=True,
  480. groups=None,
  481. sync_c=False,
  482. sync_s=False,
  483. clone_depth=None,
  484. upstream=None,
  485. parent=None,
  486. is_derived=False,
  487. dest_branch=None,
  488. optimized_fetch=False):
  489. """Init a Project object.
  490. Args:
  491. manifest: The XmlManifest object.
  492. name: The `name` attribute of manifest.xml's project element.
  493. remote: RemoteSpec object specifying its remote's properties.
  494. gitdir: Absolute path of git directory.
  495. objdir: Absolute path of directory to store git objects.
  496. worktree: Absolute path of git working tree.
  497. relpath: Relative path of git working tree to repo's top directory.
  498. revisionExpr: The `revision` attribute of manifest.xml's project element.
  499. revisionId: git commit id for checking out.
  500. rebase: The `rebase` attribute of manifest.xml's project element.
  501. groups: The `groups` attribute of manifest.xml's project element.
  502. sync_c: The `sync-c` attribute of manifest.xml's project element.
  503. sync_s: The `sync-s` attribute of manifest.xml's project element.
  504. upstream: The `upstream` attribute of manifest.xml's project element.
  505. parent: The parent Project object.
  506. is_derived: False if the project was explicitly defined in the manifest;
  507. True if the project is a discovered submodule.
  508. dest_branch: The branch to which to push changes for review by default.
  509. optimized_fetch: If True, when a project is set to a sha1 revision, only
  510. fetch from the remote if the sha1 is not present locally.
  511. """
  512. self.manifest = manifest
  513. self.name = name
  514. self.remote = remote
  515. self.gitdir = gitdir.replace('\\', '/')
  516. self.objdir = objdir.replace('\\', '/')
  517. if worktree:
  518. self.worktree = worktree.replace('\\', '/')
  519. else:
  520. self.worktree = None
  521. self.relpath = relpath
  522. self.revisionExpr = revisionExpr
  523. if revisionId is None \
  524. and revisionExpr \
  525. and IsId(revisionExpr):
  526. self.revisionId = revisionExpr
  527. else:
  528. self.revisionId = revisionId
  529. self.rebase = rebase
  530. self.groups = groups
  531. self.sync_c = sync_c
  532. self.sync_s = sync_s
  533. self.clone_depth = clone_depth
  534. self.upstream = upstream
  535. self.parent = parent
  536. self.is_derived = is_derived
  537. self.optimized_fetch = optimized_fetch
  538. self.subprojects = []
  539. self.snapshots = {}
  540. self.copyfiles = []
  541. self.linkfiles = []
  542. self.annotations = []
  543. self.config = GitConfig.ForRepository(
  544. gitdir=self.gitdir,
  545. defaults=self.manifest.globalConfig)
  546. if self.worktree:
  547. self.work_git = self._GitGetByExec(self, bare=False, gitdir=gitdir)
  548. else:
  549. self.work_git = None
  550. self.bare_git = self._GitGetByExec(self, bare=True, gitdir=gitdir)
  551. self.bare_ref = GitRefs(gitdir)
  552. self.bare_objdir = self._GitGetByExec(self, bare=True, gitdir=objdir)
  553. self.dest_branch = dest_branch
  554. # This will be filled in if a project is later identified to be the
  555. # project containing repo hooks.
  556. self.enabled_repo_hooks = []
  557. @property
  558. def Derived(self):
  559. return self.is_derived
  560. @property
  561. def Exists(self):
  562. return os.path.isdir(self.gitdir) and os.path.isdir(self.objdir)
  563. @property
  564. def CurrentBranch(self):
  565. """Obtain the name of the currently checked out branch.
  566. The branch name omits the 'refs/heads/' prefix.
  567. None is returned if the project is on a detached HEAD.
  568. """
  569. b = self.work_git.GetHead()
  570. if b.startswith(R_HEADS):
  571. return b[len(R_HEADS):]
  572. return None
  573. def IsRebaseInProgress(self):
  574. w = self.worktree
  575. g = os.path.join(w, '.git')
  576. return os.path.exists(os.path.join(g, 'rebase-apply')) \
  577. or os.path.exists(os.path.join(g, 'rebase-merge')) \
  578. or os.path.exists(os.path.join(w, '.dotest'))
  579. def IsDirty(self, consider_untracked=True):
  580. """Is the working directory modified in some way?
  581. """
  582. self.work_git.update_index('-q',
  583. '--unmerged',
  584. '--ignore-missing',
  585. '--refresh')
  586. if self.work_git.DiffZ('diff-index', '-M', '--cached', HEAD):
  587. return True
  588. if self.work_git.DiffZ('diff-files'):
  589. return True
  590. if consider_untracked and self.work_git.LsOthers():
  591. return True
  592. return False
  593. _userident_name = None
  594. _userident_email = None
  595. @property
  596. def UserName(self):
  597. """Obtain the user's personal name.
  598. """
  599. if self._userident_name is None:
  600. self._LoadUserIdentity()
  601. return self._userident_name
  602. @property
  603. def UserEmail(self):
  604. """Obtain the user's email address. This is very likely
  605. to be their Gerrit login.
  606. """
  607. if self._userident_email is None:
  608. self._LoadUserIdentity()
  609. return self._userident_email
  610. def _LoadUserIdentity(self):
  611. u = self.bare_git.var('GIT_COMMITTER_IDENT')
  612. m = re.compile("^(.*) <([^>]*)> ").match(u)
  613. if m:
  614. self._userident_name = m.group(1)
  615. self._userident_email = m.group(2)
  616. else:
  617. self._userident_name = ''
  618. self._userident_email = ''
  619. def GetRemote(self, name):
  620. """Get the configuration for a single remote.
  621. """
  622. return self.config.GetRemote(name)
  623. def GetBranch(self, name):
  624. """Get the configuration for a single branch.
  625. """
  626. return self.config.GetBranch(name)
  627. def GetBranches(self):
  628. """Get all existing local branches.
  629. """
  630. current = self.CurrentBranch
  631. all_refs = self._allrefs
  632. heads = {}
  633. for name, ref_id in all_refs.items():
  634. if name.startswith(R_HEADS):
  635. name = name[len(R_HEADS):]
  636. b = self.GetBranch(name)
  637. b.current = name == current
  638. b.published = None
  639. b.revision = ref_id
  640. heads[name] = b
  641. for name, ref_id in all_refs.items():
  642. if name.startswith(R_PUB):
  643. name = name[len(R_PUB):]
  644. b = heads.get(name)
  645. if b:
  646. b.published = ref_id
  647. return heads
  648. def MatchesGroups(self, manifest_groups):
  649. """Returns true if the manifest groups specified at init should cause
  650. this project to be synced.
  651. Prefixing a manifest group with "-" inverts the meaning of a group.
  652. All projects are implicitly labelled with "all".
  653. labels are resolved in order. In the example case of
  654. project_groups: "all,group1,group2"
  655. manifest_groups: "-group1,group2"
  656. the project will be matched.
  657. The special manifest group "default" will match any project that
  658. does not have the special project group "notdefault"
  659. """
  660. expanded_manifest_groups = manifest_groups or ['default']
  661. expanded_project_groups = ['all'] + (self.groups or [])
  662. if not 'notdefault' in expanded_project_groups:
  663. expanded_project_groups += ['default']
  664. matched = False
  665. for group in expanded_manifest_groups:
  666. if group.startswith('-') and group[1:] in expanded_project_groups:
  667. matched = False
  668. elif group in expanded_project_groups:
  669. matched = True
  670. return matched
  671. ## Status Display ##
  672. def UncommitedFiles(self, get_all=True):
  673. """Returns a list of strings, uncommitted files in the git tree.
  674. Args:
  675. get_all: a boolean, if True - get information about all different
  676. uncommitted files. If False - return as soon as any kind of
  677. uncommitted files is detected.
  678. """
  679. details = []
  680. self.work_git.update_index('-q',
  681. '--unmerged',
  682. '--ignore-missing',
  683. '--refresh')
  684. if self.IsRebaseInProgress():
  685. details.append("rebase in progress")
  686. if not get_all:
  687. return details
  688. changes = self.work_git.DiffZ('diff-index', '--cached', HEAD).keys()
  689. if changes:
  690. details.extend(changes)
  691. if not get_all:
  692. return details
  693. changes = self.work_git.DiffZ('diff-files').keys()
  694. if changes:
  695. details.extend(changes)
  696. if not get_all:
  697. return details
  698. changes = self.work_git.LsOthers()
  699. if changes:
  700. details.extend(changes)
  701. return details
  702. def HasChanges(self):
  703. """Returns true if there are uncommitted changes.
  704. """
  705. if self.UncommitedFiles(get_all=False):
  706. return True
  707. else:
  708. return False
  709. def PrintWorkTreeStatus(self, output_redir=None):
  710. """Prints the status of the repository to stdout.
  711. Args:
  712. output: If specified, redirect the output to this object.
  713. """
  714. if not os.path.isdir(self.worktree):
  715. if output_redir == None:
  716. output_redir = sys.stdout
  717. print(file=output_redir)
  718. print('project %s/' % self.relpath, file=output_redir)
  719. print(' missing (run "repo sync")', file=output_redir)
  720. return
  721. self.work_git.update_index('-q',
  722. '--unmerged',
  723. '--ignore-missing',
  724. '--refresh')
  725. rb = self.IsRebaseInProgress()
  726. di = self.work_git.DiffZ('diff-index', '-M', '--cached', HEAD)
  727. df = self.work_git.DiffZ('diff-files')
  728. do = self.work_git.LsOthers()
  729. if not rb and not di and not df and not do and not self.CurrentBranch:
  730. return 'CLEAN'
  731. out = StatusColoring(self.config)
  732. if not output_redir == None:
  733. out.redirect(output_redir)
  734. out.project('project %-40s', self.relpath + '/ ')
  735. branch = self.CurrentBranch
  736. if branch is None:
  737. out.nobranch('(*** NO BRANCH ***)')
  738. else:
  739. out.branch('branch %s', branch)
  740. out.nl()
  741. if rb:
  742. out.important('prior sync failed; rebase still in progress')
  743. out.nl()
  744. paths = list()
  745. paths.extend(di.keys())
  746. paths.extend(df.keys())
  747. paths.extend(do)
  748. for p in sorted(set(paths)):
  749. try:
  750. i = di[p]
  751. except KeyError:
  752. i = None
  753. try:
  754. f = df[p]
  755. except KeyError:
  756. f = None
  757. if i:
  758. i_status = i.status.upper()
  759. else:
  760. i_status = '-'
  761. if f:
  762. f_status = f.status.lower()
  763. else:
  764. f_status = '-'
  765. if i and i.src_path:
  766. line = ' %s%s\t%s => %s (%s%%)' % (i_status, f_status,
  767. i.src_path, p, i.level)
  768. else:
  769. line = ' %s%s\t%s' % (i_status, f_status, p)
  770. if i and not f:
  771. out.added('%s', line)
  772. elif (i and f) or (not i and f):
  773. out.changed('%s', line)
  774. elif not i and not f:
  775. out.untracked('%s', line)
  776. else:
  777. out.write('%s', line)
  778. out.nl()
  779. return 'DIRTY'
  780. def PrintWorkTreeDiff(self, absolute_paths=False):
  781. """Prints the status of the repository to stdout.
  782. """
  783. out = DiffColoring(self.config)
  784. cmd = ['diff']
  785. if out.is_on:
  786. cmd.append('--color')
  787. cmd.append(HEAD)
  788. if absolute_paths:
  789. cmd.append('--src-prefix=a/%s/' % self.relpath)
  790. cmd.append('--dst-prefix=b/%s/' % self.relpath)
  791. cmd.append('--')
  792. p = GitCommand(self,
  793. cmd,
  794. capture_stdout=True,
  795. capture_stderr=True)
  796. has_diff = False
  797. for line in p.process.stdout:
  798. if not has_diff:
  799. out.nl()
  800. out.project('project %s/' % self.relpath)
  801. out.nl()
  802. has_diff = True
  803. print(line[:-1])
  804. p.Wait()
  805. ## Publish / Upload ##
  806. def WasPublished(self, branch, all_refs=None):
  807. """Was the branch published (uploaded) for code review?
  808. If so, returns the SHA-1 hash of the last published
  809. state for the branch.
  810. """
  811. key = R_PUB + branch
  812. if all_refs is None:
  813. try:
  814. return self.bare_git.rev_parse(key)
  815. except GitError:
  816. return None
  817. else:
  818. try:
  819. return all_refs[key]
  820. except KeyError:
  821. return None
  822. def CleanPublishedCache(self, all_refs=None):
  823. """Prunes any stale published refs.
  824. """
  825. if all_refs is None:
  826. all_refs = self._allrefs
  827. heads = set()
  828. canrm = {}
  829. for name, ref_id in all_refs.items():
  830. if name.startswith(R_HEADS):
  831. heads.add(name)
  832. elif name.startswith(R_PUB):
  833. canrm[name] = ref_id
  834. for name, ref_id in canrm.items():
  835. n = name[len(R_PUB):]
  836. if R_HEADS + n not in heads:
  837. self.bare_git.DeleteRef(name, ref_id)
  838. def GetUploadableBranches(self, selected_branch=None):
  839. """List any branches which can be uploaded for review.
  840. """
  841. heads = {}
  842. pubed = {}
  843. for name, ref_id in self._allrefs.items():
  844. if name.startswith(R_HEADS):
  845. heads[name[len(R_HEADS):]] = ref_id
  846. elif name.startswith(R_PUB):
  847. pubed[name[len(R_PUB):]] = ref_id
  848. ready = []
  849. for branch, ref_id in heads.items():
  850. if branch in pubed and pubed[branch] == ref_id:
  851. continue
  852. if selected_branch and branch != selected_branch:
  853. continue
  854. rb = self.GetUploadableBranch(branch)
  855. if rb:
  856. ready.append(rb)
  857. return ready
  858. def GetUploadableBranch(self, branch_name):
  859. """Get a single uploadable branch, or None.
  860. """
  861. branch = self.GetBranch(branch_name)
  862. base = branch.LocalMerge
  863. if branch.LocalMerge:
  864. rb = ReviewableBranch(self, branch, base)
  865. if rb.commits:
  866. return rb
  867. return None
  868. def UploadForReview(self, branch=None,
  869. people=([], []),
  870. auto_topic=False,
  871. draft=False,
  872. dest_branch=None):
  873. """Uploads the named branch for code review.
  874. """
  875. if branch is None:
  876. branch = self.CurrentBranch
  877. if branch is None:
  878. raise GitError('not currently on a branch')
  879. branch = self.GetBranch(branch)
  880. if not branch.LocalMerge:
  881. raise GitError('branch %s does not track a remote' % branch.name)
  882. if not branch.remote.review:
  883. raise GitError('remote %s has no review url' % branch.remote.name)
  884. if dest_branch is None:
  885. dest_branch = self.dest_branch
  886. if dest_branch is None:
  887. dest_branch = branch.merge
  888. if not dest_branch.startswith(R_HEADS):
  889. dest_branch = R_HEADS + dest_branch
  890. if not branch.remote.projectname:
  891. branch.remote.projectname = self.name
  892. branch.remote.Save()
  893. url = branch.remote.ReviewUrl(self.UserEmail)
  894. if url is None:
  895. raise UploadError('review not configured')
  896. cmd = ['push']
  897. if url.startswith('ssh://'):
  898. rp = ['gerrit receive-pack']
  899. for e in people[0]:
  900. rp.append('--reviewer=%s' % sq(e))
  901. for e in people[1]:
  902. rp.append('--cc=%s' % sq(e))
  903. cmd.append('--receive-pack=%s' % " ".join(rp))
  904. cmd.append(url)
  905. if dest_branch.startswith(R_HEADS):
  906. dest_branch = dest_branch[len(R_HEADS):]
  907. upload_type = 'for'
  908. if draft:
  909. upload_type = 'drafts'
  910. ref_spec = '%s:refs/%s/%s' % (R_HEADS + branch.name, upload_type,
  911. dest_branch)
  912. if auto_topic:
  913. ref_spec = ref_spec + '/' + branch.name
  914. if not url.startswith('ssh://'):
  915. rp = ['r=%s' % p for p in people[0]] + \
  916. ['cc=%s' % p for p in people[1]]
  917. if rp:
  918. ref_spec = ref_spec + '%' + ','.join(rp)
  919. cmd.append(ref_spec)
  920. if GitCommand(self, cmd, bare=True).Wait() != 0:
  921. raise UploadError('Upload failed')
  922. msg = "posted to %s for %s" % (branch.remote.review, dest_branch)
  923. self.bare_git.UpdateRef(R_PUB + branch.name,
  924. R_HEADS + branch.name,
  925. message=msg)
  926. ## Sync ##
  927. def _ExtractArchive(self, tarpath, path=None):
  928. """Extract the given tar on its current location
  929. Args:
  930. - tarpath: The path to the actual tar file
  931. """
  932. try:
  933. with tarfile.open(tarpath, 'r') as tar:
  934. tar.extractall(path=path)
  935. return True
  936. except (IOError, tarfile.TarError) as e:
  937. print("error: Cannot extract archive %s: "
  938. "%s" % (tarpath, str(e)), file=sys.stderr)
  939. return False
  940. def Sync_NetworkHalf(self,
  941. quiet=False,
  942. is_new=None,
  943. current_branch_only=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()
  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):
  1057. """Perform only the local IO portion of the sync process.
  1058. Network access is not required.
  1059. """
  1060. self._InitWorkTree()
  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. if quiet:
  1613. cmd.append('--quiet')
  1614. if not self.worktree:
  1615. cmd.append('--update-head-ok')
  1616. cmd.append(name)
  1617. # If using depth then we should not get all the tags since they may
  1618. # be outside of the depth.
  1619. if no_tags or depth:
  1620. cmd.append('--no-tags')
  1621. else:
  1622. cmd.append('--tags')
  1623. spec = []
  1624. if not current_branch_only:
  1625. # Fetch whole repo
  1626. spec.append(str((u'+refs/heads/*:') + remote.ToLocal('refs/heads/*')))
  1627. elif tag_name is not None:
  1628. spec.append('tag')
  1629. spec.append(tag_name)
  1630. if not self.manifest.IsMirror:
  1631. branch = self.revisionExpr
  1632. if is_sha1 and depth and git_require((1, 8, 3)):
  1633. # Shallow checkout of a specific commit, fetch from that commit and not
  1634. # the heads only as the commit might be deeper in the history.
  1635. spec.append(branch)
  1636. else:
  1637. if is_sha1:
  1638. branch = self.upstream
  1639. if branch is not None and branch.strip():
  1640. if not branch.startswith('refs/'):
  1641. branch = R_HEADS + branch
  1642. spec.append(str((u'+%s:' % branch) + remote.ToLocal(branch)))
  1643. cmd.extend(spec)
  1644. shallowfetch = self.config.GetString('repo.shallowfetch')
  1645. if shallowfetch and shallowfetch != ' '.join(spec):
  1646. GitCommand(self, ['fetch', '--depth=2147483647', name]
  1647. + shallowfetch.split(),
  1648. bare=True, ssh_proxy=ssh_proxy).Wait()
  1649. if depth:
  1650. self.config.SetString('repo.shallowfetch', ' '.join(spec))
  1651. else:
  1652. self.config.SetString('repo.shallowfetch', None)
  1653. ok = False
  1654. for _i in range(2):
  1655. gitcmd = GitCommand(self, cmd, bare=True, ssh_proxy=ssh_proxy)
  1656. ret = gitcmd.Wait()
  1657. if ret == 0:
  1658. ok = True
  1659. break
  1660. # If needed, run the 'git remote prune' the first time through the loop
  1661. elif (not _i and
  1662. "error:" in gitcmd.stderr and
  1663. "git remote prune" in gitcmd.stderr):
  1664. prunecmd = GitCommand(self, ['remote', 'prune', name], bare=True,
  1665. ssh_proxy=ssh_proxy)
  1666. ret = prunecmd.Wait()
  1667. if ret:
  1668. break
  1669. continue
  1670. elif current_branch_only and is_sha1 and ret == 128:
  1671. # Exit code 128 means "couldn't find the ref you asked for"; if we're in sha1
  1672. # mode, we just tried sync'ing from the upstream field; it doesn't exist, thus
  1673. # abort the optimization attempt and do a full sync.
  1674. break
  1675. elif ret < 0:
  1676. # Git died with a signal, exit immediately
  1677. break
  1678. time.sleep(random.randint(30, 45))
  1679. if initial:
  1680. if alt_dir:
  1681. if old_packed != '':
  1682. _lwrite(packed_refs, old_packed)
  1683. else:
  1684. os.remove(packed_refs)
  1685. self.bare_git.pack_refs('--all', '--prune')
  1686. if is_sha1 and current_branch_only and self.upstream:
  1687. # We just synced the upstream given branch; verify we
  1688. # got what we wanted, else trigger a second run of all
  1689. # refs.
  1690. if not self._CheckForSha1():
  1691. if not depth:
  1692. # Avoid infinite recursion when depth is True (since depth implies
  1693. # current_branch_only)
  1694. return self._RemoteFetch(name=name, current_branch_only=False,
  1695. initial=False, quiet=quiet, alt_dir=alt_dir)
  1696. if self.clone_depth:
  1697. self.clone_depth = None
  1698. return self._RemoteFetch(name=name, current_branch_only=current_branch_only,
  1699. initial=False, quiet=quiet, alt_dir=alt_dir)
  1700. return ok
  1701. def _ApplyCloneBundle(self, initial=False, quiet=False):
  1702. if initial and (self.manifest.manifestProject.config.GetString('repo.depth') or self.clone_depth):
  1703. return False
  1704. remote = self.GetRemote(self.remote.name)
  1705. bundle_url = remote.url + '/clone.bundle'
  1706. bundle_url = GitConfig.ForUser().UrlInsteadOf(bundle_url)
  1707. if GetSchemeFromUrl(bundle_url) not in (
  1708. 'http', 'https', 'persistent-http', 'persistent-https'):
  1709. return False
  1710. bundle_dst = os.path.join(self.gitdir, 'clone.bundle')
  1711. bundle_tmp = os.path.join(self.gitdir, 'clone.bundle.tmp')
  1712. exist_dst = os.path.exists(bundle_dst)
  1713. exist_tmp = os.path.exists(bundle_tmp)
  1714. if not initial and not exist_dst and not exist_tmp:
  1715. return False
  1716. if not exist_dst:
  1717. exist_dst = self._FetchBundle(bundle_url, bundle_tmp, bundle_dst, quiet)
  1718. if not exist_dst:
  1719. return False
  1720. cmd = ['fetch']
  1721. if quiet:
  1722. cmd.append('--quiet')
  1723. if not self.worktree:
  1724. cmd.append('--update-head-ok')
  1725. cmd.append(bundle_dst)
  1726. for f in remote.fetch:
  1727. cmd.append(str(f))
  1728. cmd.append('refs/tags/*:refs/tags/*')
  1729. ok = GitCommand(self, cmd, bare=True).Wait() == 0
  1730. if os.path.exists(bundle_dst):
  1731. os.remove(bundle_dst)
  1732. if os.path.exists(bundle_tmp):
  1733. os.remove(bundle_tmp)
  1734. return ok
  1735. def _FetchBundle(self, srcUrl, tmpPath, dstPath, quiet):
  1736. if os.path.exists(dstPath):
  1737. os.remove(dstPath)
  1738. cmd = ['curl', '--fail', '--output', tmpPath, '--netrc', '--location']
  1739. if quiet:
  1740. cmd += ['--silent']
  1741. if os.path.exists(tmpPath):
  1742. size = os.stat(tmpPath).st_size
  1743. if size >= 1024:
  1744. cmd += ['--continue-at', '%d' % (size,)]
  1745. else:
  1746. os.remove(tmpPath)
  1747. if 'http_proxy' in os.environ and 'darwin' == sys.platform:
  1748. cmd += ['--proxy', os.environ['http_proxy']]
  1749. with self._GetBundleCookieFile(srcUrl, quiet) as cookiefile:
  1750. if cookiefile:
  1751. cmd += ['--cookie', cookiefile, '--cookie-jar', cookiefile]
  1752. if srcUrl.startswith('persistent-'):
  1753. srcUrl = srcUrl[len('persistent-'):]
  1754. cmd += [srcUrl]
  1755. if IsTrace():
  1756. Trace('%s', ' '.join(cmd))
  1757. try:
  1758. proc = subprocess.Popen(cmd)
  1759. except OSError:
  1760. return False
  1761. curlret = proc.wait()
  1762. if curlret == 22:
  1763. # From curl man page:
  1764. # 22: HTTP page not retrieved. The requested url was not found or
  1765. # returned another error with the HTTP error code being 400 or above.
  1766. # This return code only appears if -f, --fail is used.
  1767. if not quiet:
  1768. print("Server does not provide clone.bundle; ignoring.",
  1769. file=sys.stderr)
  1770. return False
  1771. if os.path.exists(tmpPath):
  1772. if curlret == 0 and self._IsValidBundle(tmpPath, quiet):
  1773. os.rename(tmpPath, dstPath)
  1774. return True
  1775. else:
  1776. os.remove(tmpPath)
  1777. return False
  1778. else:
  1779. return False
  1780. def _IsValidBundle(self, path, quiet):
  1781. try:
  1782. with open(path) as f:
  1783. if f.read(16) == '# v2 git bundle\n':
  1784. return True
  1785. else:
  1786. if not quiet:
  1787. print("Invalid clone.bundle file; ignoring.", file=sys.stderr)
  1788. return False
  1789. except OSError:
  1790. return False
  1791. @contextlib.contextmanager
  1792. def _GetBundleCookieFile(self, url, quiet):
  1793. if url.startswith('persistent-'):
  1794. try:
  1795. p = subprocess.Popen(
  1796. ['git-remote-persistent-https', '-print_config', url],
  1797. stdin=subprocess.PIPE, stdout=subprocess.PIPE,
  1798. stderr=subprocess.PIPE)
  1799. try:
  1800. prefix = 'http.cookiefile='
  1801. cookiefile = None
  1802. for line in p.stdout:
  1803. line = line.strip()
  1804. if line.startswith(prefix):
  1805. cookiefile = line[len(prefix):]
  1806. break
  1807. # Leave subprocess open, as cookie file may be transient.
  1808. if cookiefile:
  1809. yield cookiefile
  1810. return
  1811. finally:
  1812. p.stdin.close()
  1813. if p.wait():
  1814. err_msg = p.stderr.read()
  1815. if ' -print_config' in err_msg:
  1816. pass # Persistent proxy doesn't support -print_config.
  1817. elif not quiet:
  1818. print(err_msg, file=sys.stderr)
  1819. except OSError as e:
  1820. if e.errno == errno.ENOENT:
  1821. pass # No persistent proxy.
  1822. raise
  1823. yield GitConfig.ForUser().GetString('http.cookiefile')
  1824. def _Checkout(self, rev, quiet=False):
  1825. cmd = ['checkout']
  1826. if quiet:
  1827. cmd.append('-q')
  1828. cmd.append(rev)
  1829. cmd.append('--')
  1830. if GitCommand(self, cmd).Wait() != 0:
  1831. if self._allrefs:
  1832. raise GitError('%s checkout %s ' % (self.name, rev))
  1833. def _CherryPick(self, rev):
  1834. cmd = ['cherry-pick']
  1835. cmd.append(rev)
  1836. cmd.append('--')
  1837. if GitCommand(self, cmd).Wait() != 0:
  1838. if self._allrefs:
  1839. raise GitError('%s cherry-pick %s ' % (self.name, rev))
  1840. def _Revert(self, rev):
  1841. cmd = ['revert']
  1842. cmd.append('--no-edit')
  1843. cmd.append(rev)
  1844. cmd.append('--')
  1845. if GitCommand(self, cmd).Wait() != 0:
  1846. if self._allrefs:
  1847. raise GitError('%s revert %s ' % (self.name, rev))
  1848. def _ResetHard(self, rev, quiet=True):
  1849. cmd = ['reset', '--hard']
  1850. if quiet:
  1851. cmd.append('-q')
  1852. cmd.append(rev)
  1853. if GitCommand(self, cmd).Wait() != 0:
  1854. raise GitError('%s reset --hard %s ' % (self.name, rev))
  1855. def _Rebase(self, upstream, onto=None):
  1856. cmd = ['rebase']
  1857. if onto is not None:
  1858. cmd.extend(['--onto', onto])
  1859. cmd.append(upstream)
  1860. if GitCommand(self, cmd).Wait() != 0:
  1861. raise GitError('%s rebase %s ' % (self.name, upstream))
  1862. def _FastForward(self, head, ffonly=False):
  1863. cmd = ['merge', head]
  1864. if ffonly:
  1865. cmd.append("--ff-only")
  1866. if GitCommand(self, cmd).Wait() != 0:
  1867. raise GitError('%s merge %s ' % (self.name, head))
  1868. def _InitGitDir(self, mirror_git=None):
  1869. init_git_dir = not os.path.exists(self.gitdir)
  1870. init_obj_dir = not os.path.exists(self.objdir)
  1871. # Initialize the bare repository, which contains all of the objects.
  1872. if init_obj_dir:
  1873. os.makedirs(self.objdir)
  1874. self.bare_objdir.init()
  1875. # If we have a separate directory to hold refs, initialize it as well.
  1876. if self.objdir != self.gitdir:
  1877. if init_git_dir:
  1878. os.makedirs(self.gitdir)
  1879. if init_obj_dir or init_git_dir:
  1880. self._ReferenceGitDir(self.objdir, self.gitdir, share_refs=False,
  1881. copy_all=True)
  1882. self._CheckDirReference(self.objdir, self.gitdir, share_refs=False)
  1883. if init_git_dir:
  1884. mp = self.manifest.manifestProject
  1885. ref_dir = mp.config.GetString('repo.reference') or ''
  1886. if ref_dir or mirror_git:
  1887. if not mirror_git:
  1888. mirror_git = os.path.join(ref_dir, self.name + '.git')
  1889. repo_git = os.path.join(ref_dir, '.repo', 'projects',
  1890. self.relpath + '.git')
  1891. if os.path.exists(mirror_git):
  1892. ref_dir = mirror_git
  1893. elif os.path.exists(repo_git):
  1894. ref_dir = repo_git
  1895. else:
  1896. ref_dir = None
  1897. if ref_dir:
  1898. _lwrite(os.path.join(self.gitdir, 'objects/info/alternates'),
  1899. os.path.join(ref_dir, 'objects') + '\n')
  1900. self._UpdateHooks()
  1901. m = self.manifest.manifestProject.config
  1902. for key in ['user.name', 'user.email']:
  1903. if m.Has(key, include_defaults=False):
  1904. self.config.SetString(key, m.GetString(key))
  1905. if self.manifest.IsMirror:
  1906. self.config.SetString('core.bare', 'true')
  1907. else:
  1908. self.config.SetString('core.bare', None)
  1909. def _UpdateHooks(self):
  1910. if os.path.exists(self.gitdir):
  1911. self._InitHooks()
  1912. def _InitHooks(self):
  1913. hooks = os.path.realpath(self._gitdir_path('hooks'))
  1914. if not os.path.exists(hooks):
  1915. os.makedirs(hooks)
  1916. for stock_hook in _ProjectHooks():
  1917. name = os.path.basename(stock_hook)
  1918. if name in ('commit-msg',) and not self.remote.review \
  1919. and not self is self.manifest.manifestProject:
  1920. # Don't install a Gerrit Code Review hook if this
  1921. # project does not appear to use it for reviews.
  1922. #
  1923. # Since the manifest project is one of those, but also
  1924. # managed through gerrit, it's excluded
  1925. continue
  1926. dst = os.path.join(hooks, name)
  1927. if os.path.islink(dst):
  1928. continue
  1929. if os.path.exists(dst):
  1930. if filecmp.cmp(stock_hook, dst, shallow=False):
  1931. os.remove(dst)
  1932. else:
  1933. _error("%s: Not replacing %s hook", self.relpath, name)
  1934. continue
  1935. try:
  1936. os.symlink(os.path.relpath(stock_hook, os.path.dirname(dst)), dst)
  1937. except OSError as e:
  1938. if e.errno == errno.EPERM:
  1939. raise GitError('filesystem must support symlinks')
  1940. else:
  1941. raise
  1942. def _InitRemote(self):
  1943. if self.remote.url:
  1944. remote = self.GetRemote(self.remote.name)
  1945. remote.url = self.remote.url
  1946. remote.review = self.remote.review
  1947. remote.projectname = self.name
  1948. if self.worktree:
  1949. remote.ResetFetch(mirror=False)
  1950. else:
  1951. remote.ResetFetch(mirror=True)
  1952. remote.Save()
  1953. def _InitMRef(self):
  1954. if self.manifest.branch:
  1955. self._InitAnyMRef(R_M + self.manifest.branch)
  1956. def _InitMirrorHead(self):
  1957. self._InitAnyMRef(HEAD)
  1958. def _InitAnyMRef(self, ref):
  1959. cur = self.bare_ref.symref(ref)
  1960. if self.revisionId:
  1961. if cur != '' or self.bare_ref.get(ref) != self.revisionId:
  1962. msg = 'manifest set to %s' % self.revisionId
  1963. dst = self.revisionId + '^0'
  1964. self.bare_git.UpdateRef(ref, dst, message=msg, detach=True)
  1965. else:
  1966. remote = self.GetRemote(self.remote.name)
  1967. dst = remote.ToLocal(self.revisionExpr)
  1968. if cur != dst:
  1969. msg = 'manifest set to %s' % self.revisionExpr
  1970. self.bare_git.symbolic_ref('-m', msg, ref, dst)
  1971. def _CheckDirReference(self, srcdir, destdir, share_refs):
  1972. symlink_files = self.shareable_files
  1973. symlink_dirs = self.shareable_dirs
  1974. if share_refs:
  1975. symlink_files += self.working_tree_files
  1976. symlink_dirs += self.working_tree_dirs
  1977. to_symlink = symlink_files + symlink_dirs
  1978. for name in set(to_symlink):
  1979. dst = os.path.realpath(os.path.join(destdir, name))
  1980. if os.path.lexists(dst):
  1981. src = os.path.realpath(os.path.join(srcdir, name))
  1982. # Fail if the links are pointing to the wrong place
  1983. if src != dst:
  1984. raise GitError('cannot overwrite a local work tree')
  1985. def _ReferenceGitDir(self, gitdir, dotgit, share_refs, copy_all):
  1986. """Update |dotgit| to reference |gitdir|, using symlinks where possible.
  1987. Args:
  1988. gitdir: The bare git repository. Must already be initialized.
  1989. dotgit: The repository you would like to initialize.
  1990. share_refs: If true, |dotgit| will store its refs under |gitdir|.
  1991. Only one work tree can store refs under a given |gitdir|.
  1992. copy_all: If true, copy all remaining files from |gitdir| -> |dotgit|.
  1993. This saves you the effort of initializing |dotgit| yourself.
  1994. """
  1995. symlink_files = self.shareable_files
  1996. symlink_dirs = self.shareable_dirs
  1997. if share_refs:
  1998. symlink_files += self.working_tree_files
  1999. symlink_dirs += self.working_tree_dirs
  2000. to_symlink = symlink_files + symlink_dirs
  2001. to_copy = []
  2002. if copy_all:
  2003. to_copy = os.listdir(gitdir)
  2004. for name in set(to_copy).union(to_symlink):
  2005. try:
  2006. src = os.path.realpath(os.path.join(gitdir, name))
  2007. dst = os.path.realpath(os.path.join(dotgit, name))
  2008. if os.path.lexists(dst):
  2009. continue
  2010. # If the source dir doesn't exist, create an empty dir.
  2011. if name in symlink_dirs and not os.path.lexists(src):
  2012. os.makedirs(src)
  2013. # If the source file doesn't exist, ensure the destination
  2014. # file doesn't either.
  2015. if name in symlink_files and not os.path.lexists(src):
  2016. try:
  2017. os.remove(dst)
  2018. except OSError:
  2019. pass
  2020. if name in to_symlink:
  2021. os.symlink(os.path.relpath(src, os.path.dirname(dst)), dst)
  2022. elif copy_all and not os.path.islink(dst):
  2023. if os.path.isdir(src):
  2024. shutil.copytree(src, dst)
  2025. elif os.path.isfile(src):
  2026. shutil.copy(src, dst)
  2027. except OSError as e:
  2028. if e.errno == errno.EPERM:
  2029. raise GitError('filesystem must support symlinks')
  2030. else:
  2031. raise
  2032. def _InitWorkTree(self):
  2033. dotgit = os.path.join(self.worktree, '.git')
  2034. init_dotgit = not os.path.exists(dotgit)
  2035. if init_dotgit:
  2036. os.makedirs(dotgit)
  2037. self._ReferenceGitDir(self.gitdir, dotgit, share_refs=True,
  2038. copy_all=False)
  2039. self._CheckDirReference(self.gitdir, dotgit, share_refs=True)
  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. def _gitdir_path(self, path):
  2049. return os.path.realpath(os.path.join(self.gitdir, path))
  2050. def _revlist(self, *args, **kw):
  2051. a = []
  2052. a.extend(args)
  2053. a.append('--')
  2054. return self.work_git.rev_list(*a, **kw)
  2055. @property
  2056. def _allrefs(self):
  2057. return self.bare_ref.all
  2058. def _getLogs(self, rev1, rev2, oneline=False, color=True):
  2059. """Get logs between two revisions of this project."""
  2060. comp = '..'
  2061. if rev1:
  2062. revs = [rev1]
  2063. if rev2:
  2064. revs.extend([comp, rev2])
  2065. cmd = ['log', ''.join(revs)]
  2066. out = DiffColoring(self.config)
  2067. if out.is_on and color:
  2068. cmd.append('--color')
  2069. if oneline:
  2070. cmd.append('--oneline')
  2071. try:
  2072. log = GitCommand(self, cmd, capture_stdout=True, capture_stderr=True)
  2073. if log.Wait() == 0:
  2074. return log.stdout
  2075. except GitError:
  2076. # worktree may not exist if groups changed for example. In that case,
  2077. # try in gitdir instead.
  2078. if not os.path.exists(self.worktree):
  2079. return self.bare_git.log(*cmd[1:])
  2080. else:
  2081. raise
  2082. return None
  2083. def getAddedAndRemovedLogs(self, toProject, oneline=False, color=True):
  2084. """Get the list of logs from this revision to given revisionId"""
  2085. logs = {}
  2086. selfId = self.GetRevisionId(self._allrefs)
  2087. toId = toProject.GetRevisionId(toProject._allrefs)
  2088. logs['added'] = self._getLogs(selfId, toId, oneline=oneline, color=color)
  2089. logs['removed'] = self._getLogs(toId, selfId, oneline=oneline, color=color)
  2090. return logs
  2091. class _GitGetByExec(object):
  2092. def __init__(self, project, bare, gitdir):
  2093. self._project = project
  2094. self._bare = bare
  2095. self._gitdir = gitdir
  2096. def LsOthers(self):
  2097. p = GitCommand(self._project,
  2098. ['ls-files',
  2099. '-z',
  2100. '--others',
  2101. '--exclude-standard'],
  2102. bare=False,
  2103. gitdir=self._gitdir,
  2104. capture_stdout=True,
  2105. capture_stderr=True)
  2106. if p.Wait() == 0:
  2107. out = p.stdout
  2108. if out:
  2109. return out[:-1].split('\0') # pylint: disable=W1401
  2110. # Backslash is not anomalous
  2111. return []
  2112. def DiffZ(self, name, *args):
  2113. cmd = [name]
  2114. cmd.append('-z')
  2115. cmd.extend(args)
  2116. p = GitCommand(self._project,
  2117. cmd,
  2118. gitdir=self._gitdir,
  2119. bare=False,
  2120. capture_stdout=True,
  2121. capture_stderr=True)
  2122. try:
  2123. out = p.process.stdout.read()
  2124. r = {}
  2125. if out:
  2126. out = iter(out[:-1].split('\0')) # pylint: disable=W1401
  2127. while out:
  2128. try:
  2129. info = next(out)
  2130. path = next(out)
  2131. except StopIteration:
  2132. break
  2133. class _Info(object):
  2134. def __init__(self, path, omode, nmode, oid, nid, state):
  2135. self.path = path
  2136. self.src_path = None
  2137. self.old_mode = omode
  2138. self.new_mode = nmode
  2139. self.old_id = oid
  2140. self.new_id = nid
  2141. if len(state) == 1:
  2142. self.status = state
  2143. self.level = None
  2144. else:
  2145. self.status = state[:1]
  2146. self.level = state[1:]
  2147. while self.level.startswith('0'):
  2148. self.level = self.level[1:]
  2149. info = info[1:].split(' ')
  2150. info = _Info(path, *info)
  2151. if info.status in ('R', 'C'):
  2152. info.src_path = info.path
  2153. info.path = next(out)
  2154. r[info.path] = info
  2155. return r
  2156. finally:
  2157. p.Wait()
  2158. def GetHead(self):
  2159. if self._bare:
  2160. path = os.path.join(self._project.gitdir, HEAD)
  2161. else:
  2162. path = os.path.join(self._project.worktree, '.git', HEAD)
  2163. try:
  2164. fd = open(path, 'rb')
  2165. except IOError as e:
  2166. raise NoManifestException(path, str(e))
  2167. try:
  2168. line = fd.read()
  2169. finally:
  2170. fd.close()
  2171. try:
  2172. line = line.decode()
  2173. except AttributeError:
  2174. pass
  2175. if line.startswith('ref: '):
  2176. return line[5:-1]
  2177. return line[:-1]
  2178. def SetHead(self, ref, message=None):
  2179. cmdv = []
  2180. if message is not None:
  2181. cmdv.extend(['-m', message])
  2182. cmdv.append(HEAD)
  2183. cmdv.append(ref)
  2184. self.symbolic_ref(*cmdv)
  2185. def DetachHead(self, new, message=None):
  2186. cmdv = ['--no-deref']
  2187. if message is not None:
  2188. cmdv.extend(['-m', message])
  2189. cmdv.append(HEAD)
  2190. cmdv.append(new)
  2191. self.update_ref(*cmdv)
  2192. def UpdateRef(self, name, new, old=None,
  2193. message=None,
  2194. detach=False):
  2195. cmdv = []
  2196. if message is not None:
  2197. cmdv.extend(['-m', message])
  2198. if detach:
  2199. cmdv.append('--no-deref')
  2200. cmdv.append(name)
  2201. cmdv.append(new)
  2202. if old is not None:
  2203. cmdv.append(old)
  2204. self.update_ref(*cmdv)
  2205. def DeleteRef(self, name, old=None):
  2206. if not old:
  2207. old = self.rev_parse(name)
  2208. self.update_ref('-d', name, old)
  2209. self._project.bare_ref.deleted(name)
  2210. def rev_list(self, *args, **kw):
  2211. if 'format' in kw:
  2212. cmdv = ['log', '--pretty=format:%s' % kw['format']]
  2213. else:
  2214. cmdv = ['rev-list']
  2215. cmdv.extend(args)
  2216. p = GitCommand(self._project,
  2217. cmdv,
  2218. bare=self._bare,
  2219. gitdir=self._gitdir,
  2220. capture_stdout=True,
  2221. capture_stderr=True)
  2222. r = []
  2223. for line in p.process.stdout:
  2224. if line[-1] == '\n':
  2225. line = line[:-1]
  2226. r.append(line)
  2227. if p.Wait() != 0:
  2228. raise GitError('%s rev-list %s: %s' % (
  2229. self._project.name,
  2230. str(args),
  2231. p.stderr))
  2232. return r
  2233. def __getattr__(self, name):
  2234. """Allow arbitrary git commands using pythonic syntax.
  2235. This allows you to do things like:
  2236. git_obj.rev_parse('HEAD')
  2237. Since we don't have a 'rev_parse' method defined, the __getattr__ will
  2238. run. We'll replace the '_' with a '-' and try to run a git command.
  2239. Any other positional arguments will be passed to the git command, and the
  2240. following keyword arguments are supported:
  2241. config: An optional dict of git config options to be passed with '-c'.
  2242. Args:
  2243. name: The name of the git command to call. Any '_' characters will
  2244. be replaced with '-'.
  2245. Returns:
  2246. A callable object that will try to call git with the named command.
  2247. """
  2248. name = name.replace('_', '-')
  2249. def runner(*args, **kwargs):
  2250. cmdv = []
  2251. config = kwargs.pop('config', None)
  2252. for k in kwargs:
  2253. raise TypeError('%s() got an unexpected keyword argument %r'
  2254. % (name, k))
  2255. if config is not None:
  2256. if not git_require((1, 7, 2)):
  2257. raise ValueError('cannot set config on command line for %s()'
  2258. % name)
  2259. for k, v in config.items():
  2260. cmdv.append('-c')
  2261. cmdv.append('%s=%s' % (k, v))
  2262. cmdv.append(name)
  2263. cmdv.extend(args)
  2264. p = GitCommand(self._project,
  2265. cmdv,
  2266. bare=self._bare,
  2267. gitdir=self._gitdir,
  2268. capture_stdout=True,
  2269. capture_stderr=True)
  2270. if p.Wait() != 0:
  2271. raise GitError('%s %s: %s' % (
  2272. self._project.name,
  2273. name,
  2274. p.stderr))
  2275. r = p.stdout
  2276. try:
  2277. r = r.decode('utf-8')
  2278. except AttributeError:
  2279. pass
  2280. if r.endswith('\n') and r.index('\n') == len(r) - 1:
  2281. return r[:-1]
  2282. return r
  2283. return runner
  2284. class _PriorSyncFailedError(Exception):
  2285. def __str__(self):
  2286. return 'prior sync failed; rebase still in progress'
  2287. class _DirtyError(Exception):
  2288. def __str__(self):
  2289. return 'contains uncommitted changes'
  2290. class _InfoMessage(object):
  2291. def __init__(self, project, text):
  2292. self.project = project
  2293. self.text = text
  2294. def Print(self, syncbuf):
  2295. syncbuf.out.info('%s/: %s', self.project.relpath, self.text)
  2296. syncbuf.out.nl()
  2297. class _Failure(object):
  2298. def __init__(self, project, why):
  2299. self.project = project
  2300. self.why = why
  2301. def Print(self, syncbuf):
  2302. syncbuf.out.fail('error: %s/: %s',
  2303. self.project.relpath,
  2304. str(self.why))
  2305. syncbuf.out.nl()
  2306. class _Later(object):
  2307. def __init__(self, project, action):
  2308. self.project = project
  2309. self.action = action
  2310. def Run(self, syncbuf):
  2311. out = syncbuf.out
  2312. out.project('project %s/', self.project.relpath)
  2313. out.nl()
  2314. try:
  2315. self.action()
  2316. out.nl()
  2317. return True
  2318. except GitError:
  2319. out.nl()
  2320. return False
  2321. class _SyncColoring(Coloring):
  2322. def __init__(self, config):
  2323. Coloring.__init__(self, config, 'reposync')
  2324. self.project = self.printer('header', attr='bold')
  2325. self.info = self.printer('info')
  2326. self.fail = self.printer('fail', fg='red')
  2327. class SyncBuffer(object):
  2328. def __init__(self, config, detach_head=False):
  2329. self._messages = []
  2330. self._failures = []
  2331. self._later_queue1 = []
  2332. self._later_queue2 = []
  2333. self.out = _SyncColoring(config)
  2334. self.out.redirect(sys.stderr)
  2335. self.detach_head = detach_head
  2336. self.clean = True
  2337. def info(self, project, fmt, *args):
  2338. self._messages.append(_InfoMessage(project, fmt % args))
  2339. def fail(self, project, err=None):
  2340. self._failures.append(_Failure(project, err))
  2341. self.clean = False
  2342. def later1(self, project, what):
  2343. self._later_queue1.append(_Later(project, what))
  2344. def later2(self, project, what):
  2345. self._later_queue2.append(_Later(project, what))
  2346. def Finish(self):
  2347. self._PrintMessages()
  2348. self._RunLater()
  2349. self._PrintMessages()
  2350. return self.clean
  2351. def _RunLater(self):
  2352. for q in ['_later_queue1', '_later_queue2']:
  2353. if not self._RunQueue(q):
  2354. return
  2355. def _RunQueue(self, queue):
  2356. for m in getattr(self, queue):
  2357. if not m.Run(self):
  2358. self.clean = False
  2359. return False
  2360. setattr(self, queue, [])
  2361. return True
  2362. def _PrintMessages(self):
  2363. for m in self._messages:
  2364. m.Print(self)
  2365. for m in self._failures:
  2366. m.Print(self)
  2367. self._messages = []
  2368. self._failures = []
  2369. class MetaProject(Project):
  2370. """A special project housed under .repo.
  2371. """
  2372. def __init__(self, manifest, name, gitdir, worktree):
  2373. Project.__init__(self,
  2374. manifest=manifest,
  2375. name=name,
  2376. gitdir=gitdir,
  2377. objdir=gitdir,
  2378. worktree=worktree,
  2379. remote=RemoteSpec('origin'),
  2380. relpath='.repo/%s' % name,
  2381. revisionExpr='refs/heads/master',
  2382. revisionId=None,
  2383. groups=None)
  2384. def PreSync(self):
  2385. if self.Exists:
  2386. cb = self.CurrentBranch
  2387. if cb:
  2388. base = self.GetBranch(cb).merge
  2389. if base:
  2390. self.revisionExpr = base
  2391. self.revisionId = None
  2392. def MetaBranchSwitch(self):
  2393. """ Prepare MetaProject for manifest branch switch
  2394. """
  2395. # detach and delete manifest branch, allowing a new
  2396. # branch to take over
  2397. syncbuf = SyncBuffer(self.config, detach_head=True)
  2398. self.Sync_LocalHalf(syncbuf)
  2399. syncbuf.Finish()
  2400. return GitCommand(self,
  2401. ['update-ref', '-d', 'refs/heads/default'],
  2402. capture_stdout=True,
  2403. capture_stderr=True).Wait() == 0
  2404. @property
  2405. def LastFetch(self):
  2406. try:
  2407. fh = os.path.join(self.gitdir, 'FETCH_HEAD')
  2408. return os.path.getmtime(fh)
  2409. except OSError:
  2410. return 0
  2411. @property
  2412. def HasChanges(self):
  2413. """Has the remote received new commits not yet checked out?
  2414. """
  2415. if not self.remote or not self.revisionExpr:
  2416. return False
  2417. all_refs = self.bare_ref.all
  2418. revid = self.GetRevisionId(all_refs)
  2419. head = self.work_git.GetHead()
  2420. if head.startswith(R_HEADS):
  2421. try:
  2422. head = all_refs[head]
  2423. except KeyError:
  2424. head = None
  2425. if revid == head:
  2426. return False
  2427. elif self._revlist(not_rev(HEAD), revid):
  2428. return True
  2429. return False