project.py 88 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855
  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, DownloadError
  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. force_sync=False,
  945. clone_bundle=True,
  946. no_tags=False,
  947. archive=False,
  948. optimized_fetch=False):
  949. """Perform only the network IO portion of the sync process.
  950. Local working directory/branch state is not affected.
  951. """
  952. if archive and not isinstance(self, MetaProject):
  953. if self.remote.url.startswith(('http://', 'https://')):
  954. print("error: %s: Cannot fetch archives from http/https "
  955. "remotes." % self.name, file=sys.stderr)
  956. return False
  957. name = self.relpath.replace('\\', '/')
  958. name = name.replace('/', '_')
  959. tarpath = '%s.tar' % name
  960. topdir = self.manifest.topdir
  961. try:
  962. self._FetchArchive(tarpath, cwd=topdir)
  963. except GitError as e:
  964. print('error: %s' % str(e), file=sys.stderr)
  965. return False
  966. # From now on, we only need absolute tarpath
  967. tarpath = os.path.join(topdir, tarpath)
  968. if not self._ExtractArchive(tarpath, path=topdir):
  969. return False
  970. try:
  971. os.remove(tarpath)
  972. except OSError as e:
  973. print("warn: Cannot remove archive %s: "
  974. "%s" % (tarpath, str(e)), file=sys.stderr)
  975. self._CopyAndLinkFiles()
  976. return True
  977. if is_new is None:
  978. is_new = not self.Exists
  979. if is_new:
  980. self._InitGitDir(force_sync=force_sync)
  981. else:
  982. self._UpdateHooks()
  983. self._InitRemote()
  984. if is_new:
  985. alt = os.path.join(self.gitdir, 'objects/info/alternates')
  986. try:
  987. fd = open(alt, 'rb')
  988. try:
  989. alt_dir = fd.readline().rstrip()
  990. finally:
  991. fd.close()
  992. except IOError:
  993. alt_dir = None
  994. else:
  995. alt_dir = None
  996. if clone_bundle \
  997. and alt_dir is None \
  998. and self._ApplyCloneBundle(initial=is_new, quiet=quiet):
  999. is_new = False
  1000. if not current_branch_only:
  1001. if self.sync_c:
  1002. current_branch_only = True
  1003. elif not self.manifest._loaded:
  1004. # Manifest cannot check defaults until it syncs.
  1005. current_branch_only = False
  1006. elif self.manifest.default.sync_c:
  1007. current_branch_only = True
  1008. need_to_fetch = not (optimized_fetch and \
  1009. (ID_RE.match(self.revisionExpr) and self._CheckForSha1()))
  1010. if (need_to_fetch
  1011. and not self._RemoteFetch(initial=is_new, quiet=quiet, alt_dir=alt_dir,
  1012. current_branch_only=current_branch_only,
  1013. no_tags=no_tags)):
  1014. return False
  1015. if self.worktree:
  1016. self._InitMRef()
  1017. else:
  1018. self._InitMirrorHead()
  1019. try:
  1020. os.remove(os.path.join(self.gitdir, 'FETCH_HEAD'))
  1021. except OSError:
  1022. pass
  1023. return True
  1024. def PostRepoUpgrade(self):
  1025. self._InitHooks()
  1026. def _CopyAndLinkFiles(self):
  1027. for copyfile in self.copyfiles:
  1028. copyfile._Copy()
  1029. for linkfile in self.linkfiles:
  1030. linkfile._Link()
  1031. def GetCommitRevisionId(self):
  1032. """Get revisionId of a commit.
  1033. Use this method instead of GetRevisionId to get the id of the commit rather
  1034. than the id of the current git object (for example, a tag)
  1035. """
  1036. if not self.revisionExpr.startswith(R_TAGS):
  1037. return self.GetRevisionId(self._allrefs)
  1038. try:
  1039. return self.bare_git.rev_list(self.revisionExpr, '-1')[0]
  1040. except GitError:
  1041. raise ManifestInvalidRevisionError(
  1042. 'revision %s in %s not found' % (self.revisionExpr,
  1043. self.name))
  1044. def GetRevisionId(self, all_refs=None):
  1045. if self.revisionId:
  1046. return self.revisionId
  1047. rem = self.GetRemote(self.remote.name)
  1048. rev = rem.ToLocal(self.revisionExpr)
  1049. if all_refs is not None and rev in all_refs:
  1050. return all_refs[rev]
  1051. try:
  1052. return self.bare_git.rev_parse('--verify', '%s^0' % rev)
  1053. except GitError:
  1054. raise ManifestInvalidRevisionError(
  1055. 'revision %s in %s not found' % (self.revisionExpr,
  1056. self.name))
  1057. def Sync_LocalHalf(self, syncbuf, force_sync=False):
  1058. """Perform only the local IO portion of the sync process.
  1059. Network access is not required.
  1060. """
  1061. self._InitWorkTree(force_sync=force_sync)
  1062. all_refs = self.bare_ref.all
  1063. self.CleanPublishedCache(all_refs)
  1064. revid = self.GetRevisionId(all_refs)
  1065. def _doff():
  1066. self._FastForward(revid)
  1067. self._CopyAndLinkFiles()
  1068. head = self.work_git.GetHead()
  1069. if head.startswith(R_HEADS):
  1070. branch = head[len(R_HEADS):]
  1071. try:
  1072. head = all_refs[head]
  1073. except KeyError:
  1074. head = None
  1075. else:
  1076. branch = None
  1077. if branch is None or syncbuf.detach_head:
  1078. # Currently on a detached HEAD. The user is assumed to
  1079. # not have any local modifications worth worrying about.
  1080. #
  1081. if self.IsRebaseInProgress():
  1082. syncbuf.fail(self, _PriorSyncFailedError())
  1083. return
  1084. if head == revid:
  1085. # No changes; don't do anything further.
  1086. # Except if the head needs to be detached
  1087. #
  1088. if not syncbuf.detach_head:
  1089. return
  1090. else:
  1091. lost = self._revlist(not_rev(revid), HEAD)
  1092. if lost:
  1093. syncbuf.info(self, "discarding %d commits", len(lost))
  1094. try:
  1095. self._Checkout(revid, quiet=True)
  1096. except GitError as e:
  1097. syncbuf.fail(self, e)
  1098. return
  1099. self._CopyAndLinkFiles()
  1100. return
  1101. if head == revid:
  1102. # No changes; don't do anything further.
  1103. #
  1104. return
  1105. branch = self.GetBranch(branch)
  1106. if not branch.LocalMerge:
  1107. # The current branch has no tracking configuration.
  1108. # Jump off it to a detached HEAD.
  1109. #
  1110. syncbuf.info(self,
  1111. "leaving %s; does not track upstream",
  1112. branch.name)
  1113. try:
  1114. self._Checkout(revid, quiet=True)
  1115. except GitError as e:
  1116. syncbuf.fail(self, e)
  1117. return
  1118. self._CopyAndLinkFiles()
  1119. return
  1120. upstream_gain = self._revlist(not_rev(HEAD), revid)
  1121. pub = self.WasPublished(branch.name, all_refs)
  1122. if pub:
  1123. not_merged = self._revlist(not_rev(revid), pub)
  1124. if not_merged:
  1125. if upstream_gain:
  1126. # The user has published this branch and some of those
  1127. # commits are not yet merged upstream. We do not want
  1128. # to rewrite the published commits so we punt.
  1129. #
  1130. syncbuf.fail(self,
  1131. "branch %s is published (but not merged) and is now %d commits behind"
  1132. % (branch.name, len(upstream_gain)))
  1133. return
  1134. elif pub == head:
  1135. # All published commits are merged, and thus we are a
  1136. # strict subset. We can fast-forward safely.
  1137. #
  1138. syncbuf.later1(self, _doff)
  1139. return
  1140. # Examine the local commits not in the remote. Find the
  1141. # last one attributed to this user, if any.
  1142. #
  1143. local_changes = self._revlist(not_rev(revid), HEAD, format='%H %ce')
  1144. last_mine = None
  1145. cnt_mine = 0
  1146. for commit in local_changes:
  1147. commit_id, committer_email = commit.decode('utf-8').split(' ', 1)
  1148. if committer_email == self.UserEmail:
  1149. last_mine = commit_id
  1150. cnt_mine += 1
  1151. if not upstream_gain and cnt_mine == len(local_changes):
  1152. return
  1153. if self.IsDirty(consider_untracked=False):
  1154. syncbuf.fail(self, _DirtyError())
  1155. return
  1156. # If the upstream switched on us, warn the user.
  1157. #
  1158. if branch.merge != self.revisionExpr:
  1159. if branch.merge and self.revisionExpr:
  1160. syncbuf.info(self,
  1161. 'manifest switched %s...%s',
  1162. branch.merge,
  1163. self.revisionExpr)
  1164. elif branch.merge:
  1165. syncbuf.info(self,
  1166. 'manifest no longer tracks %s',
  1167. branch.merge)
  1168. if cnt_mine < len(local_changes):
  1169. # Upstream rebased. Not everything in HEAD
  1170. # was created by this user.
  1171. #
  1172. syncbuf.info(self,
  1173. "discarding %d commits removed from upstream",
  1174. len(local_changes) - cnt_mine)
  1175. branch.remote = self.GetRemote(self.remote.name)
  1176. if not ID_RE.match(self.revisionExpr):
  1177. # in case of manifest sync the revisionExpr might be a SHA1
  1178. branch.merge = self.revisionExpr
  1179. if not branch.merge.startswith('refs/'):
  1180. branch.merge = R_HEADS + branch.merge
  1181. branch.Save()
  1182. if cnt_mine > 0 and self.rebase:
  1183. def _dorebase():
  1184. self._Rebase(upstream='%s^1' % last_mine, onto=revid)
  1185. self._CopyAndLinkFiles()
  1186. syncbuf.later2(self, _dorebase)
  1187. elif local_changes:
  1188. try:
  1189. self._ResetHard(revid)
  1190. self._CopyAndLinkFiles()
  1191. except GitError as e:
  1192. syncbuf.fail(self, e)
  1193. return
  1194. else:
  1195. syncbuf.later1(self, _doff)
  1196. def AddCopyFile(self, src, dest, absdest):
  1197. # dest should already be an absolute path, but src is project relative
  1198. # make src an absolute path
  1199. abssrc = os.path.join(self.worktree, src)
  1200. self.copyfiles.append(_CopyFile(src, dest, abssrc, absdest))
  1201. def AddLinkFile(self, src, dest, absdest):
  1202. # dest should already be an absolute path, but src is project relative
  1203. # make src relative path to dest
  1204. absdestdir = os.path.dirname(absdest)
  1205. relsrc = os.path.relpath(os.path.join(self.worktree, src), absdestdir)
  1206. self.linkfiles.append(_LinkFile(self.worktree, src, dest, relsrc, absdest))
  1207. def AddAnnotation(self, name, value, keep):
  1208. self.annotations.append(_Annotation(name, value, keep))
  1209. def DownloadPatchSet(self, change_id, patch_id):
  1210. """Download a single patch set of a single change to FETCH_HEAD.
  1211. """
  1212. remote = self.GetRemote(self.remote.name)
  1213. cmd = ['fetch', remote.name]
  1214. cmd.append('refs/changes/%2.2d/%d/%d' \
  1215. % (change_id % 100, change_id, patch_id))
  1216. if GitCommand(self, cmd, bare=True).Wait() != 0:
  1217. return None
  1218. return DownloadedChange(self,
  1219. self.GetRevisionId(),
  1220. change_id,
  1221. patch_id,
  1222. self.bare_git.rev_parse('FETCH_HEAD'))
  1223. ## Branch Management ##
  1224. def StartBranch(self, name):
  1225. """Create a new branch off the manifest's revision.
  1226. """
  1227. head = self.work_git.GetHead()
  1228. if head == (R_HEADS + name):
  1229. return True
  1230. all_refs = self.bare_ref.all
  1231. if R_HEADS + name in all_refs:
  1232. return GitCommand(self,
  1233. ['checkout', name, '--'],
  1234. capture_stdout=True,
  1235. capture_stderr=True).Wait() == 0
  1236. branch = self.GetBranch(name)
  1237. branch.remote = self.GetRemote(self.remote.name)
  1238. branch.merge = self.revisionExpr
  1239. if not branch.merge.startswith('refs/') and not ID_RE.match(self.revisionExpr):
  1240. branch.merge = R_HEADS + self.revisionExpr
  1241. revid = self.GetRevisionId(all_refs)
  1242. if head.startswith(R_HEADS):
  1243. try:
  1244. head = all_refs[head]
  1245. except KeyError:
  1246. head = None
  1247. if revid and head and revid == head:
  1248. ref = os.path.join(self.gitdir, R_HEADS + name)
  1249. try:
  1250. os.makedirs(os.path.dirname(ref))
  1251. except OSError:
  1252. pass
  1253. _lwrite(ref, '%s\n' % revid)
  1254. _lwrite(os.path.join(self.worktree, '.git', HEAD),
  1255. 'ref: %s%s\n' % (R_HEADS, name))
  1256. branch.Save()
  1257. return True
  1258. if GitCommand(self,
  1259. ['checkout', '-b', branch.name, revid],
  1260. capture_stdout=True,
  1261. capture_stderr=True).Wait() == 0:
  1262. branch.Save()
  1263. return True
  1264. return False
  1265. def CheckoutBranch(self, name):
  1266. """Checkout a local topic branch.
  1267. Args:
  1268. name: The name of the branch to checkout.
  1269. Returns:
  1270. True if the checkout succeeded; False if it didn't; None if the branch
  1271. didn't exist.
  1272. """
  1273. rev = R_HEADS + name
  1274. head = self.work_git.GetHead()
  1275. if head == rev:
  1276. # Already on the branch
  1277. #
  1278. return True
  1279. all_refs = self.bare_ref.all
  1280. try:
  1281. revid = all_refs[rev]
  1282. except KeyError:
  1283. # Branch does not exist in this project
  1284. #
  1285. return None
  1286. if head.startswith(R_HEADS):
  1287. try:
  1288. head = all_refs[head]
  1289. except KeyError:
  1290. head = None
  1291. if head == revid:
  1292. # Same revision; just update HEAD to point to the new
  1293. # target branch, but otherwise take no other action.
  1294. #
  1295. _lwrite(os.path.join(self.worktree, '.git', HEAD),
  1296. 'ref: %s%s\n' % (R_HEADS, name))
  1297. return True
  1298. return GitCommand(self,
  1299. ['checkout', name, '--'],
  1300. capture_stdout=True,
  1301. capture_stderr=True).Wait() == 0
  1302. def AbandonBranch(self, name):
  1303. """Destroy a local topic branch.
  1304. Args:
  1305. name: The name of the branch to abandon.
  1306. Returns:
  1307. True if the abandon succeeded; False if it didn't; None if the branch
  1308. didn't exist.
  1309. """
  1310. rev = R_HEADS + name
  1311. all_refs = self.bare_ref.all
  1312. if rev not in all_refs:
  1313. # Doesn't exist
  1314. return None
  1315. head = self.work_git.GetHead()
  1316. if head == rev:
  1317. # We can't destroy the branch while we are sitting
  1318. # on it. Switch to a detached HEAD.
  1319. #
  1320. head = all_refs[head]
  1321. revid = self.GetRevisionId(all_refs)
  1322. if head == revid:
  1323. _lwrite(os.path.join(self.worktree, '.git', HEAD),
  1324. '%s\n' % revid)
  1325. else:
  1326. self._Checkout(revid, quiet=True)
  1327. return GitCommand(self,
  1328. ['branch', '-D', name],
  1329. capture_stdout=True,
  1330. capture_stderr=True).Wait() == 0
  1331. def PruneHeads(self):
  1332. """Prune any topic branches already merged into upstream.
  1333. """
  1334. cb = self.CurrentBranch
  1335. kill = []
  1336. left = self._allrefs
  1337. for name in left.keys():
  1338. if name.startswith(R_HEADS):
  1339. name = name[len(R_HEADS):]
  1340. if cb is None or name != cb:
  1341. kill.append(name)
  1342. rev = self.GetRevisionId(left)
  1343. if cb is not None \
  1344. and not self._revlist(HEAD + '...' + rev) \
  1345. and not self.IsDirty(consider_untracked=False):
  1346. self.work_git.DetachHead(HEAD)
  1347. kill.append(cb)
  1348. if kill:
  1349. old = self.bare_git.GetHead()
  1350. if old is None:
  1351. old = 'refs/heads/please_never_use_this_as_a_branch_name'
  1352. try:
  1353. self.bare_git.DetachHead(rev)
  1354. b = ['branch', '-d']
  1355. b.extend(kill)
  1356. b = GitCommand(self, b, bare=True,
  1357. capture_stdout=True,
  1358. capture_stderr=True)
  1359. b.Wait()
  1360. finally:
  1361. self.bare_git.SetHead(old)
  1362. left = self._allrefs
  1363. for branch in kill:
  1364. if (R_HEADS + branch) not in left:
  1365. self.CleanPublishedCache()
  1366. break
  1367. if cb and cb not in kill:
  1368. kill.append(cb)
  1369. kill.sort()
  1370. kept = []
  1371. for branch in kill:
  1372. if R_HEADS + branch in left:
  1373. branch = self.GetBranch(branch)
  1374. base = branch.LocalMerge
  1375. if not base:
  1376. base = rev
  1377. kept.append(ReviewableBranch(self, branch, base))
  1378. return kept
  1379. ## Submodule Management ##
  1380. def GetRegisteredSubprojects(self):
  1381. result = []
  1382. def rec(subprojects):
  1383. if not subprojects:
  1384. return
  1385. result.extend(subprojects)
  1386. for p in subprojects:
  1387. rec(p.subprojects)
  1388. rec(self.subprojects)
  1389. return result
  1390. def _GetSubmodules(self):
  1391. # Unfortunately we cannot call `git submodule status --recursive` here
  1392. # because the working tree might not exist yet, and it cannot be used
  1393. # without a working tree in its current implementation.
  1394. def get_submodules(gitdir, rev):
  1395. # Parse .gitmodules for submodule sub_paths and sub_urls
  1396. sub_paths, sub_urls = parse_gitmodules(gitdir, rev)
  1397. if not sub_paths:
  1398. return []
  1399. # Run `git ls-tree` to read SHAs of submodule object, which happen to be
  1400. # revision of submodule repository
  1401. sub_revs = git_ls_tree(gitdir, rev, sub_paths)
  1402. submodules = []
  1403. for sub_path, sub_url in zip(sub_paths, sub_urls):
  1404. try:
  1405. sub_rev = sub_revs[sub_path]
  1406. except KeyError:
  1407. # Ignore non-exist submodules
  1408. continue
  1409. submodules.append((sub_rev, sub_path, sub_url))
  1410. return submodules
  1411. re_path = re.compile(r'^submodule\.([^.]+)\.path=(.*)$')
  1412. re_url = re.compile(r'^submodule\.([^.]+)\.url=(.*)$')
  1413. def parse_gitmodules(gitdir, rev):
  1414. cmd = ['cat-file', 'blob', '%s:.gitmodules' % rev]
  1415. try:
  1416. p = GitCommand(None, cmd, capture_stdout=True, capture_stderr=True,
  1417. bare=True, gitdir=gitdir)
  1418. except GitError:
  1419. return [], []
  1420. if p.Wait() != 0:
  1421. return [], []
  1422. gitmodules_lines = []
  1423. fd, temp_gitmodules_path = tempfile.mkstemp()
  1424. try:
  1425. os.write(fd, p.stdout)
  1426. os.close(fd)
  1427. cmd = ['config', '--file', temp_gitmodules_path, '--list']
  1428. p = GitCommand(None, cmd, capture_stdout=True, capture_stderr=True,
  1429. bare=True, gitdir=gitdir)
  1430. if p.Wait() != 0:
  1431. return [], []
  1432. gitmodules_lines = p.stdout.split('\n')
  1433. except GitError:
  1434. return [], []
  1435. finally:
  1436. os.remove(temp_gitmodules_path)
  1437. names = set()
  1438. paths = {}
  1439. urls = {}
  1440. for line in gitmodules_lines:
  1441. if not line:
  1442. continue
  1443. m = re_path.match(line)
  1444. if m:
  1445. names.add(m.group(1))
  1446. paths[m.group(1)] = m.group(2)
  1447. continue
  1448. m = re_url.match(line)
  1449. if m:
  1450. names.add(m.group(1))
  1451. urls[m.group(1)] = m.group(2)
  1452. continue
  1453. names = sorted(names)
  1454. return ([paths.get(name, '') for name in names],
  1455. [urls.get(name, '') for name in names])
  1456. def git_ls_tree(gitdir, rev, paths):
  1457. cmd = ['ls-tree', rev, '--']
  1458. cmd.extend(paths)
  1459. try:
  1460. p = GitCommand(None, cmd, capture_stdout=True, capture_stderr=True,
  1461. bare=True, gitdir=gitdir)
  1462. except GitError:
  1463. return []
  1464. if p.Wait() != 0:
  1465. return []
  1466. objects = {}
  1467. for line in p.stdout.split('\n'):
  1468. if not line.strip():
  1469. continue
  1470. object_rev, object_path = line.split()[2:4]
  1471. objects[object_path] = object_rev
  1472. return objects
  1473. try:
  1474. rev = self.GetRevisionId()
  1475. except GitError:
  1476. return []
  1477. return get_submodules(self.gitdir, rev)
  1478. def GetDerivedSubprojects(self):
  1479. result = []
  1480. if not self.Exists:
  1481. # If git repo does not exist yet, querying its submodules will
  1482. # mess up its states; so return here.
  1483. return result
  1484. for rev, path, url in self._GetSubmodules():
  1485. name = self.manifest.GetSubprojectName(self, path)
  1486. relpath, worktree, gitdir, objdir = \
  1487. self.manifest.GetSubprojectPaths(self, name, path)
  1488. project = self.manifest.paths.get(relpath)
  1489. if project:
  1490. result.extend(project.GetDerivedSubprojects())
  1491. continue
  1492. remote = RemoteSpec(self.remote.name,
  1493. url=url,
  1494. review=self.remote.review,
  1495. revision=self.remote.revision)
  1496. subproject = Project(manifest=self.manifest,
  1497. name=name,
  1498. remote=remote,
  1499. gitdir=gitdir,
  1500. objdir=objdir,
  1501. worktree=worktree,
  1502. relpath=relpath,
  1503. revisionExpr=self.revisionExpr,
  1504. revisionId=rev,
  1505. rebase=self.rebase,
  1506. groups=self.groups,
  1507. sync_c=self.sync_c,
  1508. sync_s=self.sync_s,
  1509. parent=self,
  1510. is_derived=True)
  1511. result.append(subproject)
  1512. result.extend(subproject.GetDerivedSubprojects())
  1513. return result
  1514. ## Direct Git Commands ##
  1515. def _CheckForSha1(self):
  1516. try:
  1517. # if revision (sha or tag) is not present then following function
  1518. # throws an error.
  1519. self.bare_git.rev_parse('--verify', '%s^0' % self.revisionExpr)
  1520. return True
  1521. except GitError:
  1522. # There is no such persistent revision. We have to fetch it.
  1523. return False
  1524. def _FetchArchive(self, tarpath, cwd=None):
  1525. cmd = ['archive', '-v', '-o', tarpath]
  1526. cmd.append('--remote=%s' % self.remote.url)
  1527. cmd.append('--prefix=%s/' % self.relpath)
  1528. cmd.append(self.revisionExpr)
  1529. command = GitCommand(self, cmd, cwd=cwd,
  1530. capture_stdout=True,
  1531. capture_stderr=True)
  1532. if command.Wait() != 0:
  1533. raise GitError('git archive %s: %s' % (self.name, command.stderr))
  1534. def _RemoteFetch(self, name=None,
  1535. current_branch_only=False,
  1536. initial=False,
  1537. quiet=False,
  1538. alt_dir=None,
  1539. no_tags=False):
  1540. is_sha1 = False
  1541. tag_name = None
  1542. depth = None
  1543. # The depth should not be used when fetching to a mirror because
  1544. # it will result in a shallow repository that cannot be cloned or
  1545. # fetched from.
  1546. if not self.manifest.IsMirror:
  1547. if self.clone_depth:
  1548. depth = self.clone_depth
  1549. else:
  1550. depth = self.manifest.manifestProject.config.GetString('repo.depth')
  1551. # The repo project should never be synced with partial depth
  1552. if self.relpath == '.repo/repo':
  1553. depth = None
  1554. if depth:
  1555. current_branch_only = True
  1556. if ID_RE.match(self.revisionExpr) is not None:
  1557. is_sha1 = True
  1558. if current_branch_only:
  1559. if self.revisionExpr.startswith(R_TAGS):
  1560. # this is a tag and its sha1 value should never change
  1561. tag_name = self.revisionExpr[len(R_TAGS):]
  1562. if is_sha1 or tag_name is not None:
  1563. if self._CheckForSha1():
  1564. return True
  1565. if is_sha1 and not depth:
  1566. # When syncing a specific commit and --depth is not set:
  1567. # * if upstream is explicitly specified and is not a sha1, fetch only
  1568. # upstream as users expect only upstream to be fetch.
  1569. # Note: The commit might not be in upstream in which case the sync
  1570. # will fail.
  1571. # * otherwise, fetch all branches to make sure we end up with the
  1572. # specific commit.
  1573. current_branch_only = self.upstream and not ID_RE.match(self.upstream)
  1574. if not name:
  1575. name = self.remote.name
  1576. ssh_proxy = False
  1577. remote = self.GetRemote(name)
  1578. if remote.PreConnectFetch():
  1579. ssh_proxy = True
  1580. if initial:
  1581. if alt_dir and 'objects' == os.path.basename(alt_dir):
  1582. ref_dir = os.path.dirname(alt_dir)
  1583. packed_refs = os.path.join(self.gitdir, 'packed-refs')
  1584. remote = self.GetRemote(name)
  1585. all_refs = self.bare_ref.all
  1586. ids = set(all_refs.values())
  1587. tmp = set()
  1588. for r, ref_id in GitRefs(ref_dir).all.items():
  1589. if r not in all_refs:
  1590. if r.startswith(R_TAGS) or remote.WritesTo(r):
  1591. all_refs[r] = ref_id
  1592. ids.add(ref_id)
  1593. continue
  1594. if ref_id in ids:
  1595. continue
  1596. r = 'refs/_alt/%s' % ref_id
  1597. all_refs[r] = ref_id
  1598. ids.add(ref_id)
  1599. tmp.add(r)
  1600. tmp_packed = ''
  1601. old_packed = ''
  1602. for r in sorted(all_refs):
  1603. line = '%s %s\n' % (all_refs[r], r)
  1604. tmp_packed += line
  1605. if r not in tmp:
  1606. old_packed += line
  1607. _lwrite(packed_refs, tmp_packed)
  1608. else:
  1609. alt_dir = None
  1610. cmd = ['fetch']
  1611. if depth:
  1612. cmd.append('--depth=%s' % depth)
  1613. if quiet:
  1614. cmd.append('--quiet')
  1615. if not self.worktree:
  1616. cmd.append('--update-head-ok')
  1617. cmd.append(name)
  1618. # If using depth then we should not get all the tags since they may
  1619. # be outside of the depth.
  1620. if no_tags or depth:
  1621. cmd.append('--no-tags')
  1622. else:
  1623. cmd.append('--tags')
  1624. spec = []
  1625. if not current_branch_only:
  1626. # Fetch whole repo
  1627. spec.append(str((u'+refs/heads/*:') + remote.ToLocal('refs/heads/*')))
  1628. elif tag_name is not None:
  1629. spec.append('tag')
  1630. spec.append(tag_name)
  1631. if not self.manifest.IsMirror:
  1632. branch = self.revisionExpr
  1633. if is_sha1 and depth and git_require((1, 8, 3)):
  1634. # Shallow checkout of a specific commit, fetch from that commit and not
  1635. # the heads only as the commit might be deeper in the history.
  1636. spec.append(branch)
  1637. else:
  1638. if is_sha1:
  1639. branch = self.upstream
  1640. if branch is not None and branch.strip():
  1641. if not branch.startswith('refs/'):
  1642. branch = R_HEADS + branch
  1643. spec.append(str((u'+%s:' % branch) + remote.ToLocal(branch)))
  1644. cmd.extend(spec)
  1645. shallowfetch = self.config.GetString('repo.shallowfetch')
  1646. if shallowfetch and shallowfetch != ' '.join(spec):
  1647. GitCommand(self, ['fetch', '--depth=2147483647', name]
  1648. + shallowfetch.split(),
  1649. bare=True, ssh_proxy=ssh_proxy).Wait()
  1650. if depth:
  1651. self.config.SetString('repo.shallowfetch', ' '.join(spec))
  1652. else:
  1653. self.config.SetString('repo.shallowfetch', None)
  1654. ok = False
  1655. for _i in range(2):
  1656. gitcmd = GitCommand(self, cmd, bare=True, ssh_proxy=ssh_proxy)
  1657. ret = gitcmd.Wait()
  1658. if ret == 0:
  1659. ok = True
  1660. break
  1661. # If needed, run the 'git remote prune' the first time through the loop
  1662. elif (not _i and
  1663. "error:" in gitcmd.stderr and
  1664. "git remote prune" in gitcmd.stderr):
  1665. prunecmd = GitCommand(self, ['remote', 'prune', name], bare=True,
  1666. ssh_proxy=ssh_proxy)
  1667. ret = prunecmd.Wait()
  1668. if ret:
  1669. break
  1670. continue
  1671. elif current_branch_only and is_sha1 and ret == 128:
  1672. # Exit code 128 means "couldn't find the ref you asked for"; if we're in sha1
  1673. # mode, we just tried sync'ing from the upstream field; it doesn't exist, thus
  1674. # abort the optimization attempt and do a full sync.
  1675. break
  1676. elif ret < 0:
  1677. # Git died with a signal, exit immediately
  1678. break
  1679. time.sleep(random.randint(30, 45))
  1680. if initial:
  1681. if alt_dir:
  1682. if old_packed != '':
  1683. _lwrite(packed_refs, old_packed)
  1684. else:
  1685. os.remove(packed_refs)
  1686. self.bare_git.pack_refs('--all', '--prune')
  1687. if is_sha1 and current_branch_only and self.upstream:
  1688. # We just synced the upstream given branch; verify we
  1689. # got what we wanted, else trigger a second run of all
  1690. # refs.
  1691. if not self._CheckForSha1():
  1692. if not depth:
  1693. # Avoid infinite recursion when depth is True (since depth implies
  1694. # current_branch_only)
  1695. return self._RemoteFetch(name=name, current_branch_only=False,
  1696. initial=False, quiet=quiet, alt_dir=alt_dir)
  1697. if self.clone_depth:
  1698. self.clone_depth = None
  1699. return self._RemoteFetch(name=name, current_branch_only=current_branch_only,
  1700. initial=False, quiet=quiet, alt_dir=alt_dir)
  1701. return ok
  1702. def _ApplyCloneBundle(self, initial=False, quiet=False):
  1703. if initial and (self.manifest.manifestProject.config.GetString('repo.depth') or self.clone_depth):
  1704. return False
  1705. remote = self.GetRemote(self.remote.name)
  1706. bundle_url = remote.url + '/clone.bundle'
  1707. bundle_url = GitConfig.ForUser().UrlInsteadOf(bundle_url)
  1708. if GetSchemeFromUrl(bundle_url) not in (
  1709. 'http', 'https', 'persistent-http', 'persistent-https'):
  1710. return False
  1711. bundle_dst = os.path.join(self.gitdir, 'clone.bundle')
  1712. bundle_tmp = os.path.join(self.gitdir, 'clone.bundle.tmp')
  1713. exist_dst = os.path.exists(bundle_dst)
  1714. exist_tmp = os.path.exists(bundle_tmp)
  1715. if not initial and not exist_dst and not exist_tmp:
  1716. return False
  1717. if not exist_dst:
  1718. exist_dst = self._FetchBundle(bundle_url, bundle_tmp, bundle_dst, quiet)
  1719. if not exist_dst:
  1720. return False
  1721. cmd = ['fetch']
  1722. if quiet:
  1723. cmd.append('--quiet')
  1724. if not self.worktree:
  1725. cmd.append('--update-head-ok')
  1726. cmd.append(bundle_dst)
  1727. for f in remote.fetch:
  1728. cmd.append(str(f))
  1729. cmd.append('refs/tags/*:refs/tags/*')
  1730. ok = GitCommand(self, cmd, bare=True).Wait() == 0
  1731. if os.path.exists(bundle_dst):
  1732. os.remove(bundle_dst)
  1733. if os.path.exists(bundle_tmp):
  1734. os.remove(bundle_tmp)
  1735. return ok
  1736. def _FetchBundle(self, srcUrl, tmpPath, dstPath, quiet):
  1737. if os.path.exists(dstPath):
  1738. os.remove(dstPath)
  1739. cmd = ['curl', '--fail', '--output', tmpPath, '--netrc', '--location']
  1740. if quiet:
  1741. cmd += ['--silent']
  1742. if os.path.exists(tmpPath):
  1743. size = os.stat(tmpPath).st_size
  1744. if size >= 1024:
  1745. cmd += ['--continue-at', '%d' % (size,)]
  1746. else:
  1747. os.remove(tmpPath)
  1748. if 'http_proxy' in os.environ and 'darwin' == sys.platform:
  1749. cmd += ['--proxy', os.environ['http_proxy']]
  1750. with self._GetBundleCookieFile(srcUrl, quiet) as cookiefile:
  1751. if cookiefile:
  1752. cmd += ['--cookie', cookiefile, '--cookie-jar', cookiefile]
  1753. if srcUrl.startswith('persistent-'):
  1754. srcUrl = srcUrl[len('persistent-'):]
  1755. cmd += [srcUrl]
  1756. if IsTrace():
  1757. Trace('%s', ' '.join(cmd))
  1758. try:
  1759. proc = subprocess.Popen(cmd)
  1760. except OSError:
  1761. return False
  1762. curlret = proc.wait()
  1763. if curlret == 22:
  1764. # From curl man page:
  1765. # 22: HTTP page not retrieved. The requested url was not found or
  1766. # returned another error with the HTTP error code being 400 or above.
  1767. # This return code only appears if -f, --fail is used.
  1768. if not quiet:
  1769. print("Server does not provide clone.bundle; ignoring.",
  1770. file=sys.stderr)
  1771. return False
  1772. if os.path.exists(tmpPath):
  1773. if curlret == 0 and self._IsValidBundle(tmpPath, quiet):
  1774. os.rename(tmpPath, dstPath)
  1775. return True
  1776. else:
  1777. os.remove(tmpPath)
  1778. return False
  1779. else:
  1780. return False
  1781. def _IsValidBundle(self, path, quiet):
  1782. try:
  1783. with open(path) as f:
  1784. if f.read(16) == '# v2 git bundle\n':
  1785. return True
  1786. else:
  1787. if not quiet:
  1788. print("Invalid clone.bundle file; ignoring.", file=sys.stderr)
  1789. return False
  1790. except OSError:
  1791. return False
  1792. @contextlib.contextmanager
  1793. def _GetBundleCookieFile(self, url, quiet):
  1794. if url.startswith('persistent-'):
  1795. try:
  1796. p = subprocess.Popen(
  1797. ['git-remote-persistent-https', '-print_config', url],
  1798. stdin=subprocess.PIPE, stdout=subprocess.PIPE,
  1799. stderr=subprocess.PIPE)
  1800. try:
  1801. prefix = 'http.cookiefile='
  1802. cookiefile = None
  1803. for line in p.stdout:
  1804. line = line.strip()
  1805. if line.startswith(prefix):
  1806. cookiefile = line[len(prefix):]
  1807. break
  1808. # Leave subprocess open, as cookie file may be transient.
  1809. if cookiefile:
  1810. yield cookiefile
  1811. return
  1812. finally:
  1813. p.stdin.close()
  1814. if p.wait():
  1815. err_msg = p.stderr.read()
  1816. if ' -print_config' in err_msg:
  1817. pass # Persistent proxy doesn't support -print_config.
  1818. elif not quiet:
  1819. print(err_msg, file=sys.stderr)
  1820. except OSError as e:
  1821. if e.errno == errno.ENOENT:
  1822. pass # No persistent proxy.
  1823. raise
  1824. yield GitConfig.ForUser().GetString('http.cookiefile')
  1825. def _Checkout(self, rev, quiet=False):
  1826. cmd = ['checkout']
  1827. if quiet:
  1828. cmd.append('-q')
  1829. cmd.append(rev)
  1830. cmd.append('--')
  1831. if GitCommand(self, cmd).Wait() != 0:
  1832. if self._allrefs:
  1833. raise GitError('%s checkout %s ' % (self.name, rev))
  1834. def _CherryPick(self, rev):
  1835. cmd = ['cherry-pick']
  1836. cmd.append(rev)
  1837. cmd.append('--')
  1838. if GitCommand(self, cmd).Wait() != 0:
  1839. if self._allrefs:
  1840. raise GitError('%s cherry-pick %s ' % (self.name, rev))
  1841. def _Revert(self, rev):
  1842. cmd = ['revert']
  1843. cmd.append('--no-edit')
  1844. cmd.append(rev)
  1845. cmd.append('--')
  1846. if GitCommand(self, cmd).Wait() != 0:
  1847. if self._allrefs:
  1848. raise GitError('%s revert %s ' % (self.name, rev))
  1849. def _ResetHard(self, rev, quiet=True):
  1850. cmd = ['reset', '--hard']
  1851. if quiet:
  1852. cmd.append('-q')
  1853. cmd.append(rev)
  1854. if GitCommand(self, cmd).Wait() != 0:
  1855. raise GitError('%s reset --hard %s ' % (self.name, rev))
  1856. def _Rebase(self, upstream, onto=None):
  1857. cmd = ['rebase']
  1858. if onto is not None:
  1859. cmd.extend(['--onto', onto])
  1860. cmd.append(upstream)
  1861. if GitCommand(self, cmd).Wait() != 0:
  1862. raise GitError('%s rebase %s ' % (self.name, upstream))
  1863. def _FastForward(self, head, ffonly=False):
  1864. cmd = ['merge', head]
  1865. if ffonly:
  1866. cmd.append("--ff-only")
  1867. if GitCommand(self, cmd).Wait() != 0:
  1868. raise GitError('%s merge %s ' % (self.name, head))
  1869. def _InitGitDir(self, mirror_git=None, force_sync=False):
  1870. init_git_dir = not os.path.exists(self.gitdir)
  1871. init_obj_dir = not os.path.exists(self.objdir)
  1872. try:
  1873. # Initialize the bare repository, which contains all of the objects.
  1874. if init_obj_dir:
  1875. os.makedirs(self.objdir)
  1876. self.bare_objdir.init()
  1877. # If we have a separate directory to hold refs, initialize it as well.
  1878. if self.objdir != self.gitdir:
  1879. if init_git_dir:
  1880. os.makedirs(self.gitdir)
  1881. if init_obj_dir or init_git_dir:
  1882. self._ReferenceGitDir(self.objdir, self.gitdir, share_refs=False,
  1883. copy_all=True)
  1884. try:
  1885. self._CheckDirReference(self.objdir, self.gitdir, share_refs=False)
  1886. except GitError as e:
  1887. print("Retrying clone after deleting %s" % force_sync, file=sys.stderr)
  1888. if force_sync:
  1889. try:
  1890. shutil.rmtree(os.path.realpath(self.gitdir))
  1891. if self.worktree and os.path.exists(
  1892. os.path.realpath(self.worktree)):
  1893. shutil.rmtree(os.path.realpath(self.worktree))
  1894. return self._InitGitDir(mirror_git=mirror_git, force_sync=False)
  1895. except:
  1896. raise e
  1897. raise e
  1898. if init_git_dir:
  1899. mp = self.manifest.manifestProject
  1900. ref_dir = mp.config.GetString('repo.reference') or ''
  1901. if ref_dir or mirror_git:
  1902. if not mirror_git:
  1903. mirror_git = os.path.join(ref_dir, self.name + '.git')
  1904. repo_git = os.path.join(ref_dir, '.repo', 'projects',
  1905. self.relpath + '.git')
  1906. if os.path.exists(mirror_git):
  1907. ref_dir = mirror_git
  1908. elif os.path.exists(repo_git):
  1909. ref_dir = repo_git
  1910. else:
  1911. ref_dir = None
  1912. if ref_dir:
  1913. _lwrite(os.path.join(self.gitdir, 'objects/info/alternates'),
  1914. os.path.join(ref_dir, 'objects') + '\n')
  1915. self._UpdateHooks()
  1916. m = self.manifest.manifestProject.config
  1917. for key in ['user.name', 'user.email']:
  1918. if m.Has(key, include_defaults=False):
  1919. self.config.SetString(key, m.GetString(key))
  1920. if self.manifest.IsMirror:
  1921. self.config.SetString('core.bare', 'true')
  1922. else:
  1923. self.config.SetString('core.bare', None)
  1924. except Exception:
  1925. if init_obj_dir and os.path.exists(self.objdir):
  1926. shutil.rmtree(self.objdir)
  1927. if init_git_dir and os.path.exists(self.gitdir):
  1928. shutil.rmtree(self.gitdir)
  1929. raise
  1930. def _UpdateHooks(self):
  1931. if os.path.exists(self.gitdir):
  1932. self._InitHooks()
  1933. def _InitHooks(self):
  1934. hooks = os.path.realpath(self._gitdir_path('hooks'))
  1935. if not os.path.exists(hooks):
  1936. os.makedirs(hooks)
  1937. for stock_hook in _ProjectHooks():
  1938. name = os.path.basename(stock_hook)
  1939. if name in ('commit-msg',) and not self.remote.review \
  1940. and not self is self.manifest.manifestProject:
  1941. # Don't install a Gerrit Code Review hook if this
  1942. # project does not appear to use it for reviews.
  1943. #
  1944. # Since the manifest project is one of those, but also
  1945. # managed through gerrit, it's excluded
  1946. continue
  1947. dst = os.path.join(hooks, name)
  1948. if os.path.islink(dst):
  1949. continue
  1950. if os.path.exists(dst):
  1951. if filecmp.cmp(stock_hook, dst, shallow=False):
  1952. os.remove(dst)
  1953. else:
  1954. _error("%s: Not replacing %s hook", self.relpath, name)
  1955. continue
  1956. try:
  1957. os.symlink(os.path.relpath(stock_hook, os.path.dirname(dst)), dst)
  1958. except OSError as e:
  1959. if e.errno == errno.EPERM:
  1960. raise GitError('filesystem must support symlinks')
  1961. else:
  1962. raise
  1963. def _InitRemote(self):
  1964. if self.remote.url:
  1965. remote = self.GetRemote(self.remote.name)
  1966. remote.url = self.remote.url
  1967. remote.review = self.remote.review
  1968. remote.projectname = self.name
  1969. if self.worktree:
  1970. remote.ResetFetch(mirror=False)
  1971. else:
  1972. remote.ResetFetch(mirror=True)
  1973. remote.Save()
  1974. def _InitMRef(self):
  1975. if self.manifest.branch:
  1976. self._InitAnyMRef(R_M + self.manifest.branch)
  1977. def _InitMirrorHead(self):
  1978. self._InitAnyMRef(HEAD)
  1979. def _InitAnyMRef(self, ref):
  1980. cur = self.bare_ref.symref(ref)
  1981. if self.revisionId:
  1982. if cur != '' or self.bare_ref.get(ref) != self.revisionId:
  1983. msg = 'manifest set to %s' % self.revisionId
  1984. dst = self.revisionId + '^0'
  1985. self.bare_git.UpdateRef(ref, dst, message=msg, detach=True)
  1986. else:
  1987. remote = self.GetRemote(self.remote.name)
  1988. dst = remote.ToLocal(self.revisionExpr)
  1989. if cur != dst:
  1990. msg = 'manifest set to %s' % self.revisionExpr
  1991. self.bare_git.symbolic_ref('-m', msg, ref, dst)
  1992. def _CheckDirReference(self, srcdir, destdir, share_refs):
  1993. symlink_files = self.shareable_files
  1994. symlink_dirs = self.shareable_dirs
  1995. if share_refs:
  1996. symlink_files += self.working_tree_files
  1997. symlink_dirs += self.working_tree_dirs
  1998. to_symlink = symlink_files + symlink_dirs
  1999. for name in set(to_symlink):
  2000. dst = os.path.realpath(os.path.join(destdir, name))
  2001. if os.path.lexists(dst):
  2002. src = os.path.realpath(os.path.join(srcdir, name))
  2003. # Fail if the links are pointing to the wrong place
  2004. if src != dst:
  2005. raise GitError('--force-sync not enabled; cannot overwrite a local '
  2006. 'work tree')
  2007. def _ReferenceGitDir(self, gitdir, dotgit, share_refs, copy_all):
  2008. """Update |dotgit| to reference |gitdir|, using symlinks where possible.
  2009. Args:
  2010. gitdir: The bare git repository. Must already be initialized.
  2011. dotgit: The repository you would like to initialize.
  2012. share_refs: If true, |dotgit| will store its refs under |gitdir|.
  2013. Only one work tree can store refs under a given |gitdir|.
  2014. copy_all: If true, copy all remaining files from |gitdir| -> |dotgit|.
  2015. This saves you the effort of initializing |dotgit| yourself.
  2016. """
  2017. symlink_files = self.shareable_files
  2018. symlink_dirs = self.shareable_dirs
  2019. if share_refs:
  2020. symlink_files += self.working_tree_files
  2021. symlink_dirs += self.working_tree_dirs
  2022. to_symlink = symlink_files + symlink_dirs
  2023. to_copy = []
  2024. if copy_all:
  2025. to_copy = os.listdir(gitdir)
  2026. for name in set(to_copy).union(to_symlink):
  2027. try:
  2028. src = os.path.realpath(os.path.join(gitdir, name))
  2029. dst = os.path.realpath(os.path.join(dotgit, name))
  2030. if os.path.lexists(dst):
  2031. continue
  2032. # If the source dir doesn't exist, create an empty dir.
  2033. if name in symlink_dirs and not os.path.lexists(src):
  2034. os.makedirs(src)
  2035. # If the source file doesn't exist, ensure the destination
  2036. # file doesn't either.
  2037. if name in symlink_files and not os.path.lexists(src):
  2038. try:
  2039. os.remove(dst)
  2040. except OSError:
  2041. pass
  2042. if name in to_symlink:
  2043. os.symlink(os.path.relpath(src, os.path.dirname(dst)), dst)
  2044. elif copy_all and not os.path.islink(dst):
  2045. if os.path.isdir(src):
  2046. shutil.copytree(src, dst)
  2047. elif os.path.isfile(src):
  2048. shutil.copy(src, dst)
  2049. except OSError as e:
  2050. if e.errno == errno.EPERM:
  2051. raise DownloadError('filesystem must support symlinks')
  2052. else:
  2053. raise
  2054. def _InitWorkTree(self, force_sync=False):
  2055. dotgit = os.path.join(self.worktree, '.git')
  2056. init_dotgit = not os.path.exists(dotgit)
  2057. try:
  2058. if init_dotgit:
  2059. os.makedirs(dotgit)
  2060. self._ReferenceGitDir(self.gitdir, dotgit, share_refs=True,
  2061. copy_all=False)
  2062. try:
  2063. self._CheckDirReference(self.gitdir, dotgit, share_refs=True)
  2064. except GitError as e:
  2065. if force_sync:
  2066. try:
  2067. shutil.rmtree(dotgit)
  2068. return self._InitWorkTree(force_sync=False)
  2069. except:
  2070. raise e
  2071. raise e
  2072. if init_dotgit:
  2073. _lwrite(os.path.join(dotgit, HEAD), '%s\n' % self.GetRevisionId())
  2074. cmd = ['read-tree', '--reset', '-u']
  2075. cmd.append('-v')
  2076. cmd.append(HEAD)
  2077. if GitCommand(self, cmd).Wait() != 0:
  2078. raise GitError("cannot initialize work tree")
  2079. self._CopyAndLinkFiles()
  2080. except Exception:
  2081. if init_dotgit:
  2082. shutil.rmtree(dotgit)
  2083. raise
  2084. def _gitdir_path(self, path):
  2085. return os.path.realpath(os.path.join(self.gitdir, path))
  2086. def _revlist(self, *args, **kw):
  2087. a = []
  2088. a.extend(args)
  2089. a.append('--')
  2090. return self.work_git.rev_list(*a, **kw)
  2091. @property
  2092. def _allrefs(self):
  2093. return self.bare_ref.all
  2094. def _getLogs(self, rev1, rev2, oneline=False, color=True):
  2095. """Get logs between two revisions of this project."""
  2096. comp = '..'
  2097. if rev1:
  2098. revs = [rev1]
  2099. if rev2:
  2100. revs.extend([comp, rev2])
  2101. cmd = ['log', ''.join(revs)]
  2102. out = DiffColoring(self.config)
  2103. if out.is_on and color:
  2104. cmd.append('--color')
  2105. if oneline:
  2106. cmd.append('--oneline')
  2107. try:
  2108. log = GitCommand(self, cmd, capture_stdout=True, capture_stderr=True)
  2109. if log.Wait() == 0:
  2110. return log.stdout
  2111. except GitError:
  2112. # worktree may not exist if groups changed for example. In that case,
  2113. # try in gitdir instead.
  2114. if not os.path.exists(self.worktree):
  2115. return self.bare_git.log(*cmd[1:])
  2116. else:
  2117. raise
  2118. return None
  2119. def getAddedAndRemovedLogs(self, toProject, oneline=False, color=True):
  2120. """Get the list of logs from this revision to given revisionId"""
  2121. logs = {}
  2122. selfId = self.GetRevisionId(self._allrefs)
  2123. toId = toProject.GetRevisionId(toProject._allrefs)
  2124. logs['added'] = self._getLogs(selfId, toId, oneline=oneline, color=color)
  2125. logs['removed'] = self._getLogs(toId, selfId, oneline=oneline, color=color)
  2126. return logs
  2127. class _GitGetByExec(object):
  2128. def __init__(self, project, bare, gitdir):
  2129. self._project = project
  2130. self._bare = bare
  2131. self._gitdir = gitdir
  2132. def LsOthers(self):
  2133. p = GitCommand(self._project,
  2134. ['ls-files',
  2135. '-z',
  2136. '--others',
  2137. '--exclude-standard'],
  2138. bare=False,
  2139. gitdir=self._gitdir,
  2140. capture_stdout=True,
  2141. capture_stderr=True)
  2142. if p.Wait() == 0:
  2143. out = p.stdout
  2144. if out:
  2145. return out[:-1].split('\0') # pylint: disable=W1401
  2146. # Backslash is not anomalous
  2147. return []
  2148. def DiffZ(self, name, *args):
  2149. cmd = [name]
  2150. cmd.append('-z')
  2151. cmd.extend(args)
  2152. p = GitCommand(self._project,
  2153. cmd,
  2154. gitdir=self._gitdir,
  2155. bare=False,
  2156. capture_stdout=True,
  2157. capture_stderr=True)
  2158. try:
  2159. out = p.process.stdout.read()
  2160. r = {}
  2161. if out:
  2162. out = iter(out[:-1].split('\0')) # pylint: disable=W1401
  2163. while out:
  2164. try:
  2165. info = next(out)
  2166. path = next(out)
  2167. except StopIteration:
  2168. break
  2169. class _Info(object):
  2170. def __init__(self, path, omode, nmode, oid, nid, state):
  2171. self.path = path
  2172. self.src_path = None
  2173. self.old_mode = omode
  2174. self.new_mode = nmode
  2175. self.old_id = oid
  2176. self.new_id = nid
  2177. if len(state) == 1:
  2178. self.status = state
  2179. self.level = None
  2180. else:
  2181. self.status = state[:1]
  2182. self.level = state[1:]
  2183. while self.level.startswith('0'):
  2184. self.level = self.level[1:]
  2185. info = info[1:].split(' ')
  2186. info = _Info(path, *info)
  2187. if info.status in ('R', 'C'):
  2188. info.src_path = info.path
  2189. info.path = next(out)
  2190. r[info.path] = info
  2191. return r
  2192. finally:
  2193. p.Wait()
  2194. def GetHead(self):
  2195. if self._bare:
  2196. path = os.path.join(self._project.gitdir, HEAD)
  2197. else:
  2198. path = os.path.join(self._project.worktree, '.git', HEAD)
  2199. try:
  2200. fd = open(path, 'rb')
  2201. except IOError as e:
  2202. raise NoManifestException(path, str(e))
  2203. try:
  2204. line = fd.read()
  2205. finally:
  2206. fd.close()
  2207. try:
  2208. line = line.decode()
  2209. except AttributeError:
  2210. pass
  2211. if line.startswith('ref: '):
  2212. return line[5:-1]
  2213. return line[:-1]
  2214. def SetHead(self, ref, message=None):
  2215. cmdv = []
  2216. if message is not None:
  2217. cmdv.extend(['-m', message])
  2218. cmdv.append(HEAD)
  2219. cmdv.append(ref)
  2220. self.symbolic_ref(*cmdv)
  2221. def DetachHead(self, new, message=None):
  2222. cmdv = ['--no-deref']
  2223. if message is not None:
  2224. cmdv.extend(['-m', message])
  2225. cmdv.append(HEAD)
  2226. cmdv.append(new)
  2227. self.update_ref(*cmdv)
  2228. def UpdateRef(self, name, new, old=None,
  2229. message=None,
  2230. detach=False):
  2231. cmdv = []
  2232. if message is not None:
  2233. cmdv.extend(['-m', message])
  2234. if detach:
  2235. cmdv.append('--no-deref')
  2236. cmdv.append(name)
  2237. cmdv.append(new)
  2238. if old is not None:
  2239. cmdv.append(old)
  2240. self.update_ref(*cmdv)
  2241. def DeleteRef(self, name, old=None):
  2242. if not old:
  2243. old = self.rev_parse(name)
  2244. self.update_ref('-d', name, old)
  2245. self._project.bare_ref.deleted(name)
  2246. def rev_list(self, *args, **kw):
  2247. if 'format' in kw:
  2248. cmdv = ['log', '--pretty=format:%s' % kw['format']]
  2249. else:
  2250. cmdv = ['rev-list']
  2251. cmdv.extend(args)
  2252. p = GitCommand(self._project,
  2253. cmdv,
  2254. bare=self._bare,
  2255. gitdir=self._gitdir,
  2256. capture_stdout=True,
  2257. capture_stderr=True)
  2258. r = []
  2259. for line in p.process.stdout:
  2260. if line[-1] == '\n':
  2261. line = line[:-1]
  2262. r.append(line)
  2263. if p.Wait() != 0:
  2264. raise GitError('%s rev-list %s: %s' % (
  2265. self._project.name,
  2266. str(args),
  2267. p.stderr))
  2268. return r
  2269. def __getattr__(self, name):
  2270. """Allow arbitrary git commands using pythonic syntax.
  2271. This allows you to do things like:
  2272. git_obj.rev_parse('HEAD')
  2273. Since we don't have a 'rev_parse' method defined, the __getattr__ will
  2274. run. We'll replace the '_' with a '-' and try to run a git command.
  2275. Any other positional arguments will be passed to the git command, and the
  2276. following keyword arguments are supported:
  2277. config: An optional dict of git config options to be passed with '-c'.
  2278. Args:
  2279. name: The name of the git command to call. Any '_' characters will
  2280. be replaced with '-'.
  2281. Returns:
  2282. A callable object that will try to call git with the named command.
  2283. """
  2284. name = name.replace('_', '-')
  2285. def runner(*args, **kwargs):
  2286. cmdv = []
  2287. config = kwargs.pop('config', None)
  2288. for k in kwargs:
  2289. raise TypeError('%s() got an unexpected keyword argument %r'
  2290. % (name, k))
  2291. if config is not None:
  2292. if not git_require((1, 7, 2)):
  2293. raise ValueError('cannot set config on command line for %s()'
  2294. % name)
  2295. for k, v in config.items():
  2296. cmdv.append('-c')
  2297. cmdv.append('%s=%s' % (k, v))
  2298. cmdv.append(name)
  2299. cmdv.extend(args)
  2300. p = GitCommand(self._project,
  2301. cmdv,
  2302. bare=self._bare,
  2303. gitdir=self._gitdir,
  2304. capture_stdout=True,
  2305. capture_stderr=True)
  2306. if p.Wait() != 0:
  2307. raise GitError('%s %s: %s' % (
  2308. self._project.name,
  2309. name,
  2310. p.stderr))
  2311. r = p.stdout
  2312. try:
  2313. r = r.decode('utf-8')
  2314. except AttributeError:
  2315. pass
  2316. if r.endswith('\n') and r.index('\n') == len(r) - 1:
  2317. return r[:-1]
  2318. return r
  2319. return runner
  2320. class _PriorSyncFailedError(Exception):
  2321. def __str__(self):
  2322. return 'prior sync failed; rebase still in progress'
  2323. class _DirtyError(Exception):
  2324. def __str__(self):
  2325. return 'contains uncommitted changes'
  2326. class _InfoMessage(object):
  2327. def __init__(self, project, text):
  2328. self.project = project
  2329. self.text = text
  2330. def Print(self, syncbuf):
  2331. syncbuf.out.info('%s/: %s', self.project.relpath, self.text)
  2332. syncbuf.out.nl()
  2333. class _Failure(object):
  2334. def __init__(self, project, why):
  2335. self.project = project
  2336. self.why = why
  2337. def Print(self, syncbuf):
  2338. syncbuf.out.fail('error: %s/: %s',
  2339. self.project.relpath,
  2340. str(self.why))
  2341. syncbuf.out.nl()
  2342. class _Later(object):
  2343. def __init__(self, project, action):
  2344. self.project = project
  2345. self.action = action
  2346. def Run(self, syncbuf):
  2347. out = syncbuf.out
  2348. out.project('project %s/', self.project.relpath)
  2349. out.nl()
  2350. try:
  2351. self.action()
  2352. out.nl()
  2353. return True
  2354. except GitError:
  2355. out.nl()
  2356. return False
  2357. class _SyncColoring(Coloring):
  2358. def __init__(self, config):
  2359. Coloring.__init__(self, config, 'reposync')
  2360. self.project = self.printer('header', attr='bold')
  2361. self.info = self.printer('info')
  2362. self.fail = self.printer('fail', fg='red')
  2363. class SyncBuffer(object):
  2364. def __init__(self, config, detach_head=False):
  2365. self._messages = []
  2366. self._failures = []
  2367. self._later_queue1 = []
  2368. self._later_queue2 = []
  2369. self.out = _SyncColoring(config)
  2370. self.out.redirect(sys.stderr)
  2371. self.detach_head = detach_head
  2372. self.clean = True
  2373. def info(self, project, fmt, *args):
  2374. self._messages.append(_InfoMessage(project, fmt % args))
  2375. def fail(self, project, err=None):
  2376. self._failures.append(_Failure(project, err))
  2377. self.clean = False
  2378. def later1(self, project, what):
  2379. self._later_queue1.append(_Later(project, what))
  2380. def later2(self, project, what):
  2381. self._later_queue2.append(_Later(project, what))
  2382. def Finish(self):
  2383. self._PrintMessages()
  2384. self._RunLater()
  2385. self._PrintMessages()
  2386. return self.clean
  2387. def _RunLater(self):
  2388. for q in ['_later_queue1', '_later_queue2']:
  2389. if not self._RunQueue(q):
  2390. return
  2391. def _RunQueue(self, queue):
  2392. for m in getattr(self, queue):
  2393. if not m.Run(self):
  2394. self.clean = False
  2395. return False
  2396. setattr(self, queue, [])
  2397. return True
  2398. def _PrintMessages(self):
  2399. for m in self._messages:
  2400. m.Print(self)
  2401. for m in self._failures:
  2402. m.Print(self)
  2403. self._messages = []
  2404. self._failures = []
  2405. class MetaProject(Project):
  2406. """A special project housed under .repo.
  2407. """
  2408. def __init__(self, manifest, name, gitdir, worktree):
  2409. Project.__init__(self,
  2410. manifest=manifest,
  2411. name=name,
  2412. gitdir=gitdir,
  2413. objdir=gitdir,
  2414. worktree=worktree,
  2415. remote=RemoteSpec('origin'),
  2416. relpath='.repo/%s' % name,
  2417. revisionExpr='refs/heads/master',
  2418. revisionId=None,
  2419. groups=None)
  2420. def PreSync(self):
  2421. if self.Exists:
  2422. cb = self.CurrentBranch
  2423. if cb:
  2424. base = self.GetBranch(cb).merge
  2425. if base:
  2426. self.revisionExpr = base
  2427. self.revisionId = None
  2428. def MetaBranchSwitch(self):
  2429. """ Prepare MetaProject for manifest branch switch
  2430. """
  2431. # detach and delete manifest branch, allowing a new
  2432. # branch to take over
  2433. syncbuf = SyncBuffer(self.config, detach_head=True)
  2434. self.Sync_LocalHalf(syncbuf)
  2435. syncbuf.Finish()
  2436. return GitCommand(self,
  2437. ['update-ref', '-d', 'refs/heads/default'],
  2438. capture_stdout=True,
  2439. capture_stderr=True).Wait() == 0
  2440. @property
  2441. def LastFetch(self):
  2442. try:
  2443. fh = os.path.join(self.gitdir, 'FETCH_HEAD')
  2444. return os.path.getmtime(fh)
  2445. except OSError:
  2446. return 0
  2447. @property
  2448. def HasChanges(self):
  2449. """Has the remote received new commits not yet checked out?
  2450. """
  2451. if not self.remote or not self.revisionExpr:
  2452. return False
  2453. all_refs = self.bare_ref.all
  2454. revid = self.GetRevisionId(all_refs)
  2455. head = self.work_git.GetHead()
  2456. if head.startswith(R_HEADS):
  2457. try:
  2458. head = all_refs[head]
  2459. except KeyError:
  2460. head = None
  2461. if revid == head:
  2462. return False
  2463. elif self._revlist(not_rev(HEAD), revid):
  2464. return True
  2465. return False