blob: 6347f9f5064a103e48f112e197b469468d8cd918 [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
Michael Bestas3952f6c2016-08-26 01:12:08 +0300130 return None
131
132def is_in_manifest(projectpath):
133 try:
134 lm = ElementTree.parse(".repo/local_manifests/roomservice.xml")
135 lm = lm.getroot()
136 except:
137 lm = ElementTree.Element("manifest")
138
139 for localpath in lm.findall("project"):
140 if localpath.get("path") == projectpath:
141 return True
142
143 ## Search in main manifest, too
144 try:
145 lm = ElementTree.parse(".repo/manifest.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 return False
155
156def add_to_manifest(repositories, fallback_branch = None):
157 try:
158 lm = ElementTree.parse(".repo/local_manifests/roomservice.xml")
159 lm = lm.getroot()
160 except:
161 lm = ElementTree.Element("manifest")
162
163 for repository in repositories:
164 repo_name = repository['repository']
165 repo_target = repository['target_path']
166 print('Checking if %s is fetched from %s' % (repo_target, repo_name))
167 if is_in_manifest(repo_target):
Dan Pasanen03447712016-12-19 11:22:55 -0600168 print('LineageOS/%s already fetched to %s' % (repo_name, repo_target))
Michael Bestas3952f6c2016-08-26 01:12:08 +0300169 continue
170
Dan Pasanen03447712016-12-19 11:22:55 -0600171 print('Adding dependency: LineageOS/%s -> %s' % (repo_name, repo_target))
Michael Bestas3952f6c2016-08-26 01:12:08 +0300172 project = ElementTree.Element("project", attrib = { "path": repo_target,
Dan Pasanen03447712016-12-19 11:22:55 -0600173 "remote": "github", "name": "LineageOS/%s" % repo_name })
Michael Bestas3952f6c2016-08-26 01:12:08 +0300174
175 if 'branch' in repository:
176 project.set('revision',repository['branch'])
177 elif fallback_branch:
178 print("Using fallback branch %s for %s" % (fallback_branch, repo_name))
179 project.set('revision', fallback_branch)
180 else:
181 print("Using default branch for %s" % repo_name)
182
183 lm.append(project)
184
185 indent(lm, 0)
186 raw_xml = ElementTree.tostring(lm).decode()
187 raw_xml = '<?xml version="1.0" encoding="UTF-8"?>\n' + raw_xml
188
189 f = open('.repo/local_manifests/roomservice.xml', 'w')
190 f.write(raw_xml)
191 f.close()
192
193def fetch_dependencies(repo_path, fallback_branch = None):
Adrian DC01bdd552016-11-29 00:24:26 +0100194 print('Looking for dependencies in %s' % repo_path)
Simon Shields63ce74b2016-12-28 11:33:29 +1100195 dependencies_paths = [repo_path + '/lineage.dependencies', repo_path + '/cm.dependencies']
196 found_dependencies = False
Michael Bestas3952f6c2016-08-26 01:12:08 +0300197 syncable_repos = []
Adrian DC01bdd552016-11-29 00:24:26 +0100198 verify_repos = []
Michael Bestas3952f6c2016-08-26 01:12:08 +0300199
Simon Shields63ce74b2016-12-28 11:33:29 +1100200 for dependencies_path in dependencies_paths:
201 if os.path.exists(dependencies_path):
202 dependencies_file = open(dependencies_path, 'r')
203 dependencies = json.loads(dependencies_file.read())
204 fetch_list = []
Michael Bestas3952f6c2016-08-26 01:12:08 +0300205
Simon Shields63ce74b2016-12-28 11:33:29 +1100206 for dependency in dependencies:
207 if not is_in_manifest(dependency['target_path']):
208 fetch_list.append(dependency)
209 syncable_repos.append(dependency['target_path'])
210 verify_repos.append(dependency['target_path'])
211 elif re.search("android_device_.*_.*$", dependency['repository']):
212 verify_repos.append(dependency['target_path'])
Michael Bestas3952f6c2016-08-26 01:12:08 +0300213
Simon Shields63ce74b2016-12-28 11:33:29 +1100214 dependencies_file.close()
215 found_dependencies = True
Michael Bestas3952f6c2016-08-26 01:12:08 +0300216
Simon Shields63ce74b2016-12-28 11:33:29 +1100217 if len(fetch_list) > 0:
218 print('Adding dependencies to manifest')
219 add_to_manifest(fetch_list, fallback_branch)
220 break
221
222 if not found_dependencies:
Michael Bestas3952f6c2016-08-26 01:12:08 +0300223 print('Dependencies file not found, bailing out.')
224
225 if len(syncable_repos) > 0:
226 print('Syncing dependencies')
227 os.system('repo sync --force-sync %s' % ' '.join(syncable_repos))
228
Adrian DC01bdd552016-11-29 00:24:26 +0100229 for deprepo in verify_repos:
Michael Bestas3952f6c2016-08-26 01:12:08 +0300230 fetch_dependencies(deprepo)
231
232def has_branch(branches, revision):
233 return revision in [branch['name'] for branch in branches]
234
235if depsonly:
236 repo_path = get_from_manifest(device)
237 if repo_path:
238 fetch_dependencies(repo_path)
239 else:
240 print("Trying dependencies-only mode on a non-existing device tree?")
241
242 sys.exit()
243
244else:
245 for repository in repositories:
246 repo_name = repository['name']
Michael Gernoth29f3b572017-03-26 14:33:05 +0200247 if re.match(r"^android_device_[^_]*_" + device + "$", repo_name):
Michael Bestas3952f6c2016-08-26 01:12:08 +0300248 print("Found repository: %s" % repository['name'])
249
250 manufacturer = repo_name.replace("android_device_", "").replace("_" + device, "")
251
252 default_revision = get_default_revision()
253 print("Default revision: %s" % default_revision)
254 print("Checking branch info")
255 githubreq = urllib.request.Request(repository['branches_url'].replace('{/branch}', ''))
256 add_auth(githubreq)
257 result = json.loads(urllib.request.urlopen(githubreq).read().decode())
258
259 ## Try tags, too, since that's what releases use
260 if not has_branch(result, default_revision):
261 githubreq = urllib.request.Request(repository['tags_url'].replace('{/tag}', ''))
262 add_auth(githubreq)
263 result.extend (json.loads(urllib.request.urlopen(githubreq).read().decode()))
264
265 repo_path = "device/%s/%s" % (manufacturer, device)
266 adding = {'repository':repo_name,'target_path':repo_path}
267
268 fallback_branch = None
269 if not has_branch(result, default_revision):
270 if os.getenv('ROOMSERVICE_BRANCHES'):
271 fallbacks = list(filter(bool, os.getenv('ROOMSERVICE_BRANCHES').split(' ')))
272 for fallback in fallbacks:
273 if has_branch(result, fallback):
274 print("Using fallback branch: %s" % fallback)
275 fallback_branch = fallback
276 break
277
278 if not fallback_branch:
279 print("Default revision %s not found in %s. Bailing." % (default_revision, repo_name))
280 print("Branches found:")
281 for branch in [branch['name'] for branch in result]:
282 print(branch)
283 print("Use the ROOMSERVICE_BRANCHES environment variable to specify a list of fallback branches.")
284 sys.exit()
285
286 add_to_manifest([adding], fallback_branch)
287
288 print("Syncing repository to retrieve project.")
289 os.system('repo sync --force-sync %s' % repo_path)
290 print("Repository synced!")
291
292 fetch_dependencies(repo_path, fallback_branch)
293 print("Done")
294 sys.exit()
295
Dan Pasanen03447712016-12-19 11:22:55 -0600296print("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)