1e509ee18Sopenharmony_ci#!/usr/bin/env python3
2e509ee18Sopenharmony_ci# -*- coding: utf-8 -*-
3e509ee18Sopenharmony_ci# Copyright (c) 2012 The Chromium Authors. All rights reserved.
4e509ee18Sopenharmony_ci# Use of this source code is governed by a BSD-style license that can be
5e509ee18Sopenharmony_ci# found in the LICENSE file.
6e509ee18Sopenharmony_ci
7e509ee18Sopenharmony_ci"""Prints the lowest locally available SDK version greater than or equal to a
8e509ee18Sopenharmony_cigiven minimum sdk version to standard output. If --developer_dir is passed, then
9e509ee18Sopenharmony_cithe script will use the Xcode toolchain located at DEVELOPER_DIR.
10e509ee18Sopenharmony_ci
11e509ee18Sopenharmony_ciUsage:
12e509ee18Sopenharmony_ci  python find_sdk.py [--developer_dir DEVELOPER_DIR] 10.6  # Ignores SDKs < 10.6
13e509ee18Sopenharmony_ci"""
14e509ee18Sopenharmony_ci
15e509ee18Sopenharmony_ciimport os
16e509ee18Sopenharmony_ciimport re
17e509ee18Sopenharmony_ciimport subprocess
18e509ee18Sopenharmony_ciimport sys
19e509ee18Sopenharmony_ci
20e509ee18Sopenharmony_cifrom optparse import OptionParser
21e509ee18Sopenharmony_ci
22e509ee18Sopenharmony_ci
23e509ee18Sopenharmony_ciclass SdkError(Exception):
24e509ee18Sopenharmony_ci    def __init__(self, value):
25e509ee18Sopenharmony_ci        self.value = value
26e509ee18Sopenharmony_ci
27e509ee18Sopenharmony_ci    def __str__(self):
28e509ee18Sopenharmony_ci        return repr(self.value)
29e509ee18Sopenharmony_ci
30e509ee18Sopenharmony_ci
31e509ee18Sopenharmony_cidef parse_version(version_str):
32e509ee18Sopenharmony_ci    """'10.6' => [10, 6]"""
33e509ee18Sopenharmony_ci    return map(int, re.findall(r'(\d+)', version_str))
34e509ee18Sopenharmony_ci
35e509ee18Sopenharmony_ci
36e509ee18Sopenharmony_cidef main():
37e509ee18Sopenharmony_ci    parser = OptionParser()
38e509ee18Sopenharmony_ci    parser.add_option("--verify",
39e509ee18Sopenharmony_ci                      action="store_true", dest="verify", default=False,
40e509ee18Sopenharmony_ci                      help="return the sdk argument and warn if it doesn't exist")
41e509ee18Sopenharmony_ci    parser.add_option("--sdk_path",
42e509ee18Sopenharmony_ci                      action="store", type="string", dest="sdk_path",
43e509ee18Sopenharmony_ci                      default="",
44e509ee18Sopenharmony_ci                      help="user-specified SDK path; bypasses verification")
45e509ee18Sopenharmony_ci    parser.add_option("--print_sdk_path",
46e509ee18Sopenharmony_ci                      action="store_true", dest="print_sdk_path", default=False,
47e509ee18Sopenharmony_ci                      help="Additionally print the path the SDK (appears first).")
48e509ee18Sopenharmony_ci    parser.add_option("--developer_dir", help='Path to Xcode.')
49e509ee18Sopenharmony_ci    options, args = parser.parse_args()
50e509ee18Sopenharmony_ci    if len(args) != 1:
51e509ee18Sopenharmony_ci        parser.error('Please specify a minimum SDK version')
52e509ee18Sopenharmony_ci    min_sdk_version = args[0]
53e509ee18Sopenharmony_ci
54e509ee18Sopenharmony_ci    if options.developer_dir:
55e509ee18Sopenharmony_ci        os.environ['DEVELOPER_DIR'] = options.developer_dir
56e509ee18Sopenharmony_ci
57e509ee18Sopenharmony_ci    job = subprocess.Popen(['xcode-select', '-print-path'],
58e509ee18Sopenharmony_ci                           stdout=subprocess.PIPE,
59e509ee18Sopenharmony_ci                           stderr=subprocess.STDOUT)
60e509ee18Sopenharmony_ci    out, err = job.communicate()
61e509ee18Sopenharmony_ci    if job.returncode != 0:
62e509ee18Sopenharmony_ci        print(out, file=sys.stderr)
63e509ee18Sopenharmony_ci        print(err, file=sys.stderr)
64e509ee18Sopenharmony_ci        raise Exception('Error %d running xcode-select' % job.returncode)
65e509ee18Sopenharmony_ci    sdk_dir = os.path.join(
66e509ee18Sopenharmony_ci        str(out.rstrip(), encoding="utf-8"),
67e509ee18Sopenharmony_ci        'Platforms/MacOSX.platform/Developer/SDKs')
68e509ee18Sopenharmony_ci    # Xcode must be installed, its license agreement must be accepted, and its
69e509ee18Sopenharmony_ci    # command-line tools must be installed. Stand-alone installations (in
70e509ee18Sopenharmony_ci    # /Library/Developer/CommandLineTools) are not supported.
71e509ee18Sopenharmony_ci    # https://bugs.chromium.org/p/chromium/issues/detail?id=729990#c1
72e509ee18Sopenharmony_ci    file_path = os.path.relpath("/path/to/Xcode.app")
73e509ee18Sopenharmony_ci    if not os.path.isdir(sdk_dir) or not '.app/Contents/Developer' in sdk_dir:
74e509ee18Sopenharmony_ci        raise SdkError('Install Xcode, launch it, accept the license ' +
75e509ee18Sopenharmony_ci                       'agreement, and run `sudo xcode-select -s %s` ' % file_path +
76e509ee18Sopenharmony_ci                       'to continue.')
77e509ee18Sopenharmony_ci    sdks = [re.findall('^MacOSX(1[0,1,2,3,4]\.\d+)\.sdk$', s) for s in
78e509ee18Sopenharmony_ci            os.listdir(sdk_dir)]
79e509ee18Sopenharmony_ci    sdks = [s[0] for s in sdks if s]  # [['10.5'], ['10.6']] => ['10.5', '10.6']
80e509ee18Sopenharmony_ci    sdks = [s for s in sdks  # ['10.5', '10.6'] => ['10.6']
81e509ee18Sopenharmony_ci            if list(parse_version(s)) >= list(parse_version(min_sdk_version))]
82e509ee18Sopenharmony_ci
83e509ee18Sopenharmony_ci    if not sdks:
84e509ee18Sopenharmony_ci        raise Exception('No %s+ SDK found' % min_sdk_version)
85e509ee18Sopenharmony_ci    best_sdk = sorted(sdks)[0]
86e509ee18Sopenharmony_ci
87e509ee18Sopenharmony_ci    if options.verify and best_sdk != min_sdk_version and not options.sdk_path:
88e509ee18Sopenharmony_ci        print('', file=sys.stderr)
89e509ee18Sopenharmony_ci        print('                                           vvvvvvv',
90e509ee18Sopenharmony_ci              file=sys.stderr)
91e509ee18Sopenharmony_ci        print('', file=sys.stderr)
92e509ee18Sopenharmony_ci        print(
93e509ee18Sopenharmony_ci            'This build requires the %s SDK, but it was not found on your system.' \
94e509ee18Sopenharmony_ci            % min_sdk_version, file=sys.stderr)
95e509ee18Sopenharmony_ci        print(
96e509ee18Sopenharmony_ci            'Either install it, or explicitly set mac_sdk in your GYP_DEFINES.',
97e509ee18Sopenharmony_ci            file=sys.stderr)
98e509ee18Sopenharmony_ci        print('', file=sys.stderr)
99e509ee18Sopenharmony_ci        print('                                           ^^^^^^^',
100e509ee18Sopenharmony_ci              file=sys.stderr)
101e509ee18Sopenharmony_ci        print('', file=sys.stderr)
102e509ee18Sopenharmony_ci        sys.exit(1)
103e509ee18Sopenharmony_ci
104e509ee18Sopenharmony_ci    if options.print_sdk_path:
105e509ee18Sopenharmony_ci        _sdk_path = subprocess.check_output(
106e509ee18Sopenharmony_ci            ['xcrun', '-sdk', 'macosx' + best_sdk, '--show-sdk-path']).strip()
107e509ee18Sopenharmony_ci        if isinstance(_sdk_path, bytes):
108e509ee18Sopenharmony_ci            _sdk_path = _sdk_path.decode()
109e509ee18Sopenharmony_ci        print(_sdk_path)
110e509ee18Sopenharmony_ci    return best_sdk
111e509ee18Sopenharmony_ci
112e509ee18Sopenharmony_ci
113e509ee18Sopenharmony_ciif __name__ == '__main__':
114e509ee18Sopenharmony_ci    if sys.platform != 'darwin':
115e509ee18Sopenharmony_ci        raise Exception("This script only runs on Mac")
116e509ee18Sopenharmony_ci    print(main())
117e509ee18Sopenharmony_ci    sys.exit(0)
118