project.py 93 KB

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