blob: 8e9302992be115921529f4d96225a446edc42e2b [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
Mike Frysingerb5d075d2021-03-01 00:56:38 -050015import multiprocessing
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070016import os
17import optparse
Conley Owensd21720d2012-04-16 11:02:21 -070018import platform
Colin Cross5acde752012-03-28 20:15:45 -070019import re
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070020import sys
21
David Rileye0684ad2017-04-05 00:02:59 -070022from event_log import EventLog
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070023from error import NoSuchProjectError
Colin Cross5acde752012-03-28 20:15:45 -070024from error import InvalidProjectGroupsError
Mike Frysingerb5d075d2021-03-01 00:56:38 -050025import progress
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070026
David Pursehouseb148ac92012-11-16 09:33:39 +090027
Mike Frysinger7c871162021-02-16 01:45:39 -050028# Number of projects to submit to a single worker process at a time.
29# This number represents a tradeoff between the overhead of IPC and finer
30# grained opportunity for parallelism. This particular value was chosen by
31# iterating through powers of two until the overall performance no longer
32# improved. The performance of this batch size is not a function of the
33# number of cores on the system.
34WORKER_BATCH_SIZE = 32
35
36
Mike Frysinger6a2400a2021-02-16 01:43:31 -050037# How many jobs to run in parallel by default? This assumes the jobs are
38# largely I/O bound and do not hit the network.
39DEFAULT_LOCAL_JOBS = min(os.cpu_count(), 8)
40
41
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070042class Command(object):
43 """Base class for any command line action in repo.
44 """
45
David Rileye0684ad2017-04-05 00:02:59 -070046 event_log = EventLog()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070047 manifest = None
48 _optparse = None
49
Mike Frysinger4f210542021-06-14 16:05:19 -040050 # Whether this command is a "common" one, i.e. whether the user would commonly
51 # use it or it's a more uncommon command. This is used by the help command to
52 # show short-vs-full summaries.
53 COMMON = False
54
Mike Frysinger6a2400a2021-02-16 01:43:31 -050055 # Whether this command supports running in parallel. If greater than 0,
56 # it is the number of parallel jobs to default to.
57 PARALLEL_JOBS = None
58
Mark E. Hamilton8ccfa742016-02-10 10:44:30 -070059 def WantPager(self, _opt):
Shawn O. Pearcedb45da12009-04-18 13:49:13 -070060 return False
61
David Pursehouseb148ac92012-11-16 09:33:39 +090062 def ReadEnvironmentOptions(self, opts):
63 """ Set options from environment variables. """
64
65 env_options = self._RegisteredEnvironmentOptions()
66
67 for env_key, opt_key in env_options.items():
68 # Get the user-set option value if any
69 opt_value = getattr(opts, opt_key)
70
71 # If the value is set, it means the user has passed it as a command
72 # line option, and we should use that. Otherwise we can try to set it
73 # with the value from the corresponding environment variable.
74 if opt_value is not None:
75 continue
76
77 env_value = os.environ.get(env_key)
78 if env_value is not None:
79 setattr(opts, opt_key, env_value)
80
81 return opts
82
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070083 @property
84 def OptionParser(self):
85 if self._optparse is None:
86 try:
87 me = 'repo %s' % self.NAME
88 usage = self.helpUsage.strip().replace('%prog', me)
89 except AttributeError:
90 usage = 'repo %s' % self.NAME
Mike Frysinger72ebf192020-02-19 01:20:18 -050091 epilog = 'Run `repo help %s` to view the detailed manual.' % self.NAME
92 self._optparse = optparse.OptionParser(usage=usage, epilog=epilog)
Mike Frysinger9180a072021-04-13 14:57:40 -040093 self._CommonOptions(self._optparse)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070094 self._Options(self._optparse)
95 return self._optparse
96
Mike Frysinger9180a072021-04-13 14:57:40 -040097 def _CommonOptions(self, p, opt_v=True):
98 """Initialize the option parser with common options.
99
100 These will show up for *all* subcommands, so use sparingly.
101 NB: Keep in sync with repo:InitParser().
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700102 """
Mike Frysinger9180a072021-04-13 14:57:40 -0400103 g = p.add_option_group('Logging options')
104 opts = ['-v'] if opt_v else []
105 g.add_option(*opts, '--verbose',
106 dest='output_mode', action='store_true',
107 help='show all output')
108 g.add_option('-q', '--quiet',
109 dest='output_mode', action='store_false',
110 help='only show errors')
111
Mike Frysinger6a2400a2021-02-16 01:43:31 -0500112 if self.PARALLEL_JOBS is not None:
113 p.add_option(
114 '-j', '--jobs',
115 type=int, default=self.PARALLEL_JOBS,
116 help='number of jobs to run in parallel (default: %s)' % self.PARALLEL_JOBS)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700117
Mike Frysinger9180a072021-04-13 14:57:40 -0400118 def _Options(self, p):
119 """Initialize the option parser with subcommand-specific options."""
120
David Pursehouseb148ac92012-11-16 09:33:39 +0900121 def _RegisteredEnvironmentOptions(self):
122 """Get options that can be set from environment variables.
123
124 Return a dictionary mapping environment variable name
125 to option key name that it can override.
126
127 Example: {'REPO_MY_OPTION': 'my_option'}
128
129 Will allow the option with key value 'my_option' to be set
130 from the value in the environment variable named 'REPO_MY_OPTION'.
131
132 Note: This does not work properly for options that are explicitly
133 set to None by the user, or options that are defined with a
134 default value other than None.
135
136 """
137 return {}
138
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700139 def Usage(self):
140 """Display usage and terminate.
141 """
142 self.OptionParser.print_usage()
143 sys.exit(1)
144
Mike Frysinger9180a072021-04-13 14:57:40 -0400145 def CommonValidateOptions(self, opt, args):
146 """Validate common options."""
147 opt.quiet = opt.output_mode is False
148 opt.verbose = opt.output_mode is True
149
Mike Frysingerae6cb082019-08-27 01:10:59 -0400150 def ValidateOptions(self, opt, args):
151 """Validate the user options & arguments before executing.
152
153 This is meant to help break the code up into logical steps. Some tips:
154 * Use self.OptionParser.error to display CLI related errors.
155 * Adjust opt member defaults as makes sense.
156 * Adjust the args list, but do so inplace so the caller sees updates.
157 * Try to avoid updating self state. Leave that to Execute.
158 """
159
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700160 def Execute(self, opt, args):
161 """Perform the action, after option parsing is complete.
162 """
163 raise NotImplementedError
Conley Owens971de8e2012-04-16 10:36:08 -0700164
Mike Frysingerb5d075d2021-03-01 00:56:38 -0500165 @staticmethod
166 def ExecuteInParallel(jobs, func, inputs, callback, output=None, ordered=False):
167 """Helper for managing parallel execution boiler plate.
168
169 For subcommands that can easily split their work up.
170
171 Args:
172 jobs: How many parallel processes to use.
173 func: The function to apply to each of the |inputs|. Usually a
174 functools.partial for wrapping additional arguments. It will be run
175 in a separate process, so it must be pickalable, so nested functions
176 won't work. Methods on the subcommand Command class should work.
177 inputs: The list of items to process. Must be a list.
178 callback: The function to pass the results to for processing. It will be
179 executed in the main thread and process the results of |func| as they
180 become available. Thus it may be a local nested function. Its return
181 value is passed back directly. It takes three arguments:
182 - The processing pool (or None with one job).
183 - The |output| argument.
184 - An iterator for the results.
185 output: An output manager. May be progress.Progess or color.Coloring.
186 ordered: Whether the jobs should be processed in order.
187
188 Returns:
189 The |callback| function's results are returned.
190 """
191 try:
192 # NB: Multiprocessing is heavy, so don't spin it up for one job.
193 if len(inputs) == 1 or jobs == 1:
194 return callback(None, output, (func(x) for x in inputs))
195 else:
196 with multiprocessing.Pool(jobs) as pool:
197 submit = pool.imap if ordered else pool.imap_unordered
198 return callback(pool, output, submit(func, inputs, chunksize=WORKER_BATCH_SIZE))
199 finally:
200 if isinstance(output, progress.Progress):
201 output.end()
202
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800203 def _ResetPathToProjectMap(self, projects):
204 self._by_path = dict((p.worktree, p) for p in projects)
205
206 def _UpdatePathToProjectMap(self, project):
207 self._by_path[project.worktree] = project
208
Simran Basib9a1b732015-08-20 12:19:28 -0700209 def _GetProjectByPath(self, manifest, path):
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800210 project = None
211 if os.path.exists(path):
212 oldpath = None
David Pursehouse5a2517f2020-02-12 14:55:01 +0900213 while (path and
214 path != oldpath and
215 path != manifest.topdir):
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800216 try:
217 project = self._by_path[path]
218 break
219 except KeyError:
220 oldpath = path
221 path = os.path.dirname(path)
Mark E. Hamiltonf9fe3e12016-02-23 18:10:42 -0700222 if not project and path == manifest.topdir:
223 try:
224 project = self._by_path[path]
225 except KeyError:
226 pass
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800227 else:
228 try:
229 project = self._by_path[path]
230 except KeyError:
231 pass
232 return project
233
Simran Basib9a1b732015-08-20 12:19:28 -0700234 def GetProjects(self, args, manifest=None, groups='', missing_ok=False,
235 submodules_ok=False):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700236 """A list of projects that match the arguments.
237 """
Simran Basib9a1b732015-08-20 12:19:28 -0700238 if not manifest:
239 manifest = self.manifest
240 all_projects_list = manifest.projects
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700241 result = []
242
Simran Basib9a1b732015-08-20 12:19:28 -0700243 mp = manifest.manifestProject
Colin Cross5acde752012-03-28 20:15:45 -0700244
Graham Christensen0369a062015-07-29 17:02:54 -0500245 if not groups:
Raman Tenneti080877e2021-03-09 15:19:06 -0800246 groups = manifest.GetGroupsStr()
David Pursehouse1d947b32012-10-25 12:23:11 +0900247 groups = [x for x in re.split(r'[,\s]+', groups) if x]
Colin Cross5acde752012-03-28 20:15:45 -0700248
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700249 if not args:
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800250 derived_projects = {}
251 for project in all_projects_list:
252 if submodules_ok or project.sync_s:
253 derived_projects.update((p.name, p)
254 for p in project.GetDerivedSubprojects())
255 all_projects_list.extend(derived_projects.values())
256 for project in all_projects_list:
Mark E. Hamilton8ccfa742016-02-10 10:44:30 -0700257 if (missing_ok or project.Exists) and project.MatchesGroups(groups):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700258 result.append(project)
259 else:
David James8d201162013-10-11 17:03:19 -0700260 self._ResetPathToProjectMap(all_projects_list)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700261
262 for arg in args:
Mike Frysingere778e572019-10-04 14:21:41 -0400263 # We have to filter by manifest groups in case the requested project is
264 # checked out multiple times or differently based on them.
265 projects = [project for project in manifest.GetProjectsWithName(arg)
266 if project.MatchesGroups(groups)]
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700267
David James8d201162013-10-11 17:03:19 -0700268 if not projects:
Anthony Newnamdf14a702011-01-09 17:31:57 -0800269 path = os.path.abspath(arg).replace('\\', '/')
Simran Basib9a1b732015-08-20 12:19:28 -0700270 project = self._GetProjectByPath(manifest, path)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700271
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800272 # If it's not a derived project, update path->project mapping and
273 # search again, as arg might actually point to a derived subproject.
Mark E. Hamilton8ccfa742016-02-10 10:44:30 -0700274 if (project and not project.Derived and (submodules_ok or
275 project.sync_s)):
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800276 search_again = False
277 for subproject in project.GetDerivedSubprojects():
278 self._UpdatePathToProjectMap(subproject)
279 search_again = True
280 if search_again:
Simran Basib9a1b732015-08-20 12:19:28 -0700281 project = self._GetProjectByPath(manifest, path) or project
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700282
David James8d201162013-10-11 17:03:19 -0700283 if project:
284 projects = [project]
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700285
David James8d201162013-10-11 17:03:19 -0700286 if not projects:
287 raise NoSuchProjectError(arg)
288
289 for project in projects:
290 if not missing_ok and not project.Exists:
Mike Frysingere778e572019-10-04 14:21:41 -0400291 raise NoSuchProjectError('%s (%s)' % (arg, project.relpath))
David James8d201162013-10-11 17:03:19 -0700292 if not project.MatchesGroups(groups):
293 raise InvalidProjectGroupsError(arg)
294
295 result.extend(projects)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700296
297 def _getpath(x):
298 return x.relpath
299 result.sort(key=_getpath)
300 return result
301
Takeshi Kanemoto1f056442016-01-26 14:11:35 +0900302 def FindProjects(self, args, inverse=False):
Zhiguang Lia8864fb2013-03-15 10:32:10 +0800303 result = []
David Pursehouse84c4d3c2013-04-30 10:57:37 +0900304 patterns = [re.compile(r'%s' % a, re.IGNORECASE) for a in args]
Zhiguang Lia8864fb2013-03-15 10:32:10 +0800305 for project in self.GetProjects(''):
David Pursehouse84c4d3c2013-04-30 10:57:37 +0900306 for pattern in patterns:
Takeshi Kanemoto1f056442016-01-26 14:11:35 +0900307 match = pattern.search(project.name) or pattern.search(project.relpath)
308 if not inverse and match:
Zhiguang Lia8864fb2013-03-15 10:32:10 +0800309 result.append(project)
310 break
Takeshi Kanemoto1f056442016-01-26 14:11:35 +0900311 if inverse and match:
312 break
313 else:
314 if inverse:
315 result.append(project)
Zhiguang Lia8864fb2013-03-15 10:32:10 +0800316 result.sort(key=lambda project: project.relpath)
317 return result
318
Mark E. Hamilton8ccfa742016-02-10 10:44:30 -0700319
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700320class InteractiveCommand(Command):
321 """Command which requires user interaction on the tty and
322 must not run within a pager, even if the user asks to.
323 """
David Pursehouse819827a2020-02-12 15:20:19 +0900324
Mark E. Hamilton8ccfa742016-02-10 10:44:30 -0700325 def WantPager(self, _opt):
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700326 return False
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700327
Mark E. Hamilton8ccfa742016-02-10 10:44:30 -0700328
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700329class PagedCommand(Command):
330 """Command which defaults to output in a pager, as its
331 display tends to be larger than one screen full.
332 """
David Pursehouse819827a2020-02-12 15:20:19 +0900333
Mark E. Hamilton8ccfa742016-02-10 10:44:30 -0700334 def WantPager(self, _opt):
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700335 return True
Shawn O. Pearcec95583b2009-03-03 17:47:06 -0800336
Mark E. Hamilton8ccfa742016-02-10 10:44:30 -0700337
Shawn O. Pearcec95583b2009-03-03 17:47:06 -0800338class MirrorSafeCommand(object):
339 """Command permits itself to run within a mirror,
340 and does not require a working directory.
341 """
Dan Willemsen9ff2ece2015-08-31 15:45:06 -0700342
Mark E. Hamilton8ccfa742016-02-10 10:44:30 -0700343
Dan Willemsen79360642015-08-31 15:45:06 -0700344class GitcAvailableCommand(object):
Dan Willemsen9ff2ece2015-08-31 15:45:06 -0700345 """Command that requires GITC to be available, but does
346 not require the local client to be a GITC client.
347 """
Dan Willemsen79360642015-08-31 15:45:06 -0700348
Mark E. Hamilton8ccfa742016-02-10 10:44:30 -0700349
Dan Willemsen79360642015-08-31 15:45:06 -0700350class GitcClientCommand(object):
351 """Command that requires the local client to be a GITC
352 client.
353 """