blob: ee8e5d8a37795b946575193abbdbf02999c6808a [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
Chirayu Desai55b9b642013-04-30 17:08:17 +053016from __future__ import print_function
17
18import base64
Koushik Dutta780fb5f2011-11-26 18:51:42 -080019import json
Chirayu Desai55b9b642013-04-30 17:08:17 +053020import netrc
21import os
Diogo Ferreira0d109172012-03-18 21:18:29 +000022import re
Chirayu Desai55b9b642013-04-30 17:08:17 +053023import sys
24try:
25 # For python3
26 import urllib.error
27 import urllib.parse
28 import urllib.request
29except ImportError:
30 # For python2
31 import imp
32 import urllib2
33 import urlparse
34 urllib = imp.new_module('urllib')
35 urllib.error = urllib2
36 urllib.parse = urlparse
37 urllib.request = urllib2
38
Koushik Dutta780fb5f2011-11-26 18:51:42 -080039from xml.etree import ElementTree
40
Anthony Kingc713d762015-11-03 00:23:11 +000041product = sys.argv[1]
Diogo Ferreira0d109172012-03-18 21:18:29 +000042
43if len(sys.argv) > 2:
44 depsonly = sys.argv[2]
45else:
46 depsonly = None
47
48try:
49 device = product[product.index("_") + 1:]
50except:
51 device = product
52
53if not depsonly:
Chirayu Desai55b9b642013-04-30 17:08:17 +053054 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 -080055
56repositories = []
57
Diogo Ferreira0d109172012-03-18 21:18:29 +000058try:
59 authtuple = netrc.netrc().authenticators("api.github.com")
60
61 if authtuple:
Anthony Kingc713d762015-11-03 00:23:11 +000062 auth_string = ('%s:%s' % (authtuple[0], authtuple[2])).encode()
63 githubauth = base64.encodestring(auth_string).decode().replace('\n', '')
Diogo Ferreira0d109172012-03-18 21:18:29 +000064 else:
65 githubauth = None
66except:
67 githubauth = None
68
69def add_auth(githubreq):
70 if githubauth:
71 githubreq.add_header("Authorization","Basic %s" % githubauth)
72
Matt Moweree84e3f2014-10-31 21:02:37 -050073if not depsonly:
Matt Mower28cb6ba2015-01-02 00:08:48 -060074 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 +000075 add_auth(githubreq)
Matt Moweree84e3f2014-10-31 21:02:37 -050076 try:
Anthony King365b1e22015-01-08 11:39:12 -060077 result = json.loads(urllib.request.urlopen(githubreq).read().decode())
78 except urllib.error.URLError:
79 print("Failed to search GitHub")
Matt Moweree84e3f2014-10-31 21:02:37 -050080 sys.exit()
Anthony King365b1e22015-01-08 11:39:12 -060081 except ValueError:
82 print("Failed to parse return data from GitHub")
Matt Moweree84e3f2014-10-31 21:02:37 -050083 sys.exit()
Anthony King365b1e22015-01-08 11:39:12 -060084 for res in result.get('items', []):
Diogo Ferreira0d109172012-03-18 21:18:29 +000085 repositories.append(res)
Koushik Dutta780fb5f2011-11-26 18:51:42 -080086
Diogo Ferreira0d109172012-03-18 21:18:29 +000087local_manifests = r'.repo/local_manifests'
88if not os.path.exists(local_manifests): os.makedirs(local_manifests)
Koushik Dutta780fb5f2011-11-26 18:51:42 -080089
Diogo Ferreira0d109172012-03-18 21:18:29 +000090def exists_in_tree(lm, repository):
91 for child in lm.getchildren():
92 if child.attrib['name'].endswith(repository):
93 return True
94 return False
95
96# in-place prettyprint formatter
97def indent(elem, level=0):
98 i = "\n" + level*" "
99 if len(elem):
100 if not elem.text or not elem.text.strip():
101 elem.text = i + " "
102 if not elem.tail or not elem.tail.strip():
103 elem.tail = i
104 for elem in elem:
105 indent(elem, level+1)
106 if not elem.tail or not elem.tail.strip():
107 elem.tail = i
108 else:
109 if level and (not elem.tail or not elem.tail.strip()):
110 elem.tail = i
111
112def get_default_revision():
113 m = ElementTree.parse(".repo/manifest.xml")
114 d = m.findall('default')[0]
115 r = d.get('revision')
116 return r.replace('refs/heads/', '').replace('refs/tags/', '')
117
118def get_from_manifest(devicename):
119 try:
120 lm = ElementTree.parse(".repo/local_manifests/roomservice.xml")
121 lm = lm.getroot()
122 except:
123 lm = ElementTree.Element("manifest")
124
125 for localpath in lm.findall("project"):
126 if re.search("android_device_.*_%s$" % device, localpath.get("name")):
127 return localpath.get("path")
128
129 # Devices originally from AOSP are in the main manifest...
130 try:
131 mm = ElementTree.parse(".repo/manifest.xml")
132 mm = mm.getroot()
133 except:
134 mm = ElementTree.Element("manifest")
135
136 for localpath in mm.findall("project"):
137 if re.search("android_device_.*_%s$" % device, localpath.get("name")):
138 return localpath.get("path")
139
140 return None
141
142def is_in_manifest(projectname):
143 try:
144 lm = ElementTree.parse(".repo/local_manifests/roomservice.xml")
145 lm = lm.getroot()
146 except:
147 lm = ElementTree.Element("manifest")
148
149 for localpath in lm.findall("project"):
150 if localpath.get("name") == projectname:
151 return 1
152
153 ## Search in main manifest, too
154 try:
155 lm = ElementTree.parse(".repo/manifest.xml")
156 lm = lm.getroot()
157 except:
158 lm = ElementTree.Element("manifest")
159
160 for localpath in lm.findall("project"):
161 if localpath.get("name") == projectname:
162 return 1
163
164 return None
165
166def add_to_manifest(repositories, fallback_branch = None):
167 try:
168 lm = ElementTree.parse(".repo/local_manifests/roomservice.xml")
169 lm = lm.getroot()
170 except:
171 lm = ElementTree.Element("manifest")
172
173 for repository in repositories:
174 repo_name = repository['repository']
175 repo_target = repository['target_path']
176 if exists_in_tree(lm, repo_name):
Chirayu Desai55b9b642013-04-30 17:08:17 +0530177 print('CyanogenMod/%s already exists' % (repo_name))
Diogo Ferreira0d109172012-03-18 21:18:29 +0000178 continue
179
Chirayu Desai55b9b642013-04-30 17:08:17 +0530180 print('Adding dependency: CyanogenMod/%s -> %s' % (repo_name, repo_target))
Diogo Ferreira0d109172012-03-18 21:18:29 +0000181 project = ElementTree.Element("project", attrib = { "path": repo_target,
182 "remote": "github", "name": "CyanogenMod/%s" % repo_name })
183
184 if 'branch' in repository:
185 project.set('revision',repository['branch'])
186 elif fallback_branch:
Chirayu Desai55b9b642013-04-30 17:08:17 +0530187 print("Using fallback branch %s for %s" % (fallback_branch, repo_name))
Diogo Ferreira0d109172012-03-18 21:18:29 +0000188 project.set('revision', fallback_branch)
189 else:
Chirayu Desai55b9b642013-04-30 17:08:17 +0530190 print("Using default branch for %s" % repo_name)
Diogo Ferreira0d109172012-03-18 21:18:29 +0000191
Koushik Dutta780fb5f2011-11-26 18:51:42 -0800192 lm.append(project)
Koushik Dutta780fb5f2011-11-26 18:51:42 -0800193
Diogo Ferreira0d109172012-03-18 21:18:29 +0000194 indent(lm, 0)
Chirayu Desai55b9b642013-04-30 17:08:17 +0530195 raw_xml = ElementTree.tostring(lm).decode()
Diogo Ferreira0d109172012-03-18 21:18:29 +0000196 raw_xml = '<?xml version="1.0" encoding="UTF-8"?>\n' + raw_xml
Koushik Dutta780fb5f2011-11-26 18:51:42 -0800197
Diogo Ferreira0d109172012-03-18 21:18:29 +0000198 f = open('.repo/local_manifests/roomservice.xml', 'w')
199 f.write(raw_xml)
200 f.close()
201
202def fetch_dependencies(repo_path, fallback_branch = None):
Chirayu Desai55b9b642013-04-30 17:08:17 +0530203 print('Looking for dependencies')
Diogo Ferreira0d109172012-03-18 21:18:29 +0000204 dependencies_path = repo_path + '/cm.dependencies'
205 syncable_repos = []
206
207 if os.path.exists(dependencies_path):
208 dependencies_file = open(dependencies_path, 'r')
209 dependencies = json.loads(dependencies_file.read())
210 fetch_list = []
211
212 for dependency in dependencies:
213 if not is_in_manifest("CyanogenMod/%s" % dependency['repository']):
214 fetch_list.append(dependency)
215 syncable_repos.append(dependency['target_path'])
216
217 dependencies_file.close()
218
219 if len(fetch_list) > 0:
Chirayu Desai55b9b642013-04-30 17:08:17 +0530220 print('Adding dependencies to manifest')
Diogo Ferreira0d109172012-03-18 21:18:29 +0000221 add_to_manifest(fetch_list, fallback_branch)
222 else:
Chirayu Desai55b9b642013-04-30 17:08:17 +0530223 print('Dependencies file not found, bailing out.')
Diogo Ferreira0d109172012-03-18 21:18:29 +0000224
225 if len(syncable_repos) > 0:
Chirayu Desai55b9b642013-04-30 17:08:17 +0530226 print('Syncing dependencies')
Brint E. Kriebel9129cb02015-08-12 14:05:03 -0700227 os.system('repo sync --force-sync %s' % ' '.join(syncable_repos))
Diogo Ferreira0d109172012-03-18 21:18:29 +0000228
229 for deprepo in syncable_repos:
230 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:
Chirayu Desai55b9b642013-04-30 17:08:17 +0530240 print("Trying dependencies-only mode on a non-existing device tree?")
Diogo Ferreira0d109172012-03-18 21:18:29 +0000241
242 sys.exit()
243
244else:
245 for repository in repositories:
246 repo_name = repository['name']
247 if repo_name.startswith("android_device_") and repo_name.endswith("_" + device):
Chirayu Desai55b9b642013-04-30 17:08:17 +0530248 print("Found repository: %s" % repository['name'])
Diogo Ferreira0d109172012-03-18 21:18:29 +0000249
250 manufacturer = repo_name.replace("android_device_", "").replace("_" + device, "")
251
252 default_revision = get_default_revision()
Chirayu Desai55b9b642013-04-30 17:08:17 +0530253 print("Default revision: %s" % default_revision)
254 print("Checking branch info")
255 githubreq = urllib.request.Request(repository['branches_url'].replace('{/branch}', ''))
Diogo Ferreira0d109172012-03-18 21:18:29 +0000256 add_auth(githubreq)
Chirayu Desai55b9b642013-04-30 17:08:17 +0530257 result = json.loads(urllib.request.urlopen(githubreq).read().decode())
Diogo Ferreira0d109172012-03-18 21:18:29 +0000258
259 ## Try tags, too, since that's what releases use
260 if not has_branch(result, default_revision):
Chirayu Desai55b9b642013-04-30 17:08:17 +0530261 githubreq = urllib.request.Request(repository['tags_url'].replace('{/tag}', ''))
Diogo Ferreira0d109172012-03-18 21:18:29 +0000262 add_auth(githubreq)
Chirayu Desai55b9b642013-04-30 17:08:17 +0530263 result.extend (json.loads(urllib.request.urlopen(githubreq).read().decode()))
Diogo Ferreira0d109172012-03-18 21:18:29 +0000264
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'):
Chirayu Desai55b9b642013-04-30 17:08:17 +0530271 fallbacks = list(filter(bool, os.getenv('ROOMSERVICE_BRANCHES').split(' ')))
Diogo Ferreira0d109172012-03-18 21:18:29 +0000272 for fallback in fallbacks:
273 if has_branch(result, fallback):
Chirayu Desai55b9b642013-04-30 17:08:17 +0530274 print("Using fallback branch: %s" % fallback)
Diogo Ferreira0d109172012-03-18 21:18:29 +0000275 fallback_branch = fallback
276 break
277
278 if not fallback_branch:
Chirayu Desai55b9b642013-04-30 17:08:17 +0530279 print("Default revision %s not found in %s. Bailing." % (default_revision, repo_name))
280 print("Branches found:")
Diogo Ferreira0d109172012-03-18 21:18:29 +0000281 for branch in [branch['name'] for branch in result]:
Chirayu Desai55b9b642013-04-30 17:08:17 +0530282 print(branch)
283 print("Use the ROOMSERVICE_BRANCHES environment variable to specify a list of fallback branches.")
Diogo Ferreira0d109172012-03-18 21:18:29 +0000284 sys.exit()
285
286 add_to_manifest([adding], fallback_branch)
287
Chirayu Desai55b9b642013-04-30 17:08:17 +0530288 print("Syncing repository to retrieve project.")
Brint E. Kriebel9129cb02015-08-12 14:05:03 -0700289 os.system('repo sync --force-sync %s' % repo_path)
Chirayu Desai55b9b642013-04-30 17:08:17 +0530290 print("Repository synced!")
Diogo Ferreira0d109172012-03-18 21:18:29 +0000291
292 fetch_dependencies(repo_path, fallback_branch)
Chirayu Desai55b9b642013-04-30 17:08:17 +0530293 print("Done")
Diogo Ferreira0d109172012-03-18 21:18:29 +0000294 sys.exit()
295
Chirayu Desai55b9b642013-04-30 17:08:17 +0530296print("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)