blob: 32c85f79fdb375d8539ccc1dff1df96d48e2acd2 [file] [log] [blame]
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -07001# Copyright (C) 2008 The Android Open Source Project
2#
3# Licensed under the Apache License, Version 2.0 (the "License");
4# you may not use this file except in compliance with the License.
5# You may obtain a copy of the License at
6#
7# http://www.apache.org/licenses/LICENSE-2.0
8#
9# Unless required by applicable law or agreed to in writing, software
10# distributed under the License is distributed on an "AS IS" BASIS,
11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12# See the License for the specific language governing permissions and
13# limitations under the License.
14
15import os
Conley Owensd21720d2012-04-16 11:02:21 -070016import platform
Conley Owens971de8e2012-04-16 10:36:08 -070017import re
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070018import sys
Mike Frysingeracf63b22019-06-13 02:24:21 -040019import urllib.parse
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070020
21from color import Coloring
Shawn O. Pearcec95583b2009-03-03 17:47:06 -080022from command import InteractiveCommand, MirrorSafeCommand
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070023from error import ManifestParseError
Jonathan Nieder93719792015-03-17 11:29:58 -070024from project import SyncBuffer
Shawn O. Pearcef322b9a2011-09-19 14:50:58 -070025from git_config import GitConfig
Mike Frysinger82caef62020-02-11 18:51:08 -050026from git_command import git_require, MIN_GIT_VERSION_SOFT, MIN_GIT_VERSION_HARD
Jack Neusc474c9c2021-07-26 23:08:54 +000027import fetch
Raman Tenneti21dce3d2021-02-09 00:26:31 -080028import git_superproject
Renaud Paquaya65adf72016-11-03 10:37:53 -070029import platform_utils
Mike Frysinger3599cc32020-02-29 02:53:41 -050030from wrapper import Wrapper
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070031
David Pursehouse819827a2020-02-12 15:20:19 +090032
Shawn O. Pearcec95583b2009-03-03 17:47:06 -080033class Init(InteractiveCommand, MirrorSafeCommand):
Mike Frysinger4f210542021-06-14 16:05:19 -040034 COMMON = True
Mike Frysinger401c6f02021-02-18 15:20:15 -050035 helpSummary = "Initialize a repo client checkout in the current directory"
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070036 helpUsage = """
Mike Frysinger401c6f02021-02-18 15:20:15 -050037%prog [options] [manifest url]
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070038"""
39 helpDescription = """
40The '%prog' command is run once to install and initialize repo.
41The latest repo source code and manifest collection is downloaded
42from the server and is installed in the .repo/ directory in the
43current working directory.
44
Mike Frysinger401c6f02021-02-18 15:20:15 -050045When creating a new checkout, the manifest URL is the only required setting.
46It may be specified using the --manifest-url option, or as the first optional
47argument.
48
Shawn O. Pearce77bb4af2009-04-18 11:33:32 -070049The optional -b argument can be used to select the manifest branch
Mike Frysinger50a81de2020-09-06 15:51:21 -040050to checkout and use. If no branch is specified, the remote's default
Mike Frysinger23882b32021-02-23 15:43:07 -050051branch is used. This is equivalent to using -b HEAD.
Shawn O. Pearce77bb4af2009-04-18 11:33:32 -070052
53The optional -m argument can be used to specify an alternate manifest
54to be used. If no manifest is specified, the manifest default.xml
55will be used.
56
Jack Neusc474c9c2021-07-26 23:08:54 +000057If the --standalone-manifest argument is set, the manifest will be downloaded
58directly from the specified --manifest-url as a static file (rather than
59setting up a manifest git checkout). With --standalone-manifest, the manifest
60will be fully static and will not be re-downloaded during subsesquent
61`repo init` and `repo sync` calls.
62
Shawn O. Pearce88443382010-10-08 10:02:09 +020063The --reference option can be used to point to a directory that
64has the content of a --mirror sync. This will make the working
65directory use as much data as possible from the local reference
66directory when fetching from the server. This will make the sync
67go a lot faster by reducing data traffic on the network.
68
Nikolai Merinov09f0abb2018-10-19 15:07:05 +050069The --dissociate option can be used to borrow the objects from
70the directory specified with the --reference option only to reduce
71network transfer, and stop borrowing from them after a first clone
72is made by making necessary local copies of borrowed objects.
73
Hu xiuyun9711a982015-12-11 11:16:41 +080074The --no-clone-bundle option disables any attempt to use
75$URL/clone.bundle to bootstrap a new Git repository from a
76resumeable bundle file on a content delivery network. This
77may be necessary if there are problems with the local Python
78HTTP client or proxy configuration, but the Git binary works.
Shawn O. Pearce88443382010-10-08 10:02:09 +020079
Mike Frysingerb8f7bb02018-10-10 01:05:11 -040080# Switching Manifest Branches
Shawn O. Pearce77bb4af2009-04-18 11:33:32 -070081
82To switch to another manifest branch, `repo init -b otherbranch`
83may be used in an existing client. However, as this only updates the
84manifest, a subsequent `repo sync` (or `repo sync -d`) is necessary
85to update the working directory files.
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070086"""
87
Mike Frysinger9180a072021-04-13 14:57:40 -040088 def _CommonOptions(self, p):
89 """Disable due to re-use of Wrapper()."""
90
Mike Frysinger66098f72020-02-05 00:01:59 -050091 def _Options(self, p, gitc_init=False):
Mike Frysinger9a734a32021-04-08 19:14:15 -040092 Wrapper().InitParser(p, gitc_init=gitc_init)
Victor Boivie841be342011-04-05 11:31:10 +020093
David Pursehouse3f5ea0b2012-11-17 03:13:09 +090094 def _RegisteredEnvironmentOptions(self):
95 return {'REPO_MANIFEST_URL': 'manifest_url',
96 'REPO_MIRROR_LOCATION': 'reference'}
97
Raman Tennetief99ec02021-03-04 10:29:40 -080098 def _CloneSuperproject(self, opt):
99 """Clone the superproject based on the superproject's url and branch.
100
101 Args:
102 opt: Program options returned from optparse. See _Options().
103 """
Raman Tenneti21dce3d2021-02-09 00:26:31 -0800104 superproject = git_superproject.Superproject(self.manifest,
Raman Tennetief99ec02021-03-04 10:29:40 -0800105 self.repodir,
Raman Tenneti784e16f2021-06-11 17:29:45 -0700106 self.git_event_log,
Raman Tennetief99ec02021-03-04 10:29:40 -0800107 quiet=opt.quiet)
Raman Tenneti784e16f2021-06-11 17:29:45 -0700108 sync_result = superproject.Sync()
109 if not sync_result.success:
Raman Tenneti8db30d62021-07-06 21:30:06 -0700110 print('warning: git update of superproject failed, repo sync will not '
111 'use superproject to fetch source; while this error is not fatal, '
112 'and you can continue to run repo sync, please run repo init with '
113 'the --no-use-superproject option to stop seeing this warning',
114 file=sys.stderr)
115 if sync_result.fatal and opt.use_superproject is not None:
Raman Tenneti784e16f2021-06-11 17:29:45 -0700116 sys.exit(1)
Raman Tenneti21dce3d2021-02-09 00:26:31 -0800117
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700118 def _SyncManifest(self, opt):
119 m = self.manifest.manifestProject
Shawn O. Pearce5470df62009-03-09 18:51:58 -0700120 is_new = not m.Exists
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700121
Jack Neusc474c9c2021-07-26 23:08:54 +0000122 # If repo has already been initialized, we take -u with the absence of
123 # --standalone-manifest to mean "transition to a standard repo set up",
124 # which necessitates starting fresh.
125 # If --standalone-manifest is set, we always tear everything down and start
126 # anew.
127 if not is_new:
128 was_standalone_manifest = m.config.GetString('manifest.standalone')
Jack Neus0f6f16e2021-10-11 18:14:35 +0000129 if was_standalone_manifest and not opt.manifest_url:
130 print('fatal: repo was initialized with a standlone manifest, '
131 'cannot be re-initialized without --manifest-url/-u')
132 sys.exit(1)
133
Raman Tenneti4a478ed2021-11-17 18:38:24 -0800134 if opt.standalone_manifest or (was_standalone_manifest and
135 opt.manifest_url):
Jack Neusc474c9c2021-07-26 23:08:54 +0000136 m.config.ClearCache()
137 if m.gitdir and os.path.exists(m.gitdir):
138 platform_utils.rmtree(m.gitdir)
139 if m.worktree and os.path.exists(m.worktree):
140 platform_utils.rmtree(m.worktree)
141
142 is_new = not m.Exists
Shawn O. Pearce5470df62009-03-09 18:51:58 -0700143 if is_new:
Shawn O. Pearce34fb20f2011-11-30 13:41:02 -0800144 if not opt.manifest_url:
Mike Frysinger401c6f02021-02-18 15:20:15 -0500145 print('fatal: manifest url is required.', file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700146 sys.exit(1)
147
148 if not opt.quiet:
Mike Frysingerdcbfadf2020-02-22 00:04:39 -0500149 print('Downloading manifest from %s' %
150 (GitConfig.ForUser().UrlInsteadOf(opt.manifest_url),),
Sarah Owenscecd1d82012-11-01 22:59:27 -0700151 file=sys.stderr)
Victor Boivie2b30e3a2012-10-05 12:37:58 +0200152
153 # The manifest project object doesn't keep track of the path on the
154 # server where this git is located, so let's save that here.
155 mirrored_manifest_git = None
156 if opt.reference:
Anthony King7993f3c2015-06-03 17:21:56 +0100157 manifest_git_path = urllib.parse.urlparse(opt.manifest_url).path[1:]
Victor Boivie2b30e3a2012-10-05 12:37:58 +0200158 mirrored_manifest_git = os.path.join(opt.reference, manifest_git_path)
159 if not mirrored_manifest_git.endswith(".git"):
160 mirrored_manifest_git += ".git"
161 if not os.path.exists(mirrored_manifest_git):
Samuel Holland5f0e57d2018-01-22 11:00:24 -0600162 mirrored_manifest_git = os.path.join(opt.reference,
163 '.repo/manifests.git')
Victor Boivie2b30e3a2012-10-05 12:37:58 +0200164
165 m._InitGitDir(mirror_git=mirrored_manifest_git)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700166
Jack Neusc474c9c2021-07-26 23:08:54 +0000167 # If standalone_manifest is set, mark the project as "standalone" -- we'll
168 # still do much of the manifests.git set up, but will avoid actual syncs to
169 # a remote.
170 standalone_manifest = False
171 if opt.standalone_manifest:
172 standalone_manifest = True
Jack Neus76491592021-10-11 17:20:39 +0000173 m.config.SetString('manifest.standalone', opt.manifest_url)
174 elif not opt.manifest_url and not opt.manifest_branch:
Jack Neusc474c9c2021-07-26 23:08:54 +0000175 # If -u is set and --standalone-manifest is not, then we're not in
176 # standalone mode. Otherwise, use config to infer what we were in the last
177 # init.
178 standalone_manifest = bool(m.config.GetString('manifest.standalone'))
Jack Neus76491592021-10-11 17:20:39 +0000179 if not standalone_manifest:
180 m.config.SetString('manifest.standalone', None)
Jack Neusc474c9c2021-07-26 23:08:54 +0000181
Nasser Grainawid92464e2019-05-21 10:41:35 -0600182 self._ConfigureDepth(opt)
183
Mike Frysinger50a81de2020-09-06 15:51:21 -0400184 # Set the remote URL before the remote branch as we might need it below.
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700185 if opt.manifest_url:
186 r = m.GetRemote(m.remote.name)
187 r.url = opt.manifest_url
188 r.ResetFetch()
189 r.Save()
190
Jack Neusc474c9c2021-07-26 23:08:54 +0000191 if not standalone_manifest:
192 if opt.manifest_branch:
193 if opt.manifest_branch == 'HEAD':
194 opt.manifest_branch = m.ResolveRemoteHead()
195 if opt.manifest_branch is None:
196 print('fatal: unable to resolve HEAD', file=sys.stderr)
197 sys.exit(1)
198 m.revisionExpr = opt.manifest_branch
Mike Frysinger50a81de2020-09-06 15:51:21 -0400199 else:
Jack Neusc474c9c2021-07-26 23:08:54 +0000200 if is_new:
201 default_branch = m.ResolveRemoteHead()
202 if default_branch is None:
203 # If the remote doesn't have HEAD configured, default to master.
204 default_branch = 'refs/heads/master'
205 m.revisionExpr = default_branch
206 else:
207 m.PreSync()
Mike Frysinger50a81de2020-09-06 15:51:21 -0400208
David Pursehouse1d947b32012-10-25 12:23:11 +0900209 groups = re.split(r'[,\s]+', opt.groups)
Pascal Muetschardc2a64dd2015-10-22 13:26:36 -0700210 all_platforms = ['linux', 'darwin', 'windows']
Conley Owensd21720d2012-04-16 11:02:21 -0700211 platformize = lambda x: 'platform-' + x
212 if opt.platform == 'auto':
213 if (not opt.mirror and
David Pursehouseabdf7502020-02-12 14:58:39 +0900214 not m.config.GetString('repo.mirror') == 'true'):
Conley Owensd21720d2012-04-16 11:02:21 -0700215 groups.append(platformize(platform.system().lower()))
216 elif opt.platform == 'all':
Colin Cross54657272012-04-23 13:39:48 -0700217 groups.extend(map(platformize, all_platforms))
Conley Owensd21720d2012-04-16 11:02:21 -0700218 elif opt.platform in all_platforms:
Pascal Muetschardc2a64dd2015-10-22 13:26:36 -0700219 groups.append(platformize(opt.platform))
Conley Owensd21720d2012-04-16 11:02:21 -0700220 elif opt.platform != 'none':
Sarah Owenscecd1d82012-11-01 22:59:27 -0700221 print('fatal: invalid platform flag', file=sys.stderr)
Conley Owensd21720d2012-04-16 11:02:21 -0700222 sys.exit(1)
223
Conley Owens971de8e2012-04-16 10:36:08 -0700224 groups = [x for x in groups if x]
225 groupstr = ','.join(groups)
Raman Tenneti080877e2021-03-09 15:19:06 -0800226 if opt.platform == 'auto' and groupstr == self.manifest.GetDefaultGroupsStr():
Conley Owens971de8e2012-04-16 10:36:08 -0700227 groupstr = None
228 m.config.SetString('manifest.groups', groupstr)
Colin Cross5acde752012-03-28 20:15:45 -0700229
Shawn O. Pearce88443382010-10-08 10:02:09 +0200230 if opt.reference:
231 m.config.SetString('repo.reference', opt.reference)
232
Nikolai Merinov09f0abb2018-10-19 15:07:05 +0500233 if opt.dissociate:
Mike Frysinger38867fb2021-02-09 23:14:41 -0500234 m.config.SetBoolean('repo.dissociate', opt.dissociate)
Nikolai Merinov09f0abb2018-10-19 15:07:05 +0500235
Mike Frysinger979d5bd2020-02-09 02:28:34 -0500236 if opt.worktree:
237 if opt.mirror:
238 print('fatal: --mirror and --worktree are incompatible',
239 file=sys.stderr)
240 sys.exit(1)
241 if opt.submodules:
242 print('fatal: --submodules and --worktree are incompatible',
243 file=sys.stderr)
244 sys.exit(1)
Mike Frysinger38867fb2021-02-09 23:14:41 -0500245 m.config.SetBoolean('repo.worktree', opt.worktree)
Mike Frysinger979d5bd2020-02-09 02:28:34 -0500246 if is_new:
247 m.use_git_worktrees = True
248 print('warning: --worktree is experimental!', file=sys.stderr)
249
Julien Campergue335f5ef2013-10-16 11:02:35 +0200250 if opt.archive:
251 if is_new:
Mike Frysinger38867fb2021-02-09 23:14:41 -0500252 m.config.SetBoolean('repo.archive', opt.archive)
Julien Campergue335f5ef2013-10-16 11:02:35 +0200253 else:
254 print('fatal: --archive is only supported when initializing a new '
255 'workspace.', file=sys.stderr)
256 print('Either delete the .repo folder in this workspace, or initialize '
257 'in another location.', file=sys.stderr)
258 sys.exit(1)
259
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800260 if opt.mirror:
Shawn O. Pearce5470df62009-03-09 18:51:58 -0700261 if is_new:
Mike Frysinger38867fb2021-02-09 23:14:41 -0500262 m.config.SetBoolean('repo.mirror', opt.mirror)
Shawn O. Pearce5470df62009-03-09 18:51:58 -0700263 else:
David Pursehouse25470982012-11-21 14:41:58 +0900264 print('fatal: --mirror is only supported when initializing a new '
265 'workspace.', file=sys.stderr)
266 print('Either delete the .repo folder in this workspace, or initialize '
267 'in another location.', file=sys.stderr)
Shawn O. Pearce5470df62009-03-09 18:51:58 -0700268 sys.exit(1)
Shawn O. Pearcee284ad12008-11-04 07:37:10 -0800269
Raman Tenneti6a2f4fb2021-04-02 10:55:33 -0700270 if opt.partial_clone is not None:
Xin Li745be2e2019-06-03 11:24:30 -0700271 if opt.mirror:
272 print('fatal: --mirror and --partial-clone are mutually exclusive',
273 file=sys.stderr)
274 sys.exit(1)
Mike Frysinger38867fb2021-02-09 23:14:41 -0500275 m.config.SetBoolean('repo.partialclone', opt.partial_clone)
Xin Li745be2e2019-06-03 11:24:30 -0700276 if opt.clone_filter:
277 m.config.SetString('repo.clonefilter', opt.clone_filter)
Raman Tenneti6a2f4fb2021-04-02 10:55:33 -0700278 elif m.config.GetBoolean('repo.partialclone'):
279 opt.clone_filter = m.config.GetString('repo.clonefilter')
Xin Li745be2e2019-06-03 11:24:30 -0700280 else:
281 opt.clone_filter = None
282
Raman Tennetif32f2432021-04-12 20:57:25 -0700283 if opt.partial_clone_exclude is not None:
284 m.config.SetString('repo.partialcloneexclude', opt.partial_clone_exclude)
285
Xin Lid79a4bc2020-05-20 16:03:45 -0700286 if opt.clone_bundle is None:
287 opt.clone_bundle = False if opt.partial_clone else True
288 else:
Mike Frysinger38867fb2021-02-09 23:14:41 -0500289 m.config.SetBoolean('repo.clonebundle', opt.clone_bundle)
Xin Lid79a4bc2020-05-20 16:03:45 -0700290
Martin Kellye4e94d22017-03-21 16:05:12 -0700291 if opt.submodules:
Mike Frysinger38867fb2021-02-09 23:14:41 -0500292 m.config.SetBoolean('repo.submodules', opt.submodules)
Martin Kellye4e94d22017-03-21 16:05:12 -0700293
XD Trol630876f2022-01-17 23:29:04 +0800294 if opt.git_lfs is not None:
295 if opt.git_lfs:
296 git_require((2, 17, 0), fail=True, msg='Git LFS support')
297
298 m.config.SetBoolean('repo.git-lfs', opt.git_lfs)
299 if not is_new:
300 print('warning: Changing --git-lfs settings will only affect new project checkouts.\n'
301 ' Existing projects will require manual updates.\n', file=sys.stderr)
302
Raman Tenneti21dce3d2021-02-09 00:26:31 -0800303 if opt.use_superproject is not None:
304 m.config.SetBoolean('repo.superproject', opt.use_superproject)
305
Jack Neusc474c9c2021-07-26 23:08:54 +0000306 if standalone_manifest:
307 if is_new:
308 manifest_name = 'default.xml'
Jack Neus19883852021-10-25 22:38:44 +0000309 manifest_data = fetch.fetch_file(opt.manifest_url, verbose=opt.verbose)
Jack Neusc474c9c2021-07-26 23:08:54 +0000310 dest = os.path.join(m.worktree, manifest_name)
311 os.makedirs(os.path.dirname(dest), exist_ok=True)
312 with open(dest, 'wb') as f:
313 f.write(manifest_data)
314 return
315
Mike Frysingeredd3d452020-02-21 23:55:07 -0500316 if not m.Sync_NetworkHalf(is_new=is_new, quiet=opt.quiet, verbose=opt.verbose,
Mike Frysingerc58ec4d2020-02-17 14:36:08 -0500317 clone_bundle=opt.clone_bundle,
David Pursehouseabdf7502020-02-12 14:58:39 +0900318 current_branch_only=opt.current_branch_only,
Mike Frysingerc58ec4d2020-02-17 14:36:08 -0500319 tags=opt.tags, submodules=opt.submodules,
Raman Tennetif32f2432021-04-12 20:57:25 -0700320 clone_filter=opt.clone_filter,
321 partial_clone_exclude=self.manifest.PartialCloneExclude):
Shawn O. Pearce1fc99f42009-03-17 08:06:18 -0700322 r = m.GetRemote(m.remote.name)
Sarah Owenscecd1d82012-11-01 22:59:27 -0700323 print('fatal: cannot obtain manifest %s' % r.url, file=sys.stderr)
Doug Anderson2630dd92011-04-07 13:36:30 -0700324
325 # Better delete the manifest git dir if we created it; otherwise next
326 # time (when user fixes problems) we won't go through the "is_new" logic.
327 if is_new:
Renaud Paquaya65adf72016-11-03 10:37:53 -0700328 platform_utils.rmtree(m.gitdir)
Shawn O. Pearce1fc99f42009-03-17 08:06:18 -0700329 sys.exit(1)
330
Florian Vallee5d016502012-06-07 17:19:26 +0200331 if opt.manifest_branch:
Martin Kelly224a31a2017-07-10 14:46:25 -0700332 m.MetaBranchSwitch(submodules=opt.submodules)
Florian Vallee5d016502012-06-07 17:19:26 +0200333
Shawn O. Pearce350cde42009-04-16 11:21:18 -0700334 syncbuf = SyncBuffer(m.config)
Martin Kellye4e94d22017-03-21 16:05:12 -0700335 m.Sync_LocalHalf(syncbuf, submodules=opt.submodules)
Shawn O. Pearce350cde42009-04-16 11:21:18 -0700336 syncbuf.Finish()
337
Shawn O. Pearcedf018832009-03-17 08:15:27 -0700338 if is_new or m.CurrentBranch is None:
Shawn O. Pearce0a389e92009-04-10 16:21:18 -0700339 if not m.StartBranch('default'):
Sarah Owenscecd1d82012-11-01 22:59:27 -0700340 print('fatal: cannot create default in manifest', file=sys.stderr)
Shawn O. Pearce0a389e92009-04-10 16:21:18 -0700341 sys.exit(1)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700342
343 def _LinkManifest(self, name):
344 if not name:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700345 print('fatal: manifest name (-m) is required.', file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700346 sys.exit(1)
347
348 try:
349 self.manifest.Link(name)
Sarah Owensa5be53f2012-09-09 15:37:57 -0700350 except ManifestParseError as e:
Sarah Owenscecd1d82012-11-01 22:59:27 -0700351 print("fatal: manifest '%s' not available" % name, file=sys.stderr)
352 print('fatal: %s' % str(e), file=sys.stderr)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700353 sys.exit(1)
354
Shawn O. Pearce37dbf2b2009-07-02 10:53:04 -0700355 def _Prompt(self, prompt, value):
Mike Frysingerab85fe72019-07-04 17:35:11 -0400356 print('%-10s [%s]: ' % (prompt, value), end='')
357 # TODO: When we require Python 3, use flush=True w/print above.
358 sys.stdout.flush()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700359 a = sys.stdin.readline().strip()
Shawn O. Pearce37dbf2b2009-07-02 10:53:04 -0700360 if a == '':
361 return value
362 return a
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700363
Mike Frysinger0b888912020-02-21 22:48:40 -0500364 def _ShouldConfigureUser(self, opt):
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -0400365 gc = self.client.globalConfig
Victor Boivie841be342011-04-05 11:31:10 +0200366 mp = self.manifest.manifestProject
367
368 # If we don't have local settings, get from global.
369 if not mp.config.Has('user.name') or not mp.config.Has('user.email'):
370 if not gc.Has('user.name') or not gc.Has('user.email'):
371 return True
372
373 mp.config.SetString('user.name', gc.GetString('user.name'))
374 mp.config.SetString('user.email', gc.GetString('user.email'))
375
Mike Frysinger0b888912020-02-21 22:48:40 -0500376 if not opt.quiet:
377 print()
378 print('Your identity is: %s <%s>' % (mp.config.GetString('user.name'),
379 mp.config.GetString('user.email')))
380 print("If you want to change this, please re-run 'repo init' with --config-name")
Victor Boivie841be342011-04-05 11:31:10 +0200381 return False
382
Mike Frysinger0b888912020-02-21 22:48:40 -0500383 def _ConfigureUser(self, opt):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700384 mp = self.manifest.manifestProject
385
Shawn O. Pearce37dbf2b2009-07-02 10:53:04 -0700386 while True:
Mike Frysinger0b888912020-02-21 22:48:40 -0500387 if not opt.quiet:
388 print()
David Pursehouse54a4e602020-02-12 14:31:05 +0900389 name = self._Prompt('Your Name', mp.UserName)
Shawn O. Pearce37dbf2b2009-07-02 10:53:04 -0700390 email = self._Prompt('Your Email', mp.UserEmail)
391
Mike Frysinger0b888912020-02-21 22:48:40 -0500392 if not opt.quiet:
393 print()
Sarah Owenscecd1d82012-11-01 22:59:27 -0700394 print('Your identity is: %s <%s>' % (name, email))
Mike Frysingerab85fe72019-07-04 17:35:11 -0400395 print('is this correct [y/N]? ', end='')
396 # TODO: When we require Python 3, use flush=True w/print above.
397 sys.stdout.flush()
David Pursehousefc241242012-11-14 09:19:39 +0900398 a = sys.stdin.readline().strip().lower()
Nico Sallembien6d7508b2010-04-01 11:03:53 -0700399 if a in ('yes', 'y', 't', 'true'):
Shawn O. Pearce37dbf2b2009-07-02 10:53:04 -0700400 break
401
402 if name != mp.UserName:
403 mp.config.SetString('user.name', name)
404 if email != mp.UserEmail:
405 mp.config.SetString('user.email', email)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700406
407 def _HasColorSet(self, gc):
408 for n in ['ui', 'diff', 'status']:
409 if gc.Has('color.%s' % n):
410 return True
411 return False
412
413 def _ConfigureColor(self):
Mike Frysinger8c1e9cb2020-09-06 14:53:18 -0400414 gc = self.client.globalConfig
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700415 if self._HasColorSet(gc):
416 return
417
418 class _Test(Coloring):
419 def __init__(self):
420 Coloring.__init__(self, gc, 'test color display')
421 self._on = True
422 out = _Test()
423
Sarah Owenscecd1d82012-11-01 22:59:27 -0700424 print()
425 print("Testing colorized output (for 'repo diff', 'repo status'):")
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700426
David Pursehouse8f62fb72012-11-14 12:09:38 +0900427 for c in ['black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan']:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700428 out.write(' ')
429 out.printer(fg=c)(' %-6s ', c)
430 out.write(' ')
431 out.printer(fg='white', bg='black')(' %s ' % 'white')
432 out.nl()
433
David Pursehouse8f62fb72012-11-14 12:09:38 +0900434 for c in ['bold', 'dim', 'ul', 'reverse']:
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700435 out.write(' ')
436 out.printer(fg='black', attr=c)(' %-6s ', c)
437 out.nl()
438
Mike Frysingerab85fe72019-07-04 17:35:11 -0400439 print('Enable color display in this user account (y/N)? ', end='')
440 # TODO: When we require Python 3, use flush=True w/print above.
441 sys.stdout.flush()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700442 a = sys.stdin.readline().strip().lower()
443 if a in ('y', 'yes', 't', 'true', 'on'):
444 gc.SetString('color.ui', 'auto')
445
Doug Anderson30d45292011-05-04 15:01:04 -0700446 def _ConfigureDepth(self, opt):
447 """Configure the depth we'll sync down.
448
449 Args:
450 opt: Options from optparse. We care about opt.depth.
451 """
452 # Opt.depth will be non-None if user actually passed --depth to repo init.
453 if opt.depth is not None:
454 if opt.depth > 0:
455 # Positive values will set the depth.
456 depth = str(opt.depth)
457 else:
458 # Negative numbers will clear the depth; passing None to SetString
459 # will do that.
460 depth = None
461
462 # We store the depth in the main manifest project.
463 self.manifest.manifestProject.config.SetString('repo.depth', depth)
464
Mike Frysinger0b888912020-02-21 22:48:40 -0500465 def _DisplayResult(self, opt):
Yang Zhenhui75cc3532012-10-23 15:41:54 +0800466 if self.manifest.IsMirror:
467 init_type = 'mirror '
468 else:
469 init_type = ''
470
Mike Frysinger0b888912020-02-21 22:48:40 -0500471 if not opt.quiet:
472 print()
473 print('repo %shas been initialized in %s' %
474 (init_type, self.manifest.topdir))
Yang Zhenhui75cc3532012-10-23 15:41:54 +0800475
476 current_dir = os.getcwd()
477 if current_dir != self.manifest.topdir:
David Pursehouse35765962013-01-29 09:49:48 +0900478 print('If this is not the directory in which you want to initialize '
Sarah Owenscecd1d82012-11-01 22:59:27 -0700479 'repo, please run:')
480 print(' rm -r %s/.repo' % self.manifest.topdir)
481 print('and try again.')
Yang Zhenhui75cc3532012-10-23 15:41:54 +0800482
Mike Frysingerae6cb082019-08-27 01:10:59 -0400483 def ValidateOptions(self, opt, args):
Victor Boivie297e7c62012-10-05 14:50:05 +0200484 if opt.reference:
Samuel Hollandbaa00092018-01-22 10:57:29 -0600485 opt.reference = os.path.expanduser(opt.reference)
Victor Boivie297e7c62012-10-05 14:50:05 +0200486
Julien Campergue335f5ef2013-10-16 11:02:35 +0200487 # Check this here, else manifest will be tagged "not new" and init won't be
488 # possible anymore without removing the .repo/manifests directory.
Raman Tenneti6bd89aa2021-11-16 11:48:09 -0800489 if opt.mirror:
490 if opt.archive:
491 self.OptionParser.error('--mirror and --archive cannot be used '
492 'together.')
493 if opt.use_superproject is not None:
494 self.OptionParser.error('--mirror and --use-superproject cannot be '
495 'used together.')
Mike Frysingerae6cb082019-08-27 01:10:59 -0400496
Raman Tenneti4a478ed2021-11-17 18:38:24 -0800497 if opt.standalone_manifest and (opt.manifest_branch or
498 opt.manifest_name != 'default.xml'):
Jack Neusc474c9c2021-07-26 23:08:54 +0000499 self.OptionParser.error('--manifest-branch and --manifest-name cannot'
500 ' be used with --standalone-manifest.')
501
Mike Frysinger0578ebf2020-08-27 01:50:12 -0400502 if args:
Mike Frysinger401c6f02021-02-18 15:20:15 -0500503 if opt.manifest_url:
504 self.OptionParser.error(
505 '--manifest-url option and URL argument both specified: only use '
506 'one to select the manifest URL.')
507
508 opt.manifest_url = args.pop(0)
509
510 if args:
511 self.OptionParser.error('too many arguments to init')
Mike Frysinger0578ebf2020-08-27 01:50:12 -0400512
Mike Frysingerae6cb082019-08-27 01:10:59 -0400513 def Execute(self, opt, args):
Mike Frysinger82caef62020-02-11 18:51:08 -0500514 git_require(MIN_GIT_VERSION_HARD, fail=True)
515 if not git_require(MIN_GIT_VERSION_SOFT):
516 print('repo: warning: git-%s+ will soon be required; please upgrade your '
517 'version of git to maintain support.'
518 % ('.'.join(str(x) for x in MIN_GIT_VERSION_SOFT),),
519 file=sys.stderr)
Julien Campergue335f5ef2013-10-16 11:02:35 +0200520
Mike Frysinger7936ce82020-02-29 02:53:41 -0500521 rp = self.manifest.repoProject
522
523 # Handle new --repo-url requests.
524 if opt.repo_url:
525 remote = rp.GetRemote('origin')
526 remote.url = opt.repo_url
527 remote.Save()
528
Mike Frysinger3599cc32020-02-29 02:53:41 -0500529 # Handle new --repo-rev requests.
530 if opt.repo_rev:
531 wrapper = Wrapper()
Mike Frysinger4aa85842022-01-25 02:10:28 -0500532 try:
533 remote_ref, rev = wrapper.check_repo_rev(
534 rp.gitdir, opt.repo_rev, repo_verify=opt.repo_verify, quiet=opt.quiet)
535 except wrapper.CloneFailure:
536 print('fatal: double check your --repo-rev setting.', file=sys.stderr)
537 sys.exit(1)
Mike Frysinger3599cc32020-02-29 02:53:41 -0500538 branch = rp.GetBranch('default')
539 branch.merge = remote_ref
Mike Frysinger5e2f32f2020-12-05 22:57:19 -0500540 rp.work_git.reset('--hard', rev)
Mike Frysinger3599cc32020-02-29 02:53:41 -0500541 branch.Save()
542
Mike Frysinger979d5bd2020-02-09 02:28:34 -0500543 if opt.worktree:
544 # Older versions of git supported worktree, but had dangerous gc bugs.
545 git_require((2, 15, 0), fail=True, msg='git gc worktree corruption')
546
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700547 self._SyncManifest(opt)
548 self._LinkManifest(opt.manifest_name)
549
Raman Tenneti21dce3d2021-02-09 00:26:31 -0800550 if self.manifest.manifestProject.config.GetBoolean('repo.superproject'):
Raman Tennetief99ec02021-03-04 10:29:40 -0800551 self._CloneSuperproject(opt)
Raman Tenneti21dce3d2021-02-09 00:26:31 -0800552
Shawn O. Pearce8630f392009-03-19 10:17:12 -0700553 if os.isatty(0) and os.isatty(1) and not self.manifest.IsMirror:
Mike Frysinger0b888912020-02-21 22:48:40 -0500554 if opt.config_name or self._ShouldConfigureUser(opt):
555 self._ConfigureUser(opt)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700556 self._ConfigureColor()
557
Mike Frysinger0b888912020-02-21 22:48:40 -0500558 self._DisplayResult(opt)