project.py 93 KB

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