project.py 95 KB

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