blob: b972a0be38dceadb9d5d25660b6a5c7d7b6965f8 [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
Colin Cross5acde752012-03-28 20:15:45 -070018import re
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070019import sys
20
David Rileye0684ad2017-04-05 00:02:59 -070021from event_log import EventLog
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070022from error import NoSuchProjectError
Colin Cross5acde752012-03-28 20:15:45 -070023from error import InvalidProjectGroupsError
Mike Frysingerb5d075d2021-03-01 00:56:38 -050024import progress
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070025
David Pursehouseb148ac92012-11-16 09:33:39 +090026
Mike Frysingerdf8b1cb2021-07-26 15:59:20 -040027# Are we generating man-pages?
28GENERATE_MANPAGES = os.environ.get('_REPO_GENERATE_MANPAGES_') == ' indeed! '
29
30
Mike Frysinger7c871162021-02-16 01:45:39 -050031# Number of projects to submit to a single worker process at a time.
32# This number represents a tradeoff between the overhead of IPC and finer
33# grained opportunity for parallelism. This particular value was chosen by
34# iterating through powers of two until the overall performance no longer
35# improved. The performance of this batch size is not a function of the
36# number of cores on the system.
37WORKER_BATCH_SIZE = 32
38
39
Mike Frysinger6a2400a2021-02-16 01:43:31 -050040# How many jobs to run in parallel by default? This assumes the jobs are
41# largely I/O bound and do not hit the network.
42DEFAULT_LOCAL_JOBS = min(os.cpu_count(), 8)
43
44
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070045class Command(object):
46 """Base class for any command line action in repo.
47 """
48
Mike Frysingerd88b3692021-06-14 16:09:29 -040049 # Singleton for all commands to track overall repo command execution and
50 # provide event summary to callers. Only used by sync subcommand currently.
51 #
52 # NB: This is being replaced by git trace2 events. See git_trace2_event_log.
53 event_log = EventLog()
54
Mike Frysinger4f210542021-06-14 16:05:19 -040055 # Whether this command is a "common" one, i.e. whether the user would commonly
56 # use it or it's a more uncommon command. This is used by the help command to
57 # show short-vs-full summaries.
58 COMMON = False
59
Mike Frysinger6a2400a2021-02-16 01:43:31 -050060 # Whether this command supports running in parallel. If greater than 0,
61 # it is the number of parallel jobs to default to.
62 PARALLEL_JOBS = None
63
Raman Tenneti784e16f2021-06-11 17:29:45 -070064 def __init__(self, repodir=None, client=None, manifest=None, gitc_manifest=None,
65 git_event_log=None):
Mike Frysingerd58d0dd2021-06-14 16:17:27 -040066 self.repodir = repodir
67 self.client = client
68 self.manifest = manifest
69 self.gitc_manifest = gitc_manifest
Raman Tenneti784e16f2021-06-11 17:29:45 -070070 self.git_event_log = git_event_log
Mike Frysingerd58d0dd2021-06-14 16:17:27 -040071
72 # Cache for the OptionParser property.
73 self._optparse = None
74
Mark E. Hamilton8ccfa742016-02-10 10:44:30 -070075 def WantPager(self, _opt):
Shawn O. Pearcedb45da12009-04-18 13:49:13 -070076 return False
77
David Pursehouseb148ac92012-11-16 09:33:39 +090078 def ReadEnvironmentOptions(self, opts):
79 """ Set options from environment variables. """
80
81 env_options = self._RegisteredEnvironmentOptions()
82
83 for env_key, opt_key in env_options.items():
84 # Get the user-set option value if any
85 opt_value = getattr(opts, opt_key)
86
87 # If the value is set, it means the user has passed it as a command
88 # line option, and we should use that. Otherwise we can try to set it
89 # with the value from the corresponding environment variable.
90 if opt_value is not None:
91 continue
92
93 env_value = os.environ.get(env_key)
94 if env_value is not None:
95 setattr(opts, opt_key, env_value)
96
97 return opts
98
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070099 @property
100 def OptionParser(self):
101 if self._optparse is None:
102 try:
103 me = 'repo %s' % self.NAME
104 usage = self.helpUsage.strip().replace('%prog', me)
105 except AttributeError:
106 usage = 'repo %s' % self.NAME
Mike Frysinger72ebf192020-02-19 01:20:18 -0500107 epilog = 'Run `repo help %s` to view the detailed manual.' % self.NAME
108 self._optparse = optparse.OptionParser(usage=usage, epilog=epilog)
Mike Frysinger9180a072021-04-13 14:57:40 -0400109 self._CommonOptions(self._optparse)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700110 self._Options(self._optparse)
111 return self._optparse
112
Mike Frysinger9180a072021-04-13 14:57:40 -0400113 def _CommonOptions(self, p, opt_v=True):
114 """Initialize the option parser with common options.
115
116 These will show up for *all* subcommands, so use sparingly.
117 NB: Keep in sync with repo:InitParser().
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700118 """
Mike Frysinger9180a072021-04-13 14:57:40 -0400119 g = p.add_option_group('Logging options')
120 opts = ['-v'] if opt_v else []
121 g.add_option(*opts, '--verbose',
122 dest='output_mode', action='store_true',
123 help='show all output')
124 g.add_option('-q', '--quiet',
125 dest='output_mode', action='store_false',
126 help='only show errors')
127
Mike Frysinger6a2400a2021-02-16 01:43:31 -0500128 if self.PARALLEL_JOBS is not None:
Mike Frysingerdf8b1cb2021-07-26 15:59:20 -0400129 default = 'based on number of CPU cores'
130 if not GENERATE_MANPAGES:
131 # Only include active cpu count if we aren't generating man pages.
132 default = f'%default; {default}'
Mike Frysinger6a2400a2021-02-16 01:43:31 -0500133 p.add_option(
134 '-j', '--jobs',
135 type=int, default=self.PARALLEL_JOBS,
Mike Frysingerdf8b1cb2021-07-26 15:59:20 -0400136 help=f'number of jobs to run in parallel (default: {default})')
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700137
Mike Frysinger9180a072021-04-13 14:57:40 -0400138 def _Options(self, p):
139 """Initialize the option parser with subcommand-specific options."""
140
David Pursehouseb148ac92012-11-16 09:33:39 +0900141 def _RegisteredEnvironmentOptions(self):
142 """Get options that can be set from environment variables.
143
144 Return a dictionary mapping environment variable name
145 to option key name that it can override.
146
147 Example: {'REPO_MY_OPTION': 'my_option'}
148
149 Will allow the option with key value 'my_option' to be set
150 from the value in the environment variable named 'REPO_MY_OPTION'.
151
152 Note: This does not work properly for options that are explicitly
153 set to None by the user, or options that are defined with a
154 default value other than None.
155
156 """
157 return {}
158
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700159 def Usage(self):
160 """Display usage and terminate.
161 """
162 self.OptionParser.print_usage()
163 sys.exit(1)
164
Mike Frysinger9180a072021-04-13 14:57:40 -0400165 def CommonValidateOptions(self, opt, args):
166 """Validate common options."""
167 opt.quiet = opt.output_mode is False
168 opt.verbose = opt.output_mode is True
169
Mike Frysingerae6cb082019-08-27 01:10:59 -0400170 def ValidateOptions(self, opt, args):
171 """Validate the user options & arguments before executing.
172
173 This is meant to help break the code up into logical steps. Some tips:
174 * Use self.OptionParser.error to display CLI related errors.
175 * Adjust opt member defaults as makes sense.
176 * Adjust the args list, but do so inplace so the caller sees updates.
177 * Try to avoid updating self state. Leave that to Execute.
178 """
179
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700180 def Execute(self, opt, args):
181 """Perform the action, after option parsing is complete.
182 """
183 raise NotImplementedError
Conley Owens971de8e2012-04-16 10:36:08 -0700184
Mike Frysingerb5d075d2021-03-01 00:56:38 -0500185 @staticmethod
186 def ExecuteInParallel(jobs, func, inputs, callback, output=None, ordered=False):
187 """Helper for managing parallel execution boiler plate.
188
189 For subcommands that can easily split their work up.
190
191 Args:
192 jobs: How many parallel processes to use.
193 func: The function to apply to each of the |inputs|. Usually a
194 functools.partial for wrapping additional arguments. It will be run
195 in a separate process, so it must be pickalable, so nested functions
196 won't work. Methods on the subcommand Command class should work.
197 inputs: The list of items to process. Must be a list.
198 callback: The function to pass the results to for processing. It will be
199 executed in the main thread and process the results of |func| as they
200 become available. Thus it may be a local nested function. Its return
201 value is passed back directly. It takes three arguments:
202 - The processing pool (or None with one job).
203 - The |output| argument.
204 - An iterator for the results.
205 output: An output manager. May be progress.Progess or color.Coloring.
206 ordered: Whether the jobs should be processed in order.
207
208 Returns:
209 The |callback| function's results are returned.
210 """
211 try:
212 # NB: Multiprocessing is heavy, so don't spin it up for one job.
213 if len(inputs) == 1 or jobs == 1:
214 return callback(None, output, (func(x) for x in inputs))
215 else:
216 with multiprocessing.Pool(jobs) as pool:
217 submit = pool.imap if ordered else pool.imap_unordered
218 return callback(pool, output, submit(func, inputs, chunksize=WORKER_BATCH_SIZE))
219 finally:
220 if isinstance(output, progress.Progress):
221 output.end()
222
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800223 def _ResetPathToProjectMap(self, projects):
224 self._by_path = dict((p.worktree, p) for p in projects)
225
226 def _UpdatePathToProjectMap(self, project):
227 self._by_path[project.worktree] = project
228
Simran Basib9a1b732015-08-20 12:19:28 -0700229 def _GetProjectByPath(self, manifest, path):
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800230 project = None
231 if os.path.exists(path):
232 oldpath = None
David Pursehouse5a2517f2020-02-12 14:55:01 +0900233 while (path and
234 path != oldpath and
235 path != manifest.topdir):
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800236 try:
237 project = self._by_path[path]
238 break
239 except KeyError:
240 oldpath = path
241 path = os.path.dirname(path)
Mark E. Hamiltonf9fe3e12016-02-23 18:10:42 -0700242 if not project and path == manifest.topdir:
243 try:
244 project = self._by_path[path]
245 except KeyError:
246 pass
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800247 else:
248 try:
249 project = self._by_path[path]
250 except KeyError:
251 pass
252 return project
253
Simran Basib9a1b732015-08-20 12:19:28 -0700254 def GetProjects(self, args, manifest=None, groups='', missing_ok=False,
255 submodules_ok=False):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700256 """A list of projects that match the arguments.
257 """
Simran Basib9a1b732015-08-20 12:19:28 -0700258 if not manifest:
259 manifest = self.manifest
260 all_projects_list = manifest.projects
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700261 result = []
262
Simran Basib9a1b732015-08-20 12:19:28 -0700263 mp = manifest.manifestProject
Colin Cross5acde752012-03-28 20:15:45 -0700264
Graham Christensen0369a062015-07-29 17:02:54 -0500265 if not groups:
Raman Tenneti080877e2021-03-09 15:19:06 -0800266 groups = manifest.GetGroupsStr()
David Pursehouse1d947b32012-10-25 12:23:11 +0900267 groups = [x for x in re.split(r'[,\s]+', groups) if x]
Colin Cross5acde752012-03-28 20:15:45 -0700268
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700269 if not args:
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800270 derived_projects = {}
271 for project in all_projects_list:
272 if submodules_ok or project.sync_s:
273 derived_projects.update((p.name, p)
274 for p in project.GetDerivedSubprojects())
275 all_projects_list.extend(derived_projects.values())
276 for project in all_projects_list:
Mark E. Hamilton8ccfa742016-02-10 10:44:30 -0700277 if (missing_ok or project.Exists) and project.MatchesGroups(groups):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700278 result.append(project)
279 else:
David James8d201162013-10-11 17:03:19 -0700280 self._ResetPathToProjectMap(all_projects_list)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700281
282 for arg in args:
Mike Frysingere778e572019-10-04 14:21:41 -0400283 # We have to filter by manifest groups in case the requested project is
284 # checked out multiple times or differently based on them.
285 projects = [project for project in manifest.GetProjectsWithName(arg)
286 if project.MatchesGroups(groups)]
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700287
David James8d201162013-10-11 17:03:19 -0700288 if not projects:
Anthony Newnamdf14a702011-01-09 17:31:57 -0800289 path = os.path.abspath(arg).replace('\\', '/')
Simran Basib9a1b732015-08-20 12:19:28 -0700290 project = self._GetProjectByPath(manifest, path)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700291
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800292 # If it's not a derived project, update path->project mapping and
293 # search again, as arg might actually point to a derived subproject.
Mark E. Hamilton8ccfa742016-02-10 10:44:30 -0700294 if (project and not project.Derived and (submodules_ok or
295 project.sync_s)):
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800296 search_again = False
297 for subproject in project.GetDerivedSubprojects():
298 self._UpdatePathToProjectMap(subproject)
299 search_again = True
300 if search_again:
Simran Basib9a1b732015-08-20 12:19:28 -0700301 project = self._GetProjectByPath(manifest, path) or project
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700302
David James8d201162013-10-11 17:03:19 -0700303 if project:
304 projects = [project]
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700305
David James8d201162013-10-11 17:03:19 -0700306 if not projects:
307 raise NoSuchProjectError(arg)
308
309 for project in projects:
310 if not missing_ok and not project.Exists:
Mike Frysingere778e572019-10-04 14:21:41 -0400311 raise NoSuchProjectError('%s (%s)' % (arg, project.relpath))
David James8d201162013-10-11 17:03:19 -0700312 if not project.MatchesGroups(groups):
313 raise InvalidProjectGroupsError(arg)
314
315 result.extend(projects)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700316
317 def _getpath(x):
318 return x.relpath
319 result.sort(key=_getpath)
320 return result
321
Takeshi Kanemoto1f056442016-01-26 14:11:35 +0900322 def FindProjects(self, args, inverse=False):
Zhiguang Lia8864fb2013-03-15 10:32:10 +0800323 result = []
David Pursehouse84c4d3c2013-04-30 10:57:37 +0900324 patterns = [re.compile(r'%s' % a, re.IGNORECASE) for a in args]
Zhiguang Lia8864fb2013-03-15 10:32:10 +0800325 for project in self.GetProjects(''):
David Pursehouse84c4d3c2013-04-30 10:57:37 +0900326 for pattern in patterns:
Takeshi Kanemoto1f056442016-01-26 14:11:35 +0900327 match = pattern.search(project.name) or pattern.search(project.relpath)
328 if not inverse and match:
Zhiguang Lia8864fb2013-03-15 10:32:10 +0800329 result.append(project)
330 break
Takeshi Kanemoto1f056442016-01-26 14:11:35 +0900331 if inverse and match:
332 break
333 else:
334 if inverse:
335 result.append(project)
Zhiguang Lia8864fb2013-03-15 10:32:10 +0800336 result.sort(key=lambda project: project.relpath)
337 return result
338
Mark E. Hamilton8ccfa742016-02-10 10:44:30 -0700339
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700340class InteractiveCommand(Command):
341 """Command which requires user interaction on the tty and
342 must not run within a pager, even if the user asks to.
343 """
David Pursehouse819827a2020-02-12 15:20:19 +0900344
Mark E. Hamilton8ccfa742016-02-10 10:44:30 -0700345 def WantPager(self, _opt):
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700346 return False
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700347
Mark E. Hamilton8ccfa742016-02-10 10:44:30 -0700348
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700349class PagedCommand(Command):
350 """Command which defaults to output in a pager, as its
351 display tends to be larger than one screen full.
352 """
David Pursehouse819827a2020-02-12 15:20:19 +0900353
Mark E. Hamilton8ccfa742016-02-10 10:44:30 -0700354 def WantPager(self, _opt):
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700355 return True
Shawn O. Pearcec95583b2009-03-03 17:47:06 -0800356
Mark E. Hamilton8ccfa742016-02-10 10:44:30 -0700357
Shawn O. Pearcec95583b2009-03-03 17:47:06 -0800358class MirrorSafeCommand(object):
359 """Command permits itself to run within a mirror,
360 and does not require a working directory.
361 """
Dan Willemsen9ff2ece2015-08-31 15:45:06 -0700362
Mark E. Hamilton8ccfa742016-02-10 10:44:30 -0700363
Dan Willemsen79360642015-08-31 15:45:06 -0700364class GitcAvailableCommand(object):
Dan Willemsen9ff2ece2015-08-31 15:45:06 -0700365 """Command that requires GITC to be available, but does
366 not require the local client to be a GITC client.
367 """
Dan Willemsen79360642015-08-31 15:45:06 -0700368
Mark E. Hamilton8ccfa742016-02-10 10:44:30 -0700369
Dan Willemsen79360642015-08-31 15:45:06 -0700370class GitcClientCommand(object):
371 """Command that requires the local client to be a GITC
372 client.
373 """