blob: 5eef4eef3fb82166aee34f2001cba23f9d295398 [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
Matt Moweree84e3f2014-10-31 21:02:37 -050055if not depsonly:
Matt Mower28cb6ba2015-01-02 00:08:48 -060056 githubreq = urllib.request.Request("https://api.github.com/search/repositories?q=%s+user:CyanogenMod+in:name+fork:true" % device)
Diogo Ferreira0d109172012-03-18 21:18:29 +000057 add_auth(githubreq)
Matt Moweree84e3f2014-10-31 21:02:37 -050058 result = json.loads(urllib.request.urlopen(githubreq).read().decode())
59 try:
60 numresults = int(result['total_count'])
61 except:
62 print("Failed to search GitHub (offline?)")
63 sys.exit()
64 if (numresults == 0):
65 print("Could not find device %s on github.com/CyanogenMod" % device)
66 sys.exit()
67 for res in result['items']:
Diogo Ferreira0d109172012-03-18 21:18:29 +000068 repositories.append(res)
Koushik Dutta780fb5f2011-11-26 18:51:42 -080069
Diogo Ferreira0d109172012-03-18 21:18:29 +000070local_manifests = r'.repo/local_manifests'
71if not os.path.exists(local_manifests): os.makedirs(local_manifests)
Koushik Dutta780fb5f2011-11-26 18:51:42 -080072
Diogo Ferreira0d109172012-03-18 21:18:29 +000073def exists_in_tree(lm, repository):
74 for child in lm.getchildren():
75 if child.attrib['name'].endswith(repository):
76 return True
77 return False
78
79# in-place prettyprint formatter
80def indent(elem, level=0):
81 i = "\n" + level*" "
82 if len(elem):
83 if not elem.text or not elem.text.strip():
84 elem.text = i + " "
85 if not elem.tail or not elem.tail.strip():
86 elem.tail = i
87 for elem in elem:
88 indent(elem, level+1)
89 if not elem.tail or not elem.tail.strip():
90 elem.tail = i
91 else:
92 if level and (not elem.tail or not elem.tail.strip()):
93 elem.tail = i
94
95def get_default_revision():
96 m = ElementTree.parse(".repo/manifest.xml")
97 d = m.findall('default')[0]
98 r = d.get('revision')
99 return r.replace('refs/heads/', '').replace('refs/tags/', '')
100
101def get_from_manifest(devicename):
102 try:
103 lm = ElementTree.parse(".repo/local_manifests/roomservice.xml")
104 lm = lm.getroot()
105 except:
106 lm = ElementTree.Element("manifest")
107
108 for localpath in lm.findall("project"):
109 if re.search("android_device_.*_%s$" % device, localpath.get("name")):
110 return localpath.get("path")
111
112 # Devices originally from AOSP are in the main manifest...
113 try:
114 mm = ElementTree.parse(".repo/manifest.xml")
115 mm = mm.getroot()
116 except:
117 mm = ElementTree.Element("manifest")
118
119 for localpath in mm.findall("project"):
120 if re.search("android_device_.*_%s$" % device, localpath.get("name")):
121 return localpath.get("path")
122
123 return None
124
125def is_in_manifest(projectname):
126 try:
127 lm = ElementTree.parse(".repo/local_manifests/roomservice.xml")
128 lm = lm.getroot()
129 except:
130 lm = ElementTree.Element("manifest")
131
132 for localpath in lm.findall("project"):
133 if localpath.get("name") == projectname:
134 return 1
135
136 ## Search in main manifest, too
137 try:
138 lm = ElementTree.parse(".repo/manifest.xml")
139 lm = lm.getroot()
140 except:
141 lm = ElementTree.Element("manifest")
142
143 for localpath in lm.findall("project"):
144 if localpath.get("name") == projectname:
145 return 1
146
147 return None
148
149def add_to_manifest(repositories, fallback_branch = None):
150 try:
151 lm = ElementTree.parse(".repo/local_manifests/roomservice.xml")
152 lm = lm.getroot()
153 except:
154 lm = ElementTree.Element("manifest")
155
156 for repository in repositories:
157 repo_name = repository['repository']
158 repo_target = repository['target_path']
159 if exists_in_tree(lm, repo_name):
160 print 'CyanogenMod/%s already exists' % (repo_name)
161 continue
162
163 print 'Adding dependency: CyanogenMod/%s -> %s' % (repo_name, repo_target)
164 project = ElementTree.Element("project", attrib = { "path": repo_target,
165 "remote": "github", "name": "CyanogenMod/%s" % repo_name })
166
167 if 'branch' in repository:
168 project.set('revision',repository['branch'])
169 elif fallback_branch:
170 print "Using fallback branch %s for %s" % (fallback_branch, repo_name)
171 project.set('revision', fallback_branch)
172 else:
173 print "Using default branch for %s" % repo_name
174
Koushik Dutta780fb5f2011-11-26 18:51:42 -0800175 lm.append(project)
Koushik Dutta780fb5f2011-11-26 18:51:42 -0800176
Diogo Ferreira0d109172012-03-18 21:18:29 +0000177 indent(lm, 0)
178 raw_xml = ElementTree.tostring(lm)
179 raw_xml = '<?xml version="1.0" encoding="UTF-8"?>\n' + raw_xml
Koushik Dutta780fb5f2011-11-26 18:51:42 -0800180
Diogo Ferreira0d109172012-03-18 21:18:29 +0000181 f = open('.repo/local_manifests/roomservice.xml', 'w')
182 f.write(raw_xml)
183 f.close()
184
185def fetch_dependencies(repo_path, fallback_branch = None):
186 print 'Looking for dependencies'
187 dependencies_path = repo_path + '/cm.dependencies'
188 syncable_repos = []
189
190 if os.path.exists(dependencies_path):
191 dependencies_file = open(dependencies_path, 'r')
192 dependencies = json.loads(dependencies_file.read())
193 fetch_list = []
194
195 for dependency in dependencies:
196 if not is_in_manifest("CyanogenMod/%s" % dependency['repository']):
197 fetch_list.append(dependency)
198 syncable_repos.append(dependency['target_path'])
199
200 dependencies_file.close()
201
202 if len(fetch_list) > 0:
203 print 'Adding dependencies to manifest'
204 add_to_manifest(fetch_list, fallback_branch)
205 else:
206 print 'Dependencies file not found, bailing out.'
207
208 if len(syncable_repos) > 0:
209 print 'Syncing dependencies'
210 os.system('repo sync %s' % ' '.join(syncable_repos))
211
212 for deprepo in syncable_repos:
213 fetch_dependencies(deprepo)
214
215def has_branch(branches, revision):
216 return revision in [branch['name'] for branch in branches]
217
218if depsonly:
219 repo_path = get_from_manifest(device)
220 if repo_path:
221 fetch_dependencies(repo_path)
222 else:
223 print "Trying dependencies-only mode on a non-existing device tree?"
224
225 sys.exit()
226
227else:
228 for repository in repositories:
229 repo_name = repository['name']
230 if repo_name.startswith("android_device_") and repo_name.endswith("_" + device):
231 print "Found repository: %s" % repository['name']
232
233 manufacturer = repo_name.replace("android_device_", "").replace("_" + device, "")
234
235 default_revision = get_default_revision()
236 print "Default revision: %s" % default_revision
237 print "Checking branch info"
238 githubreq = urllib2.Request(repository['branches_url'].replace('{/branch}', ''))
239 add_auth(githubreq)
240 result = json.loads(urllib2.urlopen(githubreq).read())
241
242 ## Try tags, too, since that's what releases use
243 if not has_branch(result, default_revision):
244 githubreq = urllib2.Request(repository['tags_url'].replace('{/tag}', ''))
245 add_auth(githubreq)
246 result.extend (json.loads(urllib2.urlopen(githubreq).read()))
247
248 repo_path = "device/%s/%s" % (manufacturer, device)
249 adding = {'repository':repo_name,'target_path':repo_path}
250
251 fallback_branch = None
252 if not has_branch(result, default_revision):
253 if os.getenv('ROOMSERVICE_BRANCHES'):
254 fallbacks = filter(bool, os.getenv('ROOMSERVICE_BRANCHES').split(' '))
255 for fallback in fallbacks:
256 if has_branch(result, fallback):
257 print "Using fallback branch: %s" % fallback
258 fallback_branch = fallback
259 break
260
261 if not fallback_branch:
262 print "Default revision %s not found in %s. Bailing." % (default_revision, repo_name)
263 print "Branches found:"
264 for branch in [branch['name'] for branch in result]:
265 print branch
266 print "Use the ROOMSERVICE_BRANCHES environment variable to specify a list of fallback branches."
267 sys.exit()
268
269 add_to_manifest([adding], fallback_branch)
270
271 print "Syncing repository to retrieve project."
272 os.system('repo sync %s' % repo_path)
273 print "Repository synced!"
274
275 fetch_dependencies(repo_path, fallback_branch)
276 print "Done"
277 sys.exit()
278
279print "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