1 # -*- coding: utf-8 -*-
3 #-------------------------------------------------------------------------
4 # drawElements Quality Program utilities
5 # --------------------------------------
7 # Copyright 2015 The Android Open Source Project
9 # Licensed under the Apache License, Version 2.0 (the "License");
10 # you may not use this file except in compliance with the License.
11 # You may obtain a copy of the License at
13 # http://www.apache.org/licenses/LICENSE-2.0
15 # Unless required by applicable law or agreed to in writing, software
16 # distributed under the License is distributed on an "AS IS" BASIS,
17 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18 # See the License for the specific language governing permissions and
19 # limitations under the License.
21 #-------------------------------------------------------------------------
33 sys.path.append(os.path.join(os.path.dirname(__file__), "..", "scripts"))
35 from build.common import *
37 EXTERNAL_DIR = os.path.realpath(os.path.normpath(os.path.dirname(__file__)))
39 def computeChecksum (data):
40 return hashlib.sha256(data).hexdigest()
42 def onReadonlyRemoveError (func, path, exc_info):
43 os.chmod(path, stat.S_IWRITE)
47 def __init__(self, baseDir, extractDir):
48 self.baseDir = baseDir
49 self.extractDir = extractDir
52 fullDstPath = os.path.join(EXTERNAL_DIR, self.baseDir, self.extractDir)
53 # Remove read-only first
54 readonlydir = os.path.join(fullDstPath, ".git", "objects", "pack")
55 if os.path.exists(readonlydir):
56 shutil.rmtree(readonlydir, onerror = onReadonlyRemoveError )
57 if os.path.exists(fullDstPath):
58 shutil.rmtree(fullDstPath, ignore_errors=False)
60 class SourcePackage (Source):
61 def __init__(self, url, filename, checksum, baseDir, extractDir = "src", postExtract=None):
62 Source.__init__(self, baseDir, extractDir)
64 self.filename = filename
65 self.checksum = checksum
66 self.archiveDir = "packages"
67 self.postExtract = postExtract
73 def update (self, cmdProtocol = None):
74 if not self.isArchiveUpToDate():
75 self.fetchAndVerifyArchive()
77 if self.getExtractedChecksum() != self.checksum:
80 self.storeExtractedChecksum(self.checksum)
82 def removeArchives (self):
83 archiveDir = os.path.join(EXTERNAL_DIR, pkg.baseDir, pkg.archiveDir)
84 if os.path.exists(archiveDir):
85 shutil.rmtree(archiveDir, ignore_errors=False)
87 def isArchiveUpToDate (self):
88 archiveFile = os.path.join(EXTERNAL_DIR, pkg.baseDir, pkg.archiveDir, pkg.filename)
89 if os.path.exists(archiveFile):
90 return computeChecksum(readFile(archiveFile)) == self.checksum
94 def getExtractedChecksumFilePath (self):
95 return os.path.join(EXTERNAL_DIR, pkg.baseDir, pkg.archiveDir, "extracted")
97 def getExtractedChecksum (self):
98 extractedChecksumFile = self.getExtractedChecksumFilePath()
100 if os.path.exists(extractedChecksumFile):
101 return readFile(extractedChecksumFile)
105 def storeExtractedChecksum (self, checksum):
106 checksum_bytes = checksum.encode("utf-8")
107 writeFile(self.getExtractedChecksumFilePath(), checksum_bytes)
109 def connectToUrl (self, url):
112 if sys.version_info < (3, 0):
113 from urllib2 import urlopen
115 from urllib.request import urlopen
118 print("Ignoring certificate checks")
119 ssl_context = ssl._create_unverified_context()
120 result = urlopen(url, context=ssl_context)
122 result = urlopen(url)
126 def fetchAndVerifyArchive (self):
127 print("Fetching %s" % self.url)
129 req = self.connectToUrl(self.url)
131 checksum = computeChecksum(data)
132 dstPath = os.path.join(EXTERNAL_DIR, self.baseDir, self.archiveDir, self.filename)
134 if checksum != self.checksum:
135 raise Exception("Checksum mismatch for %s, expected %s, got %s" % (self.filename, self.checksum, checksum))
137 if not os.path.exists(os.path.dirname(dstPath)):
138 os.mkdir(os.path.dirname(dstPath))
140 writeFile(dstPath, data)
143 print("Extracting %s to %s/%s" % (self.filename, self.baseDir, self.extractDir))
145 srcPath = os.path.join(EXTERNAL_DIR, self.baseDir, self.archiveDir, self.filename)
146 tmpPath = os.path.join(EXTERNAL_DIR, ".extract-tmp-%s" % self.baseDir)
147 dstPath = os.path.join(EXTERNAL_DIR, self.baseDir, self.extractDir)
148 archive = tarfile.open(srcPath)
150 if os.path.exists(tmpPath):
151 shutil.rmtree(tmpPath, ignore_errors=False)
155 archive.extractall(tmpPath)
158 extractedEntries = os.listdir(tmpPath)
159 if len(extractedEntries) != 1 or not os.path.isdir(os.path.join(tmpPath, extractedEntries[0])):
160 raise Exception("%s doesn't contain single top-level directory" % self.filename)
162 topLevelPath = os.path.join(tmpPath, extractedEntries[0])
164 if not os.path.exists(dstPath):
167 for entry in os.listdir(topLevelPath):
168 if os.path.exists(os.path.join(dstPath, entry)):
169 raise Exception("%s exists already" % entry)
171 shutil.move(os.path.join(topLevelPath, entry), dstPath)
173 shutil.rmtree(tmpPath, ignore_errors=True)
175 if self.postExtract != None:
176 self.postExtract(dstPath)
178 class GitRepo (Source):
179 def __init__(self, httpsUrl, sshUrl, revision, baseDir, extractDir = "src", removeTags = []):
180 Source.__init__(self, baseDir, extractDir)
181 self.httpsUrl = httpsUrl
183 self.revision = revision
184 self.removeTags = removeTags
186 def detectProtocol(self, cmdProtocol = None):
187 # reuse parent repo protocol
188 proc = subprocess.Popen(['git', 'ls-remote', '--get-url', 'origin'], stdout=subprocess.PIPE)
189 (stdout, stderr) = proc.communicate()
191 if proc.returncode != 0:
192 raise Exception("Failed to execute 'git ls-remote origin', got %d" % proc.returncode)
193 if (stdout[:3] == 'ssh') or (stdout[:3] == 'git'):
196 # remote 'origin' doesn't exist, assume 'https' as checkout protocol
200 def selectUrl(self, cmdProtocol = None):
202 if cmdProtocol == None:
203 protocol = self.detectProtocol(cmdProtocol)
205 protocol = cmdProtocol
207 # fallback to https on any issues
210 if protocol == 'ssh':
211 if self.sshUrl != None:
214 assert self.httpsUrl != None
217 assert protocol == 'https'
223 def update (self, cmdProtocol = None):
224 fullDstPath = os.path.join(EXTERNAL_DIR, self.baseDir, self.extractDir)
226 url = self.selectUrl(cmdProtocol)
227 if not os.path.exists(fullDstPath):
228 execute(["git", "clone", "--no-checkout", url, fullDstPath])
230 pushWorkingDir(fullDstPath)
232 for tag in self.removeTags:
233 proc = subprocess.Popen(['git', 'tag', '-l', tag], stdout=subprocess.PIPE)
234 (stdout, stderr) = proc.communicate()
235 if proc.returncode == 0:
236 execute(["git", "tag", "-d",tag])
237 execute(["git", "fetch", "--tags", url, "+refs/heads/*:refs/remotes/origin/*"])
238 execute(["git", "checkout", self.revision])
242 def postExtractLibpng (path):
243 shutil.copy(os.path.join(path, "scripts", "pnglibconf.h.prebuilt"),
244 os.path.join(path, "pnglibconf.h"))
248 "http://zlib.net/zlib-1.2.11.tar.gz",
249 "zlib-1.2.11.tar.gz",
250 "c3e5e9fdd5004dcb542feda5ee4f0ff0744628baf8ed2dd5d66f8ca1197cb1a1",
253 "http://prdownloads.sourceforge.net/libpng/libpng-1.6.27.tar.gz",
254 "libpng-1.6.27.tar.gz",
255 "c9d164ec247f426a525a7b89936694aefbc91fb7a50182b198898b8fc91174b4",
257 postExtract = postExtractLibpng),
259 "https://github.com/KhronosGroup/SPIRV-Tools.git",
261 "dd1e837e1ceffbb6445774b4c2ecb18862429ddb",
264 "https://github.com/KhronosGroup/glslang.git",
266 "e9405d0b443a1849fa55b7bfeaceda586a1c37af",
268 removeTags = ['master-tot']),
270 "https://github.com/KhronosGroup/SPIRV-Headers.git",
272 "d5b2e1255f706ce1f88812217e9a554f299848af",
277 versionsForInsecure = ((2,7,9), (3,4,3))
278 versionsForInsecureStr = ' or '.join(('.'.join(str(x) for x in v)) for v in versionsForInsecure)
280 parser = argparse.ArgumentParser(description = "Fetch external sources")
281 parser.add_argument('--clean', dest='clean', action='store_true', default=False,
282 help='Remove sources instead of fetching')
283 parser.add_argument('--insecure', dest='insecure', action='store_true', default=False,
284 help="Disable certificate check for external sources."
285 " Minimum python version required " + versionsForInsecureStr)
286 parser.add_argument('--protocol', dest='protocol', default=None, choices=['ssh', 'https'],
287 help="Select protocol to checkout git repositories.")
289 args = parser.parse_args()
292 for versionItem in versionsForInsecure:
293 if (sys.version_info.major == versionItem[0]):
294 if sys.version_info < versionItem:
295 parser.error("For --insecure minimum required python version is " +
296 versionsForInsecureStr)
301 if __name__ == "__main__":
308 pkg.update(args.protocol)