blob: 8f3641f2e17386fd8a542aa234a563c0a4bda4d9 [file] [log] [blame]
cybojenix3e873402013-10-17 03:34:57 +04001#!/usr/bin/env python
2
3# Copyright (C) 2013 Cybojenix <anthonydking@gmail.com>
4# Copyright (C) 2013 The OmniROM Project
5#
6# This program is free software: you can redistribute it and/or modify
7# it under the terms of the GNU General Public License as published by
8# the Free Software Foundation, either version 3 of the License, or
9# (at your option) any later version.
10#
11# This program is distributed in the hope that it will be useful,
12# but WITHOUT ANY WARRANTY; without even the implied warranty of
13# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14# GNU General Public License for more details.
15#
16# You should have received a copy of the GNU General Public License
17# along with this program. If not, see <http://www.gnu.org/licenses/>.
18
19from __future__ import print_function
20import json
21import sys
22import os
23import os.path
24import re
25from xml.etree import ElementTree as ES
26# Use the urllib importer from the Cyanogenmod roomservice
27try:
28 # For python3
29 import urllib.request
30except ImportError:
31 # For python2
32 import imp
33 import urllib2
34 urllib = imp.new_module('urllib')
35 urllib.request = urllib2
36
37# Config
38# set this to the default remote to use in repo
39default_rem = "omnirom"
40# set this to the default revision to use (branch/tag name)
Marko Man97ff5862018-08-09 14:29:04 +020041default_rev = "android-9.0"
cybojenix3e873402013-10-17 03:34:57 +040042# set this to the remote that you use for projects from your team repos
43# example fetch="https://github.com/omnirom"
44default_team_rem = "omnirom"
45# this shouldn't change unless google makes changes
46local_manifest_dir = ".repo/local_manifests"
47# change this to your name on github (or equivalent hosting)
48android_team = "omnirom"
49# url to gerrit repository
50gerrit_url = "gerrit.omnirom.org"
51
52
53def check_repo_exists(git_data, device):
54 re_match = "^android_device_.*_{device}$".format(device=device)
Felix Elsner67fdf892018-12-04 21:45:49 +010055 matches = list(filter(lambda x: re.match(re_match, x), git_data))
cybojenix3e873402013-10-17 03:34:57 +040056 if len(matches) != 1:
57 raise Exception("{device} not found,"
58 "exiting roomservice".format(device=device))
59
60 return git_data[matches[0]]
61
62
63def search_gerrit_for_device(device):
64 # TODO: In next gerrit release regex search with r= should be supported!
65 git_search_url = "https://{gerrit_url}/projects/?m={device}".format(
66 gerrit_url=gerrit_url,
67 device=device
68 )
69 git_req = urllib.request.Request(git_search_url)
70 try:
71 response = urllib.request.urlopen(git_req)
Felix Elsnerc1c2d752018-11-25 12:46:13 +010072 except urllib.request.HTTPError:
cybojenix3e873402013-10-17 03:34:57 +040073 print("There was an issue connecting to gerrit."
Felix Elsnerc1c2d752018-11-25 12:46:13 +010074 " Please try again in a minute")
75 except urllib.request.URLError:
cybojenix3e873402013-10-17 03:34:57 +040076 print("WARNING: No network connection available.")
77 else:
78 # Skip silly gerrit "header"
79 response.readline()
80 git_data = json.load(response)
81 device_data = check_repo_exists(git_data, device)
82 print("found the {} device repo".format(device))
83 return device_data
84
85
86def parse_device_directory(device_url, device):
87 pattern = "^android_device_(?P<vendor>.+)_{}$".format(device)
88 match = re.match(pattern, device_url)
89
90 if match is None:
91 raise Exception("Invalid project name {}".format(device_url))
92 return "device/{vendor}/{device}".format(
93 vendor=match.group('vendor'),
94 device=device,
95 )
96
97
98# Thank you RaYmAn
99def iterate_manifests():
100 files = []
101 for file in os.listdir(local_manifest_dir):
102 if file.endswith(".xml"):
103 files.append(os.path.join(local_manifest_dir, file))
104 files.append('.repo/manifest.xml')
105 for file in files:
106 try:
107 man = ES.parse(file)
108 man = man.getroot()
Felix Elsnerc1c2d752018-11-25 12:46:13 +0100109 except (IOError, ES.ParseError):
cybojenix3e873402013-10-17 03:34:57 +0400110 print("WARNING: error while parsing %s" % file)
111 else:
112 for project in man.findall("project"):
113 yield project
114
115
116def check_project_exists(url, revision, path):
117 for project in iterate_manifests():
Felix Elsnerc1c2d752018-11-25 12:46:13 +0100118 if project.get("name") == url \
119 and project.get("revision") == revision \
120 and project.get("path") == path:
cybojenix3e873402013-10-17 03:34:57 +0400121 return True
122 return False
123
124
125def check_target_exists(directory):
126 return os.path.isdir(directory)
127
128
129# Use the indent function from http://stackoverflow.com/a/4590052
130def indent(elem, level=0):
131 i = ''.join(["\n", level*" "])
132 if len(elem):
133 if not elem.text or not elem.text.strip():
134 elem.text = ''.join([i, " "])
135 if not elem.tail or not elem.tail.strip():
136 elem.tail = i
137 for elem in elem:
138 indent(elem, level+1)
139 if not elem.tail or not elem.tail.strip():
140 elem.tail = i
141 else:
142 if level and (not elem.tail or not elem.tail.strip()):
143 elem.tail = i
144
145
146def create_manifest_project(url, directory,
147 remote=default_rem,
148 revision=default_rev):
149 project_exists = check_project_exists(url, revision, directory)
150
151 if project_exists:
152 return None
153
154 project = ES.Element("project",
155 attrib={
156 "path": directory,
157 "name": url,
158 "remote": remote,
159 "revision": revision
160 })
161 return project
162
163
164def append_to_manifest(project):
165 try:
166 lm = ES.parse('/'.join([local_manifest_dir, "roomservice.xml"]))
167 lm = lm.getroot()
Felix Elsnerc1c2d752018-11-25 12:46:13 +0100168 except (IOError, ES.ParseError):
cybojenix3e873402013-10-17 03:34:57 +0400169 lm = ES.Element("manifest")
170 lm.append(project)
171 return lm
172
173
174def write_to_manifest(manifest):
175 indent(manifest)
176 raw_xml = ES.tostring(manifest).decode()
177 raw_xml = ''.join(['<?xml version="1.0" encoding="UTF-8"?>\n'
178 '<!--Please do not manually edit this file-->\n',
179 raw_xml])
180
181 with open('/'.join([local_manifest_dir, "roomservice.xml"]), 'w') as f:
182 f.write(raw_xml)
183 print("wrote the new roomservice manifest")
184
185
186def parse_device_from_manifest(device):
187 for project in iterate_manifests():
188 name = project.get('name')
189 if name.startswith("android_device_") and name.endswith(device):
190 return project.get('path')
191 return None
192
193
194def parse_device_from_folder(device):
195 search = []
maxwenc8a6b6c2017-12-05 01:37:48 +0100196 if not os.path.isdir("device"):
197 os.mkdir("device")
cybojenix3e873402013-10-17 03:34:57 +0400198 for sub_folder in os.listdir("device"):
199 if os.path.isdir("device/%s/%s" % (sub_folder, device)):
200 search.append("device/%s/%s" % (sub_folder, device))
201 if len(search) > 1:
202 print("multiple devices under the name %s. "
203 "defaulting to checking the manifest" % device)
204 location = parse_device_from_manifest(device)
205 elif len(search) == 1:
206 location = search[0]
207 else:
208 print("Your device can't be found in device sources..")
209 location = parse_device_from_manifest(device)
210 return location
211
212
213def parse_dependency_file(location):
214 dep_file = "omni.dependencies"
215 dep_location = '/'.join([location, dep_file])
216 if not os.path.isfile(dep_location):
217 print("WARNING: %s file not found" % dep_location)
218 sys.exit()
219 try:
220 with open(dep_location, 'r') as f:
221 dependencies = json.loads(f.read())
222 except ValueError:
223 raise Exception("ERROR: malformed dependency file")
224 return dependencies
225
Felix Elsnerc1c2d752018-11-25 12:46:13 +0100226
cybojenix3e873402013-10-17 03:34:57 +0400227# if there is any conflict with existing and new
228# delete the roomservice.xml file and create new
229def check_manifest_problems(dependencies):
230 for dependency in dependencies:
231 repository = dependency.get("repository")
232 target_path = dependency.get("target_path")
233 revision = dependency.get("revision", default_rev)
cybojenix3e873402013-10-17 03:34:57 +0400234
235 # check for existing projects
236 for project in iterate_manifests():
Felix Elsnerc1c2d752018-11-25 12:46:13 +0100237 if project.get("revision") is not None \
238 and project.get("path") is not None \
239 and project.get("path") == target_path \
240 and project.get("revision") != revision:
241 print("WARNING: detected conflict in revisions for repository ",
242 repository)
243 current_dependency = str(project.get(repository))
244 file = ES.parse('/'.join([local_manifest_dir,
245 "roomservice.xml"]))
246 file_root = file.getroot()
247 for current_project in file_root.findall('project'):
248 new_dependency = str(current_project.find('revision'))
249 if new_dependency == current_dependency:
250 file_root.remove(current_project)
251 file.write('/'.join([local_manifest_dir, "roomservice.xml"]))
252 return
253
cybojenix3e873402013-10-17 03:34:57 +0400254
255def create_dependency_manifest(dependencies):
256 projects = []
257 for dependency in dependencies:
258 repository = dependency.get("repository")
259 target_path = dependency.get("target_path")
260 revision = dependency.get("revision", default_rev)
261 remote = dependency.get("remote", default_rem)
262
263 # not adding an organization should default to android_team
264 # only apply this to github
265 if remote == "github":
266 if "/" not in repository:
267 repository = '/'.join([android_team, repository])
268 project = create_manifest_project(repository,
269 target_path,
270 remote=remote,
271 revision=revision)
272 if project is not None:
273 manifest = append_to_manifest(project)
274 write_to_manifest(manifest)
275 projects.append(target_path)
276 if len(projects) > 0:
277 os.system("repo sync -f --no-clone-bundle %s" % " ".join(projects))
278
279
280def create_common_dependencies_manifest(dependencies):
281 dep_file = "omni.dependencies"
282 common_list = []
283 if dependencies is not None:
284 for dependency in dependencies:
285 try:
286 index = common_list.index(dependency['target_path'])
287 except ValueError:
288 index = None
289 if index is None:
290 common_list.append(dependency['target_path'])
291 dep_location = '/'.join([dependency['target_path'], dep_file])
292 if not os.path.isfile(dep_location):
293 sys.exit()
294 else:
295 try:
296 with open(dep_location, 'r') as f:
297 common_deps = json.loads(f.read())
298 except ValueError:
299 raise Exception("ERROR: malformed dependency file")
300
301 if common_deps is not None:
302 print("Looking for dependencies on: ",
Felix Elsnerc1c2d752018-11-25 12:46:13 +0100303 dependency['target_path'])
cybojenix3e873402013-10-17 03:34:57 +0400304 check_manifest_problems(common_deps)
305 create_dependency_manifest(common_deps)
306 create_common_dependencies_manifest(common_deps)
307
308
309def fetch_dependencies(device):
310 location = parse_device_from_folder(device)
311 if location is None or not os.path.isdir(location):
312 raise Exception("ERROR: could not find your device "
313 "folder location, bailing out")
314 dependencies = parse_dependency_file(location)
315 check_manifest_problems(dependencies)
316 create_dependency_manifest(dependencies)
317 create_common_dependencies_manifest(dependencies)
318 fetch_device(device)
319
Felix Elsnerc1c2d752018-11-25 12:46:13 +0100320
cybojenix3e873402013-10-17 03:34:57 +0400321def check_device_exists(device):
322 location = parse_device_from_folder(device)
323 if location is None:
324 return False
325 return os.path.isdir(location)
326
327
328def fetch_device(device):
329 if check_device_exists(device):
330 print("WARNING: Trying to fetch a device that's already there")
331 git_data = search_gerrit_for_device(device)
332 if git_data is not None:
333 device_url = git_data['id']
334 device_dir = parse_device_directory(device_url, device)
335 project = create_manifest_project(device_url,
Felix Elsnerc1c2d752018-11-25 12:46:13 +0100336 device_dir,
337 remote=default_team_rem)
cybojenix3e873402013-10-17 03:34:57 +0400338 if project is not None:
339 manifest = append_to_manifest(project)
340 write_to_manifest(manifest)
341 # In case a project was written to manifest, but never synced
342 if project is not None or not check_target_exists(device_dir):
343 print("syncing the device config")
344 os.system('repo sync -f --no-clone-bundle %s' % device_dir)
345
346
347if __name__ == '__main__':
348 if not os.path.isdir(local_manifest_dir):
349 os.mkdir(local_manifest_dir)
350
351 product = sys.argv[1]
352 try:
353 device = product[product.index("_") + 1:]
354 except ValueError:
355 device = product
356
357 if len(sys.argv) > 2:
358 deps_only = sys.argv[2]
359 else:
360 deps_only = False
361
362 if not deps_only:
363 fetch_device(device)
364 fetch_dependencies(device)