command.py 7.6 KB

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