blob: f5aac06955460cfda1dc1c90119f30f25e0d04f4 [file] [log] [blame]
Koushik Dutta780fb5f2011-11-26 18:51:42 -08001#!/usr/bin/env python
Diogo Ferreira0d109172012-03-18 21:18:29 +00002# Copyright (C) 2012-2013, The CyanogenMod 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
Koushik Dutta780fb5f2011-11-26 18:51:42 -080016import os
17import sys
18import urllib2
19import json
Diogo Ferreira0d109172012-03-18 21:18:29 +000020import re
21import netrc, base64
Koushik Dutta780fb5f2011-11-26 18:51:42 -080022from xml.etree import ElementTree
23
24product = sys.argv[1];
Diogo Ferreira0d109172012-03-18 21:18:29 +000025
26if len(sys.argv) > 2:
27 depsonly = sys.argv[2]
28else:
29 depsonly = None
30
31try:
32 device = product[product.index("_") + 1:]
33except:
34 device = product
35
36if not depsonly:
37 print "Device %s not found. Attempting to retrieve device repository from CyanogenMod Github (http://github.com/CyanogenMod)." % device
Koushik Dutta780fb5f2011-11-26 18:51:42 -080038
39repositories = []
40
Diogo Ferreira0d109172012-03-18 21:18:29 +000041try:
42 authtuple = netrc.netrc().authenticators("api.github.com")
43
44 if authtuple:
45 githubauth = base64.encodestring('%s:%s' % (authtuple[0], authtuple[2])).replace('\n', '')
46 else:
47 githubauth = None
48except:
49 githubauth = None
50
51def add_auth(githubreq):
52 if githubauth:
53 githubreq.add_header("Authorization","Basic %s" % githubauth)
54
Koushik Dutta780fb5f2011-11-26 18:51:42 -080055page = 1
Diogo Ferreira0d109172012-03-18 21:18:29 +000056while not depsonly:
57 githubreq = urllib2.Request("https://api.github.com/users/CyanogenMod/repos?per_page=200&page=%d" % page)
58 add_auth(githubreq)
59 result = json.loads(urllib2.urlopen(githubreq).read())
60 if len(result) == 0:
Koushik Dutta780fb5f2011-11-26 18:51:42 -080061 break
Diogo Ferreira0d109172012-03-18 21:18:29 +000062 for res in result:
63 repositories.append(res)
Koushik Dutta780fb5f2011-11-26 18:51:42 -080064 page = page + 1
65
Diogo Ferreira0d109172012-03-18 21:18:29 +000066local_manifests = r'.repo/local_manifests'
67if not os.path.exists(local_manifests): os.makedirs(local_manifests)
Koushik Dutta780fb5f2011-11-26 18:51:42 -080068
Diogo Ferreira0d109172012-03-18 21:18:29 +000069def exists_in_tree(lm, repository):
70 for child in lm.getchildren():
71 if child.attrib['name'].endswith(repository):
72 return True
73 return False
74
75# in-place prettyprint formatter
76def indent(elem, level=0):
77 i = "\n" + level*" "
78 if len(elem):
79 if not elem.text or not elem.text.strip():
80 elem.text = i + " "
81 if not elem.tail or not elem.tail.strip():
82 elem.tail = i
83 for elem in elem:
84 indent(elem, level+1)
85 if not elem.tail or not elem.tail.strip():
86 elem.tail = i
87 else:
88 if level and (not elem.tail or not elem.tail.strip()):
89 elem.tail = i
90
91def get_default_revision():
92 m = ElementTree.parse(".repo/manifest.xml")
93 d = m.findall('default')[0]
94 r = d.get('revision')
95 return r.replace('refs/heads/', '').replace('refs/tags/', '')
96
97def get_from_manifest(devicename):
98 try:
99 lm = ElementTree.parse(".repo/local_manifests/roomservice.xml")
100 lm = lm.getroot()
101 except:
102 lm = ElementTree.Element("manifest")
103
104 for localpath in lm.findall("project"):
105 if re.search("android_device_.*_%s$" % device, localpath.get("name")):
106 return localpath.get("path")
107
108 # Devices originally from AOSP are in the main manifest...
109 try:
110 mm = ElementTree.parse(".repo/manifest.xml")
111 mm = mm.getroot()
112 except:
113 mm = ElementTree.Element("manifest")
114
115 for localpath in mm.findall("project"):
116 if re.search("android_device_.*_%s$" % device, localpath.get("name")):
117 return localpath.get("path")
118
119 return None
120
121def is_in_manifest(projectname):
122 try:
123 lm = ElementTree.parse(".repo/local_manifests/roomservice.xml")
124 lm = lm.getroot()
125 except:
126 lm = ElementTree.Element("manifest")
127
128 for localpath in lm.findall("project"):
129 if localpath.get("name") == projectname:
130 return 1
131
132 ## Search in main manifest, too
133 try:
134 lm = ElementTree.parse(".repo/manifest.xml")
135 lm = lm.getroot()
136 except:
137 lm = ElementTree.Element("manifest")
138
139 for localpath in lm.findall("project"):
140 if localpath.get("name") == projectname:
141 return 1
142
143 return None
144
145def add_to_manifest(repositories, fallback_branch = None):
146 try:
147 lm = ElementTree.parse(".repo/local_manifests/roomservice.xml")
148 lm = lm.getroot()
149 except:
150 lm = ElementTree.Element("manifest")
151
152 for repository in repositories:
153 repo_name = repository['repository']
154 repo_target = repository['target_path']
155 if exists_in_tree(lm, repo_name):
156 print 'CyanogenMod/%s already exists' % (repo_name)
157 continue
158
159 print 'Adding dependency: CyanogenMod/%s -> %s' % (repo_name, repo_target)
160 project = ElementTree.Element("project", attrib = { "path": repo_target,
161 "remote": "github", "name": "CyanogenMod/%s" % repo_name })
162
163 if 'branch' in repository:
164 project.set('revision',repository['branch'])
165 elif fallback_branch:
166 print "Using fallback branch %s for %s" % (fallback_branch, repo_name)
167 project.set('revision', fallback_branch)
168 else:
169 print "Using default branch for %s" % repo_name
170
Koushik Dutta780fb5f2011-11-26 18:51:42 -0800171 lm.append(project)
Koushik Dutta780fb5f2011-11-26 18:51:42 -0800172
Diogo Ferreira0d109172012-03-18 21:18:29 +0000173 indent(lm, 0)
174 raw_xml = ElementTree.tostring(lm)
175 raw_xml = '<?xml version="1.0" encoding="UTF-8"?>\n' + raw_xml
Koushik Dutta780fb5f2011-11-26 18:51:42 -0800176
Diogo Ferreira0d109172012-03-18 21:18:29 +0000177 f = open('.repo/local_manifests/roomservice.xml', 'w')
178 f.write(raw_xml)
179 f.close()
180
181def fetch_dependencies(repo_path, fallback_branch = None):
182 print 'Looking for dependencies'
183 dependencies_path = repo_path + '/cm.dependencies'
184 syncable_repos = []
185
186 if os.path.exists(dependencies_path):
187 dependencies_file = open(dependencies_path, 'r')
188 dependencies = json.loads(dependencies_file.read())
189 fetch_list = []
190
191 for dependency in dependencies:
192 if not is_in_manifest("CyanogenMod/%s" % dependency['repository']):
193 fetch_list.append(dependency)
194 syncable_repos.append(dependency['target_path'])
195
196 dependencies_file.close()
197
198 if len(fetch_list) > 0:
199 print 'Adding dependencies to manifest'
200 add_to_manifest(fetch_list, fallback_branch)
201 else:
202 print 'Dependencies file not found, bailing out.'
203
204 if len(syncable_repos) > 0:
205 print 'Syncing dependencies'
206 os.system('repo sync %s' % ' '.join(syncable_repos))
207
208 for deprepo in syncable_repos:
209 fetch_dependencies(deprepo)
210
211def has_branch(branches, revision):
212 return revision in [branch['name'] for branch in branches]
213
214if depsonly:
215 repo_path = get_from_manifest(device)
216 if repo_path:
217 fetch_dependencies(repo_path)
218 else:
219 print "Trying dependencies-only mode on a non-existing device tree?"
220
221 sys.exit()
222
223else:
224 for repository in repositories:
225 repo_name = repository['name']
226 if repo_name.startswith("android_device_") and repo_name.endswith("_" + device):
227 print "Found repository: %s" % repository['name']
228
229 manufacturer = repo_name.replace("android_device_", "").replace("_" + device, "")
230
231 default_revision = get_default_revision()
232 print "Default revision: %s" % default_revision
233 print "Checking branch info"
234 githubreq = urllib2.Request(repository['branches_url'].replace('{/branch}', ''))
235 add_auth(githubreq)
236 result = json.loads(urllib2.urlopen(githubreq).read())
237
238 ## Try tags, too, since that's what releases use
239 if not has_branch(result, default_revision):
240 githubreq = urllib2.Request(repository['tags_url'].replace('{/tag}', ''))
241 add_auth(githubreq)
242 result.extend (json.loads(urllib2.urlopen(githubreq).read()))
243
244 repo_path = "device/%s/%s" % (manufacturer, device)
245 adding = {'repository':repo_name,'target_path':repo_path}
246
247 fallback_branch = None
248 if not has_branch(result, default_revision):
249 if os.getenv('ROOMSERVICE_BRANCHES'):
250 fallbacks = filter(bool, os.getenv('ROOMSERVICE_BRANCHES').split(' '))
251 for fallback in fallbacks:
252 if has_branch(result, fallback):
253 print "Using fallback branch: %s" % fallback
254 fallback_branch = fallback
255 break
256
257 if not fallback_branch:
258 print "Default revision %s not found in %s. Bailing." % (default_revision, repo_name)
259 print "Branches found:"
260 for branch in [branch['name'] for branch in result]:
261 print branch
262 print "Use the ROOMSERVICE_BRANCHES environment variable to specify a list of fallback branches."
263 sys.exit()
264
265 add_to_manifest([adding], fallback_branch)
266
267 print "Syncing repository to retrieve project."
268 os.system('repo sync %s' % repo_path)
269 print "Repository synced!"
270
271 fetch_dependencies(repo_path, fallback_branch)
272 print "Done"
273 sys.exit()
274
275print "Repository for %s not found in the CyanogenMod Github repository list. If this is in error, you may need to manually add it to your local_manifests/roomservice.xml." % device