project.py 115 KB

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