project.py 96 KB

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