blob: 771d58680c784f67350a4788fe4ae74fe74acfeb [file] [log] [blame]
Michael Bestas3952f6c2016-08-26 01:12:08 +03001#!/usr/bin/env python
2# Copyright (C) 2012-2013, The CyanogenMod Project
Dan Pasanen03447712016-12-19 11:22:55 -06003# (C) 2017, The LineageOS Project
Michael Bestas3952f6c2016-08-26 01:12:08 +03004#
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
17from __future__ import print_function
18
19import base64
20import json
21import netrc
22import os
23import re
24import sys
25try:
26 # For python3
27 import urllib.error
28 import urllib.parse
29 import urllib.request
30except ImportError:
31 # For python2
32 import imp
33 import urllib2
34 import urlparse
35 urllib = imp.new_module('urllib')
36 urllib.error = urllib2
37 urllib.parse = urlparse
38 urllib.request = urllib2
39
40from xml.etree import ElementTree
41
42product = sys.argv[1]
43
44if len(sys.argv) > 2:
45 depsonly = sys.argv[2]
46else:
47 depsonly = None
48
49try:
50 device = product[product.index("_") + 1:]
51except:
52 device = product
53
54if not depsonly:
Dan Pasanen03447712016-12-19 11:22:55 -060055 print("Device %s not found. Attempting to retrieve device repository from LineageOS Github (http://github.com/LineageOS)." % device)
Michael Bestas3952f6c2016-08-26 01:12:08 +030056
57repositories = []
58
59try:
60 authtuple = netrc.netrc().authenticators("api.github.com")
61
62 if authtuple:
63 auth_string = ('%s:%s' % (authtuple[0], authtuple[2])).encode()
64 githubauth = base64.encodestring(auth_string).decode().replace('\n', '')
65 else:
66 githubauth = None
67except:
68 githubauth = None
69
70def add_auth(githubreq):
71 if githubauth:
72 githubreq.add_header("Authorization","Basic %s" % githubauth)
73
74if not depsonly:
Dan Pasanen03447712016-12-19 11:22:55 -060075 githubreq = urllib.request.Request("https://api.github.com/search/repositories?q=%s+user:LineageOS+in:name+fork:true" % device)
Michael Bestas3952f6c2016-08-26 01:12:08 +030076 add_auth(githubreq)
77 try:
78 result = json.loads(urllib.request.urlopen(githubreq).read().decode())
79 except urllib.error.URLError:
80 print("Failed to search GitHub")
81 sys.exit()
82 except ValueError:
83 print("Failed to parse return data from GitHub")
84 sys.exit()
85 for res in result.get('items', []):
86 repositories.append(res)
87
88local_manifests = r'.repo/local_manifests'
89if not os.path.exists(local_manifests): os.makedirs(local_manifests)
90
91def exists_in_tree(lm, path):
92 for child in lm.getchildren():
93 if child.attrib['path'] == path:
94 return True
95 return False
96
97# in-place prettyprint formatter
98def indent(elem, level=0):
99 i = "\n" + level*" "
100 if len(elem):
101 if not elem.text or not elem.text.strip():
102 elem.text = i + " "
103 if not elem.tail or not elem.tail.strip():
104 elem.tail = i
105 for elem in elem:
106 indent(elem, level+1)
107 if not elem.tail or not elem.tail.strip():
108 elem.tail = i
109 else:
110 if level and (not elem.tail or not elem.tail.strip()):
111 elem.tail = i
112
113def get_default_revision():
114 m = ElementTree.parse(".repo/manifest.xml")
115 d = m.findall('default')[0]
116 r = d.get('revision')
117 return r.replace('refs/heads/', '').replace('refs/tags/', '')
118
119def get_from_manifest(devicename):
120 try:
121 lm = ElementTree.parse(".repo/local_manifests/roomservice.xml")
122 lm = lm.getroot()
123 except:
124 lm = ElementTree.Element("manifest")
125
126 for localpath in lm.findall("project"):
127 if re.search("android_device_.*_%s$" % device, localpath.get("name")):
128 return localpath.get("path")
129
130 # Devices originally from AOSP are in the main manifest...
131 try:
132 mm = ElementTree.parse(".repo/manifest.xml")
133 mm = mm.getroot()
134 except:
135 mm = ElementTree.Element("manifest")
136
137 for localpath in mm.findall("project"):
138 if re.search("android_device_.*_%s$" % device, localpath.get("name")):
139 return localpath.get("path")
140
141 return None
142
143def is_in_manifest(projectpath):
144 try:
145 lm = ElementTree.parse(".repo/local_manifests/roomservice.xml")
146 lm = lm.getroot()
147 except:
148 lm = ElementTree.Element("manifest")
149
150 for localpath in lm.findall("project"):
151 if localpath.get("path") == projectpath:
152 return True
153
154 ## Search in main manifest, too
155 try:
156 lm = ElementTree.parse(".repo/manifest.xml")
157 lm = lm.getroot()
158 except:
159 lm = ElementTree.Element("manifest")
160
161 for localpath in lm.findall("project"):
162 if localpath.get("path") == projectpath:
163 return True
164
165 return False
166
167def add_to_manifest(repositories, fallback_branch = None):
168 try:
169 lm = ElementTree.parse(".repo/local_manifests/roomservice.xml")
170 lm = lm.getroot()
171 except:
172 lm = ElementTree.Element("manifest")
173
174 for repository in repositories:
175 repo_name = repository['repository']
176 repo_target = repository['target_path']
177 print('Checking if %s is fetched from %s' % (repo_target, repo_name))
178 if is_in_manifest(repo_target):
Dan Pasanen03447712016-12-19 11:22:55 -0600179 print('LineageOS/%s already fetched to %s' % (repo_name, repo_target))
Michael Bestas3952f6c2016-08-26 01:12:08 +0300180 continue
181
Dan Pasanen03447712016-12-19 11:22:55 -0600182 print('Adding dependency: LineageOS/%s -> %s' % (repo_name, repo_target))
Michael Bestas3952f6c2016-08-26 01:12:08 +0300183 project = ElementTree.Element("project", attrib = { "path": repo_target,
Dan Pasanen03447712016-12-19 11:22:55 -0600184 "remote": "github", "name": "LineageOS/%s" % repo_name })
Michael Bestas3952f6c2016-08-26 01:12:08 +0300185
186 if 'branch' in repository:
187 project.set('revision',repository['branch'])
188 elif fallback_branch:
189 print("Using fallback branch %s for %s" % (fallback_branch, repo_name))
190 project.set('revision', fallback_branch)
191 else:
192 print("Using default branch for %s" % repo_name)
193
194 lm.append(project)
195
196 indent(lm, 0)
197 raw_xml = ElementTree.tostring(lm).decode()
198 raw_xml = '<?xml version="1.0" encoding="UTF-8"?>\n' + raw_xml
199
200 f = open('.repo/local_manifests/roomservice.xml', 'w')
201 f.write(raw_xml)
202 f.close()
203
204def fetch_dependencies(repo_path, fallback_branch = None):
Adrian DC01bdd552016-11-29 00:24:26 +0100205 print('Looking for dependencies in %s' % repo_path)
Simon Shields63ce74b2016-12-28 11:33:29 +1100206 dependencies_paths = [repo_path + '/lineage.dependencies', repo_path + '/cm.dependencies']
207 found_dependencies = False
Michael Bestas3952f6c2016-08-26 01:12:08 +0300208 syncable_repos = []
Adrian DC01bdd552016-11-29 00:24:26 +0100209 verify_repos = []
Michael Bestas3952f6c2016-08-26 01:12:08 +0300210
Simon Shields63ce74b2016-12-28 11:33:29 +1100211 for dependencies_path in dependencies_paths:
212 if os.path.exists(dependencies_path):
213 dependencies_file = open(dependencies_path, 'r')
214 dependencies = json.loads(dependencies_file.read())
215 fetch_list = []
Michael Bestas3952f6c2016-08-26 01:12:08 +0300216
Simon Shields63ce74b2016-12-28 11:33:29 +1100217 for dependency in dependencies:
218 if not is_in_manifest(dependency['target_path']):
219 fetch_list.append(dependency)
220 syncable_repos.append(dependency['target_path'])
221 verify_repos.append(dependency['target_path'])
222 elif re.search("android_device_.*_.*$", dependency['repository']):
223 verify_repos.append(dependency['target_path'])
Michael Bestas3952f6c2016-08-26 01:12:08 +0300224
Simon Shields63ce74b2016-12-28 11:33:29 +1100225 dependencies_file.close()
226 found_dependencies = True
Michael Bestas3952f6c2016-08-26 01:12:08 +0300227
Simon Shields63ce74b2016-12-28 11:33:29 +1100228 if len(fetch_list) > 0:
229 print('Adding dependencies to manifest')
230 add_to_manifest(fetch_list, fallback_branch)
231 break
232
233 if not found_dependencies:
Michael Bestas3952f6c2016-08-26 01:12:08 +0300234 print('Dependencies file not found, bailing out.')
235
236 if len(syncable_repos) > 0:
237 print('Syncing dependencies')
238 os.system('repo sync --force-sync %s' % ' '.join(syncable_repos))
239
Adrian DC01bdd552016-11-29 00:24:26 +0100240 for deprepo in verify_repos:
Michael Bestas3952f6c2016-08-26 01:12:08 +0300241 fetch_dependencies(deprepo)
242
243def has_branch(branches, revision):
244 return revision in [branch['name'] for branch in branches]
245
246if depsonly:
247 repo_path = get_from_manifest(device)
248 if repo_path:
249 fetch_dependencies(repo_path)
250 else:
251 print("Trying dependencies-only mode on a non-existing device tree?")
252
253 sys.exit()
254
255else:
256 for repository in repositories:
257 repo_name = repository['name']
258 if repo_name.startswith("android_device_") and repo_name.endswith("_" + device):
259 print("Found repository: %s" % repository['name'])
260
261 manufacturer = repo_name.replace("android_device_", "").replace("_" + device, "")
262
263 default_revision = get_default_revision()
264 print("Default revision: %s" % default_revision)
265 print("Checking branch info")
266 githubreq = urllib.request.Request(repository['branches_url'].replace('{/branch}', ''))
267 add_auth(githubreq)
268 result = json.loads(urllib.request.urlopen(githubreq).read().decode())
269
270 ## Try tags, too, since that's what releases use
271 if not has_branch(result, default_revision):
272 githubreq = urllib.request.Request(repository['tags_url'].replace('{/tag}', ''))
273 add_auth(githubreq)
274 result.extend (json.loads(urllib.request.urlopen(githubreq).read().decode()))
275
276 repo_path = "device/%s/%s" % (manufacturer, device)
277 adding = {'repository':repo_name,'target_path':repo_path}
278
279 fallback_branch = None
280 if not has_branch(result, default_revision):
281 if os.getenv('ROOMSERVICE_BRANCHES'):
282 fallbacks = list(filter(bool, os.getenv('ROOMSERVICE_BRANCHES').split(' ')))
283 for fallback in fallbacks:
284 if has_branch(result, fallback):
285 print("Using fallback branch: %s" % fallback)
286 fallback_branch = fallback
287 break
288
289 if not fallback_branch:
290 print("Default revision %s not found in %s. Bailing." % (default_revision, repo_name))
291 print("Branches found:")
292 for branch in [branch['name'] for branch in result]:
293 print(branch)
294 print("Use the ROOMSERVICE_BRANCHES environment variable to specify a list of fallback branches.")
295 sys.exit()
296
297 add_to_manifest([adding], fallback_branch)
298
299 print("Syncing repository to retrieve project.")
300 os.system('repo sync --force-sync %s' % repo_path)
301 print("Repository synced!")
302
303 fetch_dependencies(repo_path, fallback_branch)
304 print("Done")
305 sys.exit()
306
Dan Pasanen03447712016-12-19 11:22:55 -0600307print("Repository for %s not found in the LineageOS Github repository list. If this is in error, you may need to manually add it to your local_manifests/roomservice.xml." % device)