blob: 9b1220dc460576d645573ee47d2f9dc835884b3e [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
46 common = False
David Rileye0684ad2017-04-05 00:02:59 -070047 event_log = EventLog()
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070048 manifest = None
49 _optparse = None
50
Mike Frysinger6a2400a2021-02-16 01:43:31 -050051 # Whether this command supports running in parallel. If greater than 0,
52 # it is the number of parallel jobs to default to.
53 PARALLEL_JOBS = None
54
Mark E. Hamilton8ccfa742016-02-10 10:44:30 -070055 def WantPager(self, _opt):
Shawn O. Pearcedb45da12009-04-18 13:49:13 -070056 return False
57
David Pursehouseb148ac92012-11-16 09:33:39 +090058 def ReadEnvironmentOptions(self, opts):
59 """ Set options from environment variables. """
60
61 env_options = self._RegisteredEnvironmentOptions()
62
63 for env_key, opt_key in env_options.items():
64 # Get the user-set option value if any
65 opt_value = getattr(opts, opt_key)
66
67 # If the value is set, it means the user has passed it as a command
68 # line option, and we should use that. Otherwise we can try to set it
69 # with the value from the corresponding environment variable.
70 if opt_value is not None:
71 continue
72
73 env_value = os.environ.get(env_key)
74 if env_value is not None:
75 setattr(opts, opt_key, env_value)
76
77 return opts
78
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070079 @property
80 def OptionParser(self):
81 if self._optparse is None:
82 try:
83 me = 'repo %s' % self.NAME
84 usage = self.helpUsage.strip().replace('%prog', me)
85 except AttributeError:
86 usage = 'repo %s' % self.NAME
Mike Frysinger72ebf192020-02-19 01:20:18 -050087 epilog = 'Run `repo help %s` to view the detailed manual.' % self.NAME
88 self._optparse = optparse.OptionParser(usage=usage, epilog=epilog)
Mike Frysinger9180a072021-04-13 14:57:40 -040089 self._CommonOptions(self._optparse)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070090 self._Options(self._optparse)
91 return self._optparse
92
Mike Frysinger9180a072021-04-13 14:57:40 -040093 def _CommonOptions(self, p, opt_v=True):
94 """Initialize the option parser with common options.
95
96 These will show up for *all* subcommands, so use sparingly.
97 NB: Keep in sync with repo:InitParser().
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -070098 """
Mike Frysinger9180a072021-04-13 14:57:40 -040099 g = p.add_option_group('Logging options')
100 opts = ['-v'] if opt_v else []
101 g.add_option(*opts, '--verbose',
102 dest='output_mode', action='store_true',
103 help='show all output')
104 g.add_option('-q', '--quiet',
105 dest='output_mode', action='store_false',
106 help='only show errors')
107
Mike Frysinger6a2400a2021-02-16 01:43:31 -0500108 if self.PARALLEL_JOBS is not None:
109 p.add_option(
110 '-j', '--jobs',
111 type=int, default=self.PARALLEL_JOBS,
112 help='number of jobs to run in parallel (default: %s)' % self.PARALLEL_JOBS)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700113
Mike Frysinger9180a072021-04-13 14:57:40 -0400114 def _Options(self, p):
115 """Initialize the option parser with subcommand-specific options."""
116
David Pursehouseb148ac92012-11-16 09:33:39 +0900117 def _RegisteredEnvironmentOptions(self):
118 """Get options that can be set from environment variables.
119
120 Return a dictionary mapping environment variable name
121 to option key name that it can override.
122
123 Example: {'REPO_MY_OPTION': 'my_option'}
124
125 Will allow the option with key value 'my_option' to be set
126 from the value in the environment variable named 'REPO_MY_OPTION'.
127
128 Note: This does not work properly for options that are explicitly
129 set to None by the user, or options that are defined with a
130 default value other than None.
131
132 """
133 return {}
134
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700135 def Usage(self):
136 """Display usage and terminate.
137 """
138 self.OptionParser.print_usage()
139 sys.exit(1)
140
Mike Frysinger9180a072021-04-13 14:57:40 -0400141 def CommonValidateOptions(self, opt, args):
142 """Validate common options."""
143 opt.quiet = opt.output_mode is False
144 opt.verbose = opt.output_mode is True
145
Mike Frysingerae6cb082019-08-27 01:10:59 -0400146 def ValidateOptions(self, opt, args):
147 """Validate the user options & arguments before executing.
148
149 This is meant to help break the code up into logical steps. Some tips:
150 * Use self.OptionParser.error to display CLI related errors.
151 * Adjust opt member defaults as makes sense.
152 * Adjust the args list, but do so inplace so the caller sees updates.
153 * Try to avoid updating self state. Leave that to Execute.
154 """
155
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700156 def Execute(self, opt, args):
157 """Perform the action, after option parsing is complete.
158 """
159 raise NotImplementedError
Conley Owens971de8e2012-04-16 10:36:08 -0700160
Mike Frysingerb5d075d2021-03-01 00:56:38 -0500161 @staticmethod
162 def ExecuteInParallel(jobs, func, inputs, callback, output=None, ordered=False):
163 """Helper for managing parallel execution boiler plate.
164
165 For subcommands that can easily split their work up.
166
167 Args:
168 jobs: How many parallel processes to use.
169 func: The function to apply to each of the |inputs|. Usually a
170 functools.partial for wrapping additional arguments. It will be run
171 in a separate process, so it must be pickalable, so nested functions
172 won't work. Methods on the subcommand Command class should work.
173 inputs: The list of items to process. Must be a list.
174 callback: The function to pass the results to for processing. It will be
175 executed in the main thread and process the results of |func| as they
176 become available. Thus it may be a local nested function. Its return
177 value is passed back directly. It takes three arguments:
178 - The processing pool (or None with one job).
179 - The |output| argument.
180 - An iterator for the results.
181 output: An output manager. May be progress.Progess or color.Coloring.
182 ordered: Whether the jobs should be processed in order.
183
184 Returns:
185 The |callback| function's results are returned.
186 """
187 try:
188 # NB: Multiprocessing is heavy, so don't spin it up for one job.
189 if len(inputs) == 1 or jobs == 1:
190 return callback(None, output, (func(x) for x in inputs))
191 else:
192 with multiprocessing.Pool(jobs) as pool:
193 submit = pool.imap if ordered else pool.imap_unordered
194 return callback(pool, output, submit(func, inputs, chunksize=WORKER_BATCH_SIZE))
195 finally:
196 if isinstance(output, progress.Progress):
197 output.end()
198
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800199 def _ResetPathToProjectMap(self, projects):
200 self._by_path = dict((p.worktree, p) for p in projects)
201
202 def _UpdatePathToProjectMap(self, project):
203 self._by_path[project.worktree] = project
204
Simran Basib9a1b732015-08-20 12:19:28 -0700205 def _GetProjectByPath(self, manifest, path):
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800206 project = None
207 if os.path.exists(path):
208 oldpath = None
David Pursehouse5a2517f2020-02-12 14:55:01 +0900209 while (path and
210 path != oldpath and
211 path != manifest.topdir):
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800212 try:
213 project = self._by_path[path]
214 break
215 except KeyError:
216 oldpath = path
217 path = os.path.dirname(path)
Mark E. Hamiltonf9fe3e12016-02-23 18:10:42 -0700218 if not project and path == manifest.topdir:
219 try:
220 project = self._by_path[path]
221 except KeyError:
222 pass
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800223 else:
224 try:
225 project = self._by_path[path]
226 except KeyError:
227 pass
228 return project
229
Simran Basib9a1b732015-08-20 12:19:28 -0700230 def GetProjects(self, args, manifest=None, groups='', missing_ok=False,
231 submodules_ok=False):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700232 """A list of projects that match the arguments.
233 """
Simran Basib9a1b732015-08-20 12:19:28 -0700234 if not manifest:
235 manifest = self.manifest
236 all_projects_list = manifest.projects
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700237 result = []
238
Simran Basib9a1b732015-08-20 12:19:28 -0700239 mp = manifest.manifestProject
Colin Cross5acde752012-03-28 20:15:45 -0700240
Graham Christensen0369a062015-07-29 17:02:54 -0500241 if not groups:
Raman Tenneti080877e2021-03-09 15:19:06 -0800242 groups = manifest.GetGroupsStr()
David Pursehouse1d947b32012-10-25 12:23:11 +0900243 groups = [x for x in re.split(r'[,\s]+', groups) if x]
Colin Cross5acde752012-03-28 20:15:45 -0700244
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700245 if not args:
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800246 derived_projects = {}
247 for project in all_projects_list:
248 if submodules_ok or project.sync_s:
249 derived_projects.update((p.name, p)
250 for p in project.GetDerivedSubprojects())
251 all_projects_list.extend(derived_projects.values())
252 for project in all_projects_list:
Mark E. Hamilton8ccfa742016-02-10 10:44:30 -0700253 if (missing_ok or project.Exists) and project.MatchesGroups(groups):
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700254 result.append(project)
255 else:
David James8d201162013-10-11 17:03:19 -0700256 self._ResetPathToProjectMap(all_projects_list)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700257
258 for arg in args:
Mike Frysingere778e572019-10-04 14:21:41 -0400259 # We have to filter by manifest groups in case the requested project is
260 # checked out multiple times or differently based on them.
261 projects = [project for project in manifest.GetProjectsWithName(arg)
262 if project.MatchesGroups(groups)]
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700263
David James8d201162013-10-11 17:03:19 -0700264 if not projects:
Anthony Newnamdf14a702011-01-09 17:31:57 -0800265 path = os.path.abspath(arg).replace('\\', '/')
Simran Basib9a1b732015-08-20 12:19:28 -0700266 project = self._GetProjectByPath(manifest, path)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700267
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800268 # If it's not a derived project, update path->project mapping and
269 # search again, as arg might actually point to a derived subproject.
Mark E. Hamilton8ccfa742016-02-10 10:44:30 -0700270 if (project and not project.Derived and (submodules_ok or
271 project.sync_s)):
Che-Liang Chioub2bd91c2012-01-11 11:28:42 +0800272 search_again = False
273 for subproject in project.GetDerivedSubprojects():
274 self._UpdatePathToProjectMap(subproject)
275 search_again = True
276 if search_again:
Simran Basib9a1b732015-08-20 12:19:28 -0700277 project = self._GetProjectByPath(manifest, path) or project
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700278
David James8d201162013-10-11 17:03:19 -0700279 if project:
280 projects = [project]
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700281
David James8d201162013-10-11 17:03:19 -0700282 if not projects:
283 raise NoSuchProjectError(arg)
284
285 for project in projects:
286 if not missing_ok and not project.Exists:
Mike Frysingere778e572019-10-04 14:21:41 -0400287 raise NoSuchProjectError('%s (%s)' % (arg, project.relpath))
David James8d201162013-10-11 17:03:19 -0700288 if not project.MatchesGroups(groups):
289 raise InvalidProjectGroupsError(arg)
290
291 result.extend(projects)
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700292
293 def _getpath(x):
294 return x.relpath
295 result.sort(key=_getpath)
296 return result
297
Takeshi Kanemoto1f056442016-01-26 14:11:35 +0900298 def FindProjects(self, args, inverse=False):
Zhiguang Lia8864fb2013-03-15 10:32:10 +0800299 result = []
David Pursehouse84c4d3c2013-04-30 10:57:37 +0900300 patterns = [re.compile(r'%s' % a, re.IGNORECASE) for a in args]
Zhiguang Lia8864fb2013-03-15 10:32:10 +0800301 for project in self.GetProjects(''):
David Pursehouse84c4d3c2013-04-30 10:57:37 +0900302 for pattern in patterns:
Takeshi Kanemoto1f056442016-01-26 14:11:35 +0900303 match = pattern.search(project.name) or pattern.search(project.relpath)
304 if not inverse and match:
Zhiguang Lia8864fb2013-03-15 10:32:10 +0800305 result.append(project)
306 break
Takeshi Kanemoto1f056442016-01-26 14:11:35 +0900307 if inverse and match:
308 break
309 else:
310 if inverse:
311 result.append(project)
Zhiguang Lia8864fb2013-03-15 10:32:10 +0800312 result.sort(key=lambda project: project.relpath)
313 return result
314
Mark E. Hamilton8ccfa742016-02-10 10:44:30 -0700315
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700316class InteractiveCommand(Command):
317 """Command which requires user interaction on the tty and
318 must not run within a pager, even if the user asks to.
319 """
David Pursehouse819827a2020-02-12 15:20:19 +0900320
Mark E. Hamilton8ccfa742016-02-10 10:44:30 -0700321 def WantPager(self, _opt):
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700322 return False
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700323
Mark E. Hamilton8ccfa742016-02-10 10:44:30 -0700324
The Android Open Source Projectcf31fe92008-10-21 07:00:00 -0700325class PagedCommand(Command):
326 """Command which defaults to output in a pager, as its
327 display tends to be larger than one screen full.
328 """
David Pursehouse819827a2020-02-12 15:20:19 +0900329
Mark E. Hamilton8ccfa742016-02-10 10:44:30 -0700330 def WantPager(self, _opt):
Shawn O. Pearcedb45da12009-04-18 13:49:13 -0700331 return True
Shawn O. Pearcec95583b2009-03-03 17:47:06 -0800332
Mark E. Hamilton8ccfa742016-02-10 10:44:30 -0700333
Shawn O. Pearcec95583b2009-03-03 17:47:06 -0800334class MirrorSafeCommand(object):
335 """Command permits itself to run within a mirror,
336 and does not require a working directory.
337 """
Dan Willemsen9ff2ece2015-08-31 15:45:06 -0700338
Mark E. Hamilton8ccfa742016-02-10 10:44:30 -0700339
Dan Willemsen79360642015-08-31 15:45:06 -0700340class GitcAvailableCommand(object):
Dan Willemsen9ff2ece2015-08-31 15:45:06 -0700341 """Command that requires GITC to be available, but does
342 not require the local client to be a GITC client.
343 """
Dan Willemsen79360642015-08-31 15:45:06 -0700344
Mark E. Hamilton8ccfa742016-02-10 10:44:30 -0700345
Dan Willemsen79360642015-08-31 15:45:06 -0700346class GitcClientCommand(object):
347 """Command that requires the local client to be a GITC
348 client.
349 """