blob: 813d0b77d18596659da5f90044ab1ea499885d9e [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
Michael Bestase5969e22017-06-17 20:01:23 +0300143 # Search in main manifest, too
Michael Bestas3952f6c2016-08-26 01:12:08 +0300144 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
Michael Bestase5969e22017-06-17 20:01:23 +0300154 # ... and don't forget the lineage snippet
155 try:
Luca Stefani5c60e4f2017-08-17 19:28:48 +0200156 lm = ElementTree.parse(".repo/manifests/snippets/lineage.xml")
Michael Bestase5969e22017-06-17 20:01:23 +0300157 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
Michael Bestas3952f6c2016-08-26 01:12:08 +0300165 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)
Luca Stefani5c60e4f2017-08-17 19:28:48 +0200206 dependencies_path = repo_path + '/lineage.dependencies'
Michael Bestas3952f6c2016-08-26 01:12:08 +0300207 syncable_repos = []
Adrian DC01bdd552016-11-29 00:24:26 +0100208 verify_repos = []
Michael Bestas3952f6c2016-08-26 01:12:08 +0300209
Luca Stefani5c60e4f2017-08-17 19:28:48 +0200210 if os.path.exists(dependencies_path):
211 dependencies_file = open(dependencies_path, 'r')
212 dependencies = json.loads(dependencies_file.read())
213 fetch_list = []
Michael Bestas3952f6c2016-08-26 01:12:08 +0300214
Luca Stefani5c60e4f2017-08-17 19:28:48 +0200215 for dependency in dependencies:
216 if not is_in_manifest(dependency['target_path']):
217 fetch_list.append(dependency)
218 syncable_repos.append(dependency['target_path'])
219 verify_repos.append(dependency['target_path'])
LuK1337e67b6cb2017-12-28 12:46:16 +0100220 else:
Luca Stefani5c60e4f2017-08-17 19:28:48 +0200221 verify_repos.append(dependency['target_path'])
Michael Bestas3952f6c2016-08-26 01:12:08 +0300222
Luca Stefani5c60e4f2017-08-17 19:28:48 +0200223 dependencies_file.close()
Michael Bestas3952f6c2016-08-26 01:12:08 +0300224
Luca Stefani5c60e4f2017-08-17 19:28:48 +0200225 if len(fetch_list) > 0:
226 print('Adding dependencies to manifest')
227 add_to_manifest(fetch_list, fallback_branch)
228 else:
LuK1337f017e362018-01-26 15:00:52 +0100229 print('%s has no additional dependencies.' % repo_path)
Michael Bestas3952f6c2016-08-26 01:12:08 +0300230
231 if len(syncable_repos) > 0:
232 print('Syncing dependencies')
233 os.system('repo sync --force-sync %s' % ' '.join(syncable_repos))
234
Adrian DC01bdd552016-11-29 00:24:26 +0100235 for deprepo in verify_repos:
Michael Bestas3952f6c2016-08-26 01:12:08 +0300236 fetch_dependencies(deprepo)
237
238def has_branch(branches, revision):
239 return revision in [branch['name'] for branch in branches]
240
241if depsonly:
242 repo_path = get_from_manifest(device)
243 if repo_path:
244 fetch_dependencies(repo_path)
245 else:
246 print("Trying dependencies-only mode on a non-existing device tree?")
247
248 sys.exit()
249
250else:
251 for repository in repositories:
252 repo_name = repository['name']
Michael Gernoth29f3b572017-03-26 14:33:05 +0200253 if re.match(r"^android_device_[^_]*_" + device + "$", repo_name):
Michael Bestas3952f6c2016-08-26 01:12:08 +0300254 print("Found repository: %s" % repository['name'])
255
256 manufacturer = repo_name.replace("android_device_", "").replace("_" + device, "")
257
258 default_revision = get_default_revision()
259 print("Default revision: %s" % default_revision)
260 print("Checking branch info")
261 githubreq = urllib.request.Request(repository['branches_url'].replace('{/branch}', ''))
262 add_auth(githubreq)
263 result = json.loads(urllib.request.urlopen(githubreq).read().decode())
264
265 ## Try tags, too, since that's what releases use
266 if not has_branch(result, default_revision):
267 githubreq = urllib.request.Request(repository['tags_url'].replace('{/tag}', ''))
268 add_auth(githubreq)
269 result.extend (json.loads(urllib.request.urlopen(githubreq).read().decode()))
270
271 repo_path = "device/%s/%s" % (manufacturer, device)
272 adding = {'repository':repo_name,'target_path':repo_path}
273
274 fallback_branch = None
275 if not has_branch(result, default_revision):
276 if os.getenv('ROOMSERVICE_BRANCHES'):
277 fallbacks = list(filter(bool, os.getenv('ROOMSERVICE_BRANCHES').split(' ')))
278 for fallback in fallbacks:
279 if has_branch(result, fallback):
280 print("Using fallback branch: %s" % fallback)
281 fallback_branch = fallback
282 break
283
284 if not fallback_branch:
285 print("Default revision %s not found in %s. Bailing." % (default_revision, repo_name))
286 print("Branches found:")
287 for branch in [branch['name'] for branch in result]:
288 print(branch)
289 print("Use the ROOMSERVICE_BRANCHES environment variable to specify a list of fallback branches.")
290 sys.exit()
291
292 add_to_manifest([adding], fallback_branch)
293
294 print("Syncing repository to retrieve project.")
295 os.system('repo sync --force-sync %s' % repo_path)
296 print("Repository synced!")
297
298 fetch_dependencies(repo_path, fallback_branch)
299 print("Done")
300 sys.exit()
301
Dan Pasanen03447712016-12-19 11:22:55 -0600302print("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)