project.py 102 KB

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