## Copyright (C) 2008 The Android Open Source Project## Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.import osimport optparseimport platformimport reimport sysfrom error import NoSuchProjectErrorfrom error import InvalidProjectGroupsErrorclass Command(object):"""Base class for any command line action in repo."""common = Falsemanifest = None_optparse = Nonedef WantPager(self, opt):return Falsedef ReadEnvironmentOptions(self, opts):""" Set options from environment variables. """env_options = self._RegisteredEnvironmentOptions()for env_key, opt_key in env_options.items():# Get the user-set option value if anyopt_value = getattr(opts, opt_key)# If the value is set, it means the user has passed it as a command# line option, and we should use that. Otherwise we can try to set it# with the value from the corresponding environment variable.if opt_value is not None:continueenv_value = os.environ.get(env_key)if env_value is not None:setattr(opts, opt_key, env_value)return opts@propertydef OptionParser(self):if self._optparse is None:try:me = 'repo %s' % self.NAMEusage = self.helpUsage.strip().replace('%prog', me)except AttributeError:usage = 'repo %s' % self.NAMEself._optparse = optparse.OptionParser(usage = usage)self._Options(self._optparse)return self._optparsedef _Options(self, p):"""Initialize the option parser."""def _RegisteredEnvironmentOptions(self):"""Get options that can be set from environment variables.Return a dictionary mapping environment variable nameto option key name that it can override.Example: {'REPO_MY_OPTION': 'my_option'}Will allow the option with key value 'my_option' to be setfrom the value in the environment variable named 'REPO_MY_OPTION'.Note: This does not work properly for options that are explicitlyset to None by the user, or options that are defined with adefault value other than None."""return {}def Usage(self):"""Display usage and terminate."""self.OptionParser.print_usage()sys.exit(1)def Execute(self, opt, args):"""Perform the action, after option parsing is complete."""raise NotImplementedErrordef _ResetPathToProjectMap(self, projects):self._by_path = dict((p.worktree, p) for p in projects)def _UpdatePathToProjectMap(self, project):self._by_path[project.worktree] = projectdef _GetProjectByPath(self, path):project = Noneif os.path.exists(path):oldpath = Nonewhile path \and path != oldpath \and path != self.manifest.topdir:try:project = self._by_path[path]breakexcept KeyError:oldpath = pathpath = os.path.dirname(path)else:try:project = self._by_path[path]except KeyError:passreturn projectdef GetProjects(self, args, missing_ok=False, submodules_ok=False):"""A list of projects that match the arguments."""all_projects_list = self.manifest.projectsresult = []mp = self.manifest.manifestProjectgroups = mp.config.GetString('manifest.groups')if not groups:groups = 'default,platform-' + platform.system().lower()groups = [x for x in re.split(r'[,\s]+', groups) if x]if not args:derived_projects = {}for project in all_projects_list:if submodules_ok or project.sync_s:derived_projects.update((p.name, p)for p in project.GetDerivedSubprojects())all_projects_list.extend(derived_projects.values())for project in all_projects_list:if ((missing_ok or project.Exists) andproject.MatchesGroups(groups)):result.append(project)else:self._ResetPathToProjectMap(all_projects_list)for arg in args:projects = self.manifest.GetProjectsWithName(arg)if not projects:path = os.path.abspath(arg).replace('\\', '/')project = self._GetProjectByPath(path)# If it's not a derived project, update path->project mapping and# search again, as arg might actually point to a derived subproject.if (project and not project.Derived and(submodules_ok or project.sync_s)):search_again = Falsefor subproject in project.GetDerivedSubprojects():self._UpdatePathToProjectMap(subproject)search_again = Trueif search_again:project = self._GetProjectByPath(path) or projectif project:projects = [project]if not projects:raise NoSuchProjectError(arg)for project in projects:if not missing_ok and not project.Exists:raise NoSuchProjectError(arg)if not project.MatchesGroups(groups):raise InvalidProjectGroupsError(arg)result.extend(projects)def _getpath(x):return x.relpathresult.sort(key=_getpath)return resultdef FindProjects(self, args):result = []patterns = [re.compile(r'%s' % a, re.IGNORECASE) for a in args]for project in self.GetProjects(''):for pattern in patterns:if pattern.search(project.name) or pattern.search(project.relpath):result.append(project)breakresult.sort(key=lambda project: project.relpath)return result# pylint: disable=W0223# Pylint warns that the `InteractiveCommand` and `PagedCommand` classes do not# override method `Execute` which is abstract in `Command`. Since that method# is always implemented in classes derived from `InteractiveCommand` and# `PagedCommand`, this warning can be suppressed.class InteractiveCommand(Command):"""Command which requires user interaction on the tty andmust not run within a pager, even if the user asks to."""def WantPager(self, opt):return Falseclass PagedCommand(Command):"""Command which defaults to output in a pager, as itsdisplay tends to be larger than one screen full."""def WantPager(self, opt):return True# pylint: enable=W0223class MirrorSafeCommand(object):"""Command permits itself to run within a mirror,and does not require a working directory."""
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。