command.py 8.1 KB

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