blob: d0c510f1c83e81653cd2ed6fe08ab69c4f892c21 [file] [log] [blame]
Brian Harring7fcc02e2012-08-05 04:10:57 -07001# Copyright (c) 2010 The Chromium OS Authors. All rights reserved.
2# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4
5"""This module allows adding and deleting of projects to the local manifest."""
6
Brian Harringb0043ab2012-08-05 04:09:56 -07007import logging
8import platform
Brian Harring7fcc02e2012-08-05 04:10:57 -07009import optparse
10import os
Brian Harringb0043ab2012-08-05 04:09:56 -070011import sys
Brian Harring7fcc02e2012-08-05 04:10:57 -070012import xml.etree.ElementTree as ElementTree
Mike Frysinger750c5f52014-09-16 16:16:57 -040013
Brian Harringb0043ab2012-08-05 04:09:56 -070014from chromite.lib import cros_build_lib
David James97d95872012-11-16 15:09:56 -080015from chromite.lib import git
Brian Harring7fcc02e2012-08-05 04:10:57 -070016
17
Brian Harringb0043ab2012-08-05 04:09:56 -070018class Manifest(object):
Brian Harring7fcc02e2012-08-05 04:10:57 -070019 """Class which provides an abstraction for manipulating the local manifest."""
20
Brian Harringb0043ab2012-08-05 04:09:56 -070021 @classmethod
22 def FromPath(cls, path, empty_if_missing=False):
23 if os.path.isfile(path):
24 with open(path) as f:
25 return cls(f.read())
26 elif empty_if_missing:
27 cros_build_lib.Die('Manifest file, %r, not found' % path)
28 return cls()
29
Brian Harring7fcc02e2012-08-05 04:10:57 -070030 def __init__(self, text=None):
31 self._text = text or '<manifest>\n</manifest>'
Brian Harringb0043ab2012-08-05 04:09:56 -070032 self.nodes = ElementTree.fromstring(self._text)
Brian Harring7fcc02e2012-08-05 04:10:57 -070033
Rhyland Kleinb1d1f382012-08-23 11:53:45 -040034 def AddNonWorkonProject(self, name, path, remote=None, revision=None):
Brian Harringb0043ab2012-08-05 04:09:56 -070035 """Add a new nonworkon project element to the manifest tree."""
36 element = ElementTree.Element('project', name=name, path=path,
Rhyland Kleindd8ebbb2012-09-06 11:51:30 -040037 remote=remote)
Brian Harringb0043ab2012-08-05 04:09:56 -070038 element.attrib['workon'] = 'False'
Rhyland Kleindd8ebbb2012-09-06 11:51:30 -040039 if revision is not None:
40 element.attrib['revision'] = revision
Brian Harringb0043ab2012-08-05 04:09:56 -070041 self.nodes.append(element)
42 return element
Brian Harring7fcc02e2012-08-05 04:10:57 -070043
Brian Harringb0043ab2012-08-05 04:09:56 -070044 def GetProject(self, name, path=None):
Brian Harring7fcc02e2012-08-05 04:10:57 -070045 """Accessor method for getting a project node from the manifest tree.
46
47 Returns:
48 project element node from ElementTree, otherwise, None
49 """
Brian Harringb0043ab2012-08-05 04:09:56 -070050 if path is None:
51 # Use a unique value that can't ever match.
52 path = object()
53 for project in self.nodes.findall('project'):
54 if project.attrib['name'] == name or project.attrib['path'] == path:
Brian Harring7fcc02e2012-08-05 04:10:57 -070055 return project
56 return None
57
58 def ToString(self):
Brian Harringb0043ab2012-08-05 04:09:56 -070059 # Reset the tail for each node, then just do a hacky replace.
60 project = None
61 for project in self.nodes.findall('project'):
62 project.tail = '\n '
63 if project is not None:
64 # Tweak the last project to not have the trailing space.
65 project.tail = '\n'
66 # Fix manifest tag text and tail.
67 self.nodes.text = '\n '
68 self.nodes.tail = '\n'
69 return ElementTree.tostring(self.nodes)
70
71 def GetProjects(self):
72 return list(self.nodes.findall('project'))
73
74
Mike Frysingerc15efa52013-12-12 01:13:56 -050075def _AddProjectsToManifestGroups(options, *args):
Brian Harringb0043ab2012-08-05 04:09:56 -070076 """Enable the given manifest groups for the configured repository."""
77
Mike Frysingerc15efa52013-12-12 01:13:56 -050078 groups_to_enable = ['name:%s' % x for x in args]
Brian Harringb0043ab2012-08-05 04:09:56 -070079
80 git_config = options.git_config
81
David James67d73252013-09-19 17:33:12 -070082 cmd = ['config', '-f', git_config, '--get', 'manifest.groups']
83 enabled_groups = git.RunGit('.', cmd, error_code_ok=True).output.split(',')
Brian Harringb0043ab2012-08-05 04:09:56 -070084
85 # Note that ordering actually matters, thus why the following code
86 # is written this way.
87 # Per repo behaviour, enforce an appropriate platform group if
88 # we're converting from a default manifest group to a limited one.
89 # Finally, note we reprocess the existing groups; this is to allow
90 # us to cleanup any user screwups, or our own screwups.
91 requested_groups = (
92 ['minilayout', 'platform-%s' % (platform.system().lower(),)] +
93 enabled_groups + list(groups_to_enable))
94
95 processed_groups = set()
96 finalized_groups = []
97
98 for group in requested_groups:
99 if group not in processed_groups:
100 finalized_groups.append(group)
101 processed_groups.add(group)
102
David James67d73252013-09-19 17:33:12 -0700103 cmd = ['config', '-f', git_config, 'manifest.groups',
104 ','.join(finalized_groups)]
105 git.RunGit('.', cmd)
Brian Harringb0043ab2012-08-05 04:09:56 -0700106
107
108def _UpgradeMinilayout(options):
109 """Convert a repo checkout away from minilayout.xml to default.xml."""
110
111 full_tree = Manifest.FromPath(options.default_manifest_path)
112 local_manifest_exists = os.path.exists(options.local_manifest_path)
113
114 new_groups = []
115 if local_manifest_exists:
116 local_tree = Manifest.FromPath(options.local_manifest_path)
117 # Identify which projects need to be transferred across.
118 projects = local_tree.GetProjects()
119 new_groups = [x.attrib['name'] for x in projects]
120 allowed = set(x.attrib['name'] for x in full_tree.GetProjects())
121 transferred = [x for x in projects if x.attrib['name'] in allowed]
122 for project in transferred:
123 # Mangle local_manifest object, removing those projects;
124 # note we'll still be adding those projects to the default groups,
125 # including those that didn't intersect the main manifest.
126 local_tree.nodes.remove(project)
127
128 _AddProjectsToManifestGroups(options, *new_groups)
129
130 if local_manifest_exists:
131 # Rewrite the local_manifest now; if there is no settings left in
132 # the local_manifest, wipe it.
133 if local_tree.nodes.getchildren():
134 with open(options.local_manifest_path, 'w') as f:
135 f.write(local_tree.ToString())
136 else:
137 os.unlink(options.local_manifest_path)
138
139 # Finally, move the symlink.
140 os.unlink(options.manifest_sym_path)
141 os.symlink('manifests/default.xml', options.manifest_sym_path)
142 logging.info("Converted the checkout to manifest groups based minilayout.")
Brian Harring7fcc02e2012-08-05 04:10:57 -0700143
144
145def main(argv):
Brian Harringb0043ab2012-08-05 04:09:56 -0700146 parser = optparse.OptionParser(usage='usage: %prog add [options] <name> '
147 '<--workon | <path> --remote <remote> >')
Brian Harring7fcc02e2012-08-05 04:10:57 -0700148 parser.add_option('-w', '--workon', action='store_true', dest='workon',
149 default=False, help='Is this a workon package?')
Brian Harring7fcc02e2012-08-05 04:10:57 -0700150 parser.add_option('-r', '--remote', dest='remote',
151 default=None)
Rhyland Kleinb1d1f382012-08-23 11:53:45 -0400152 parser.add_option('-v', '--revision', dest='revision',
153 default=None,
154 help="Use to override the manifest defined default "
155 "revision used for a given project.")
Brian Harringb0043ab2012-08-05 04:09:56 -0700156 parser.add_option('--upgrade-minilayout', default=False, action='store_true',
157 help="Upgrade a minilayout checkout into a full.xml "
158 "checkout utilizing manifest groups.")
159 (options, args) = parser.parse_args(argv)
Brian Harring7fcc02e2012-08-05 04:10:57 -0700160
Ryan Cui0b1b94b2012-12-21 12:09:57 -0800161 repo_dir = git.FindRepoDir(os.getcwd())
Brian Harringb0043ab2012-08-05 04:09:56 -0700162 if not repo_dir:
163 parser.error("This script must be invoked from within a repository "
164 "checkout.")
Brian Harring7fcc02e2012-08-05 04:10:57 -0700165
Brian Harringb0043ab2012-08-05 04:09:56 -0700166 options.git_config = os.path.join(repo_dir, 'manifests.git', 'config')
167 options.repo_dir = repo_dir
168 options.local_manifest_path = os.path.join(repo_dir, 'local_manifest.xml')
169 # This constant is used only when we're doing an upgrade away from
170 # minilayout.xml to default.xml.
171 options.default_manifest_path = os.path.join(repo_dir, 'manifests',
172 'default.xml')
173 options.manifest_sym_path = os.path.join(repo_dir, 'manifest.xml')
174
175 active_manifest = os.path.basename(os.readlink(options.manifest_sym_path))
176 upgrade_required = active_manifest == 'minilayout.xml'
177
178 if options.upgrade_minilayout:
179 if args:
180 parser.error("--upgrade-minilayout takes no arguments.")
181 if not upgrade_required:
182 print "This repository checkout isn't using minilayout.xml; nothing to do"
183 else:
184 _UpgradeMinilayout(options)
185 return 0
186 elif upgrade_required:
187 logging.warn(
188 "Your repository checkout is using the old minilayout.xml workflow; "
189 "auto-upgrading it.")
190 cros_build_lib.RunCommand(
191 [sys.argv[0], '--upgrade-minilayout'], cwd=os.getcwd(),
192 print_cmd=False)
193
194 if not args:
195 parser.error("No command specified.")
196 elif args[0] != 'add':
197 parser.error("Only supported subcommand is add right now.")
198 elif options.workon:
199 if len(args) != 2:
200 parser.error(
201 "Argument count is wrong for --workon; must be add <project>")
202 name, path = args[1], None
Brian Harring7fcc02e2012-08-05 04:10:57 -0700203 else:
Brian Harringb0043ab2012-08-05 04:09:56 -0700204 if options.remote is None:
205 parser.error('Adding non-workon projects requires a remote.')
206 elif len(args) != 3:
207 parser.error(
208 "Argument count is wrong for non-workon mode; "
209 "must be add <project> <path> --remote <remote-arg>")
210 name, path = args[1:]
Brian Harring7fcc02e2012-08-05 04:10:57 -0700211
Rhyland Kleinb1d1f382012-08-23 11:53:45 -0400212 revision = options.revision
213 if revision is not None:
David James97d95872012-11-16 15:09:56 -0800214 if (not git.IsRefsTags(revision) and
215 not git.IsSHA1(revision)):
216 revision = git.StripRefsHeads(revision, False)
Rhyland Kleinb1d1f382012-08-23 11:53:45 -0400217
Brian Harringb0043ab2012-08-05 04:09:56 -0700218 main_manifest = Manifest.FromPath(options.manifest_sym_path,
219 empty_if_missing=False)
220 local_manifest = Manifest.FromPath(options.local_manifest_path)
Brian Harring7fcc02e2012-08-05 04:10:57 -0700221
Brian Harringb0043ab2012-08-05 04:09:56 -0700222 main_element = main_manifest.GetProject(name, path=path)
Brian Harring7fcc02e2012-08-05 04:10:57 -0700223
Brian Harringb0043ab2012-08-05 04:09:56 -0700224 if options.workon:
225 if main_element is None:
226 parser.error('No project named %r in the default manifest.' % name)
227 _AddProjectsToManifestGroups(options, main_element.attrib['name'])
228
Rhyland Kleinf33f6222012-10-25 12:15:42 -0400229 elif main_element is not None:
Rhyland Kleine5faad52012-10-31 11:58:19 -0400230 if options.remote is not None:
231 # Likely this project wasn't meant to be remote, so workon main element
232 print "Project already exists in manifest. Using that as workon project."
233 _AddProjectsToManifestGroups(options, main_element.attrib['name'])
234 else:
235 # Conflict will occur; complain.
236 parser.error("Requested project name=%r path=%r will conflict with "
237 "your current manifest %s" % (name, path, active_manifest))
Brian Harringb0043ab2012-08-05 04:09:56 -0700238
239 elif local_manifest.GetProject(name, path=path) is not None:
240 parser.error("Requested project name=%r path=%r conflicts with "
241 "your local_manifest.xml" % (name, path))
242
243 else:
Rhyland Kleinb1d1f382012-08-23 11:53:45 -0400244 element = local_manifest.AddNonWorkonProject(name=name, path=path,
245 remote=options.remote,
246 revision=revision)
Brian Harringb0043ab2012-08-05 04:09:56 -0700247 _AddProjectsToManifestGroups(options, element.attrib['name'])
248
249 with open(options.local_manifest_path, 'w') as f:
250 f.write(local_manifest.ToString())
251 return 0