command.py 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  1. #
  2. # Copyright (C) 2008 The Android Open Source Project
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. import os
  16. import optparse
  17. import platform
  18. import re
  19. import sys
  20. from error import NoSuchProjectError
  21. from error import InvalidProjectGroupsError
  22. class Command(object):
  23. """Base class for any command line action in repo.
  24. """
  25. common = False
  26. manifest = None
  27. _optparse = None
  28. def WantPager(self, _opt):
  29. return False
  30. def ReadEnvironmentOptions(self, opts):
  31. """ Set options from environment variables. """
  32. env_options = self._RegisteredEnvironmentOptions()
  33. for env_key, opt_key in env_options.items():
  34. # Get the user-set option value if any
  35. opt_value = getattr(opts, opt_key)
  36. # If the value is set, it means the user has passed it as a command
  37. # line option, and we should use that. Otherwise we can try to set it
  38. # with the value from the corresponding environment variable.
  39. if opt_value is not None:
  40. continue
  41. env_value = os.environ.get(env_key)
  42. if env_value is not None:
  43. setattr(opts, opt_key, env_value)
  44. return opts
  45. @property
  46. def OptionParser(self):
  47. if self._optparse is None:
  48. try:
  49. me = 'repo %s' % self.NAME
  50. usage = self.helpUsage.strip().replace('%prog', me)
  51. except AttributeError:
  52. usage = 'repo %s' % self.NAME
  53. self._optparse = optparse.OptionParser(usage=usage)
  54. self._Options(self._optparse)
  55. return self._optparse
  56. def _Options(self, p):
  57. """Initialize the option parser.
  58. """
  59. def _RegisteredEnvironmentOptions(self):
  60. """Get options that can be set from environment variables.
  61. Return a dictionary mapping environment variable name
  62. to option key name that it can override.
  63. Example: {'REPO_MY_OPTION': 'my_option'}
  64. Will allow the option with key value 'my_option' to be set
  65. from the value in the environment variable named 'REPO_MY_OPTION'.
  66. Note: This does not work properly for options that are explicitly
  67. set to None by the user, or options that are defined with a
  68. default value other than None.
  69. """
  70. return {}
  71. def Usage(self):
  72. """Display usage and terminate.
  73. """
  74. self.OptionParser.print_usage()
  75. sys.exit(1)
  76. def Execute(self, opt, args):
  77. """Perform the action, after option parsing is complete.
  78. """
  79. raise NotImplementedError
  80. def _ResetPathToProjectMap(self, projects):
  81. self._by_path = dict((p.worktree, p) for p in projects)
  82. def _UpdatePathToProjectMap(self, project):
  83. self._by_path[project.worktree] = project
  84. def _GetProjectByPath(self, manifest, path):
  85. project = None
  86. if os.path.exists(path):
  87. oldpath = None
  88. while path and \
  89. path != oldpath and \
  90. path != manifest.topdir:
  91. try:
  92. project = self._by_path[path]
  93. break
  94. except KeyError:
  95. oldpath = path
  96. path = os.path.dirname(path)
  97. else:
  98. try:
  99. project = self._by_path[path]
  100. except KeyError:
  101. pass
  102. return project
  103. def GetProjects(self, args, manifest=None, groups='', missing_ok=False,
  104. submodules_ok=False):
  105. """A list of projects that match the arguments.
  106. """
  107. if not manifest:
  108. manifest = self.manifest
  109. all_projects_list = manifest.projects
  110. result = []
  111. mp = manifest.manifestProject
  112. if not groups:
  113. groups = mp.config.GetString('manifest.groups')
  114. if not groups:
  115. groups = 'default,platform-' + platform.system().lower()
  116. groups = [x for x in re.split(r'[,\s]+', groups) if x]
  117. if not args:
  118. derived_projects = {}
  119. for project in all_projects_list:
  120. if submodules_ok or project.sync_s:
  121. derived_projects.update((p.name, p)
  122. for p in project.GetDerivedSubprojects())
  123. all_projects_list.extend(derived_projects.values())
  124. for project in all_projects_list:
  125. if (missing_ok or project.Exists) and project.MatchesGroups(groups):
  126. result.append(project)
  127. else:
  128. self._ResetPathToProjectMap(all_projects_list)
  129. for arg in args:
  130. projects = manifest.GetProjectsWithName(arg)
  131. if not projects:
  132. path = os.path.abspath(arg).replace('\\', '/')
  133. project = self._GetProjectByPath(manifest, path)
  134. # If it's not a derived project, update path->project mapping and
  135. # search again, as arg might actually point to a derived subproject.
  136. if (project and not project.Derived and (submodules_ok or
  137. project.sync_s)):
  138. search_again = False
  139. for subproject in project.GetDerivedSubprojects():
  140. self._UpdatePathToProjectMap(subproject)
  141. search_again = True
  142. if search_again:
  143. project = self._GetProjectByPath(manifest, path) or project
  144. if project:
  145. projects = [project]
  146. if not projects:
  147. raise NoSuchProjectError(arg)
  148. for project in projects:
  149. if not missing_ok and not project.Exists:
  150. raise NoSuchProjectError(arg)
  151. if not project.MatchesGroups(groups):
  152. raise InvalidProjectGroupsError(arg)
  153. result.extend(projects)
  154. def _getpath(x):
  155. return x.relpath
  156. result.sort(key=_getpath)
  157. return result
  158. def FindProjects(self, args):
  159. result = []
  160. patterns = [re.compile(r'%s' % a, re.IGNORECASE) for a in args]
  161. for project in self.GetProjects(''):
  162. for pattern in patterns:
  163. if pattern.search(project.name) or pattern.search(project.relpath):
  164. result.append(project)
  165. break
  166. result.sort(key=lambda project: project.relpath)
  167. return result
  168. # pylint: disable=W0223
  169. # Pylint warns that the `InteractiveCommand` and `PagedCommand` classes do not
  170. # override method `Execute` which is abstract in `Command`. Since that method
  171. # is always implemented in classes derived from `InteractiveCommand` and
  172. # `PagedCommand`, this warning can be suppressed.
  173. class InteractiveCommand(Command):
  174. """Command which requires user interaction on the tty and
  175. must not run within a pager, even if the user asks to.
  176. """
  177. def WantPager(self, _opt):
  178. return False
  179. class PagedCommand(Command):
  180. """Command which defaults to output in a pager, as its
  181. display tends to be larger than one screen full.
  182. """
  183. def WantPager(self, _opt):
  184. return True
  185. # pylint: enable=W0223
  186. class MirrorSafeCommand(object):
  187. """Command permits itself to run within a mirror,
  188. and does not require a working directory.
  189. """
  190. class GitcAvailableCommand(object):
  191. """Command that requires GITC to be available, but does
  192. not require the local client to be a GITC client.
  193. """
  194. class GitcClientCommand(object):
  195. """Command that requires the local client to be a GITC
  196. client.
  197. """