command.py 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  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 \
  89. and path != oldpath \
  90. and 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
  126. project.MatchesGroups(groups)):
  127. result.append(project)
  128. else:
  129. self._ResetPathToProjectMap(all_projects_list)
  130. for arg in args:
  131. projects = manifest.GetProjectsWithName(arg)
  132. if not projects:
  133. path = os.path.abspath(arg).replace('\\', '/')
  134. project = self._GetProjectByPath(manifest, path)
  135. # If it's not a derived project, update path->project mapping and
  136. # search again, as arg might actually point to a derived subproject.
  137. if (project and not project.Derived and
  138. (submodules_ok or project.sync_s)):
  139. search_again = False
  140. for subproject in project.GetDerivedSubprojects():
  141. self._UpdatePathToProjectMap(subproject)
  142. search_again = True
  143. if search_again:
  144. project = self._GetProjectByPath(manifest, path) or project
  145. if project:
  146. projects = [project]
  147. if not projects:
  148. raise NoSuchProjectError(arg)
  149. for project in projects:
  150. if not missing_ok and not project.Exists:
  151. raise NoSuchProjectError(arg)
  152. if not project.MatchesGroups(groups):
  153. raise InvalidProjectGroupsError(arg)
  154. result.extend(projects)
  155. def _getpath(x):
  156. return x.relpath
  157. result.sort(key=_getpath)
  158. return result
  159. def FindProjects(self, args):
  160. result = []
  161. patterns = [re.compile(r'%s' % a, re.IGNORECASE) for a in args]
  162. for project in self.GetProjects(''):
  163. for pattern in patterns:
  164. if pattern.search(project.name) or pattern.search(project.relpath):
  165. result.append(project)
  166. break
  167. result.sort(key=lambda project: project.relpath)
  168. return result
  169. # pylint: disable=W0223
  170. # Pylint warns that the `InteractiveCommand` and `PagedCommand` classes do not
  171. # override method `Execute` which is abstract in `Command`. Since that method
  172. # is always implemented in classes derived from `InteractiveCommand` and
  173. # `PagedCommand`, this warning can be suppressed.
  174. class InteractiveCommand(Command):
  175. """Command which requires user interaction on the tty and
  176. must not run within a pager, even if the user asks to.
  177. """
  178. def WantPager(self, opt):
  179. return False
  180. class PagedCommand(Command):
  181. """Command which defaults to output in a pager, as its
  182. display tends to be larger than one screen full.
  183. """
  184. def WantPager(self, opt):
  185. return True
  186. # pylint: enable=W0223
  187. class MirrorSafeCommand(object):
  188. """Command permits itself to run within a mirror,
  189. and does not require a working directory.
  190. """
  191. class RequiresGitcCommand(object):
  192. """Command that requires GITC to be available, but does
  193. not require the local client to be a GITC client.
  194. """