command.py 8.1 KB

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