sky_tool 49.3 KB
Newer Older
1 2 3 4 5 6
#!/usr/bin/env python
# Copyright 2015 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

import argparse
7
import atexit
8
import errno
9
import hashlib
10 11
import json
import logging
12
import multiprocessing
13
import os
14
import platform
15
import random
16 17 18 19 20
import re
import signal
import socket
import subprocess
import sys
21
import tempfile
22
import time
23
import urlparse
24

25 26 27
PACKAGES_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
SKY_ENGINE_DIR = os.path.join(PACKAGES_DIR, 'sky_engine')
APK_DIR = os.path.join(os.path.realpath(SKY_ENGINE_DIR), os.pardir, 'apks')
28 29 30

SKY_SERVER_PORT = 9888
OBSERVATORY_PORT = 8181
31
ADB_PATH = 'adb'
Adam Barth's avatar
Adam Barth committed
32
APK_NAME = 'SkyShell.apk'
33
ANDROID_PACKAGE = 'org.domokit.sky.shell'
Adam Barth's avatar
Adam Barth committed
34
ANDROID_COMPONENT = '%s/%s.SkyActivity' % (ANDROID_PACKAGE, ANDROID_PACKAGE)
35
SHA1_PATH = '/sdcard/%s/%s.sha1' % (ANDROID_PACKAGE, APK_NAME)
36

37 38 39
SKY_SHELL_APP_ID = 'com.google.SkyShell'
IOS_APP_NAME = 'SkyShell.app'

40 41
# FIXME: Do we need to look in $DART_SDK?
DART_PATH = 'dart'
42
PUB_PATH = 'pub'
43

44
PID_FILE_PATH = '/tmp/sky_tool.pids'
45 46 47 48 49 50 51
PID_FILE_KEYS = frozenset([
    'remote_sky_server_port',
    'sky_server_pid',
    'sky_server_port',
    'sky_server_root',
])

52
IOS_SIM_PATH = [
53
    os.path.join('/Applications', 'iOS Simulator.app', 'Contents', 'MacOS', 'iOS Simulator')
54 55
]

56 57
XCRUN_PATH = [
    os.path.join('/usr', 'bin', 'env'),
58
    'xcrun',
59 60 61
]

SIMCTL_PATH = XCRUN_PATH + [
62 63 64
    'simctl',
]

65
PLIST_BUDDY_PATH = XCRUN_PATH + [
66 67 68
    'PlistBuddy',
]

69 70 71 72 73 74 75 76

def _port_in_use(port):
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    return sock.connect_ex(('localhost', port)) == 0


def _start_http_server(port, root):
    server_command = [
77
        PUB_PATH, 'run', 'sky_tools:sky_server', str(port),
78
    ]
79
    logging.info(' '.join(server_command))
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133
    return subprocess.Popen(server_command, cwd=root).pid


# This 'strict dictionary' approach is useful for catching typos.
class Pids(object):
    def __init__(self, known_keys, contents=None):
        self._known_keys = known_keys
        self._dict = contents if contents is not None else {}

    def __len__(self):
        return len(self._dict)

    def get(self, key, default=None):
        assert key in self._known_keys, '%s not in known_keys' % key
        return self._dict.get(key, default)

    def __getitem__(self, key):
        assert key in self._known_keys, '%s not in known_keys' % key
        return self._dict[key]

    def __setitem__(self, key, value):
        assert key in self._known_keys, '%s not in known_keys' % key
        self._dict[key] = value

    def __delitem__(self, key):
        assert key in self._known_keys, '%s not in known_keys' % key
        del self._dict[key]

    def __iter__(self):
        return iter(self._dict)

    def __contains__(self, key):
        assert key in self._known_keys, '%s not in allowed_keys' % key
        return key in self._dict

    def clear(self):
        self._dict = {}

    def pop(self, key, default=None):
        assert key in self._known_keys, '%s not in known_keys' % key
        return self._dict.pop(key, default)

    @classmethod
    def read_from(cls, path, known_keys):
        contents = {}
        try:
            with open(path, 'r') as pid_file:
                contents = json.load(pid_file)
        except:
            if os.path.exists(path):
                logging.warn('Failed to read pid file: %s' % path)
        return cls(known_keys, contents)

    def write_to(self, path):
134 135 136 137
        # These keys are required to write a valid file.
        if not self._dict.viewkeys() >= { 'sky_server_pid', 'sky_server_port' }:
            return

138 139 140 141 142 143 144 145 146
        try:
            with open(path, 'w') as pid_file:
                json.dump(self._dict, pid_file, indent=2, sort_keys=True)
        except:
            logging.warn('Failed to write pid file: %s' % path)


def _url_for_path(port, root, path):
    relative_path = os.path.relpath(path, root)
147
    return 'http://localhost:%s/%s' % (port, relative_path)
148 149


150 151 152 153
class SkyLogs(object):
    def add_subparser(self, subparsers):
        logs_parser = subparsers.add_parser('logs',
            help='Show logs for running Sky apps')
154 155
        logs_parser.add_argument('--clear', action='store_true', dest='clear_logs',
            help='Clear log history before reading from logs (currently only implemented for Android)')
156 157 158 159 160 161 162 163 164
        logs_parser.set_defaults(func=self.run)

    def run(self, args, pids):
        android_log_reader = None
        ios_dev_log_reader = None
        ios_sim_log_reader = None

        android = AndroidDevice()
        if android.is_connected():
165
            android_log_reader = android.logs(args.clear_logs)
166 167

        if IOSDevice.is_connected():
168
            ios_dev_log_reader = IOSDevice.logs(args.clear_logs)
169 170

        if IOSSimulator.is_connected():
171
            ios_sim_log_reader = IOSSimulator.logs(args.clear_logs)
172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191

        if android_log_reader is not None:
            try:
                android_log_reader.join()
            except KeyboardInterrupt:
                pass

        if ios_dev_log_reader is not None:
            try:
                ios_dev_log_reader.join()
            except KeyboardInterrupt:
                pass

        if ios_sim_log_reader is not None:
            try:
                ios_sim_log_reader.join()
            except KeyboardInterrupt:
                pass


192 193 194 195 196 197 198 199 200
class InstallSky(object):
    def add_subparser(self, subparsers):
        install_parser = subparsers.add_parser('install',
            help='install SkyShell on Android and iOS devices and simulators')
        install_parser.set_defaults(func=self.run)

    def run(self, args, pids):
        android = AndroidDevice()

201
        installed_somewhere = False
202 203
        # Install on connected Android device
        if android.is_connected() and args.android_build_available:
204
            installed_somewhere = installed_somewhere or android.install_apk(android.get_apk_path(args))
205 206 207

        # Install on connected iOS device
        if IOSDevice.is_connected() and args.ios_build_available:
208
            installed_somewhere = installed_somewhere or IOSDevice.install_app(IOSDevice.get_app_path(args))
209 210 211

        # Install on iOS simulator if it's running
        if IOSSimulator.is_booted() and args.ios_sim_build_available:
212 213 214 215 216 217
            installed_somewhere = installed_somewhere or IOSSimulator.fork_install_app(IOSSimulator.get_app_path(args))

        if installed_somewhere:
            return 0
        else:
            return 2
218 219 220 221 222 223

    # TODO(iansf): get rid of need for args
    def needs_install(self, args):
        return AndroidDevice().needs_install(args) or IOSDevice.needs_install(args) or IOSSimulator.needs_install(args)


224 225 226 227
class StartSky(object):
    def add_subparser(self, subparsers):
        start_parser = subparsers.add_parser('start',
            help='launch %s on the device' % APK_NAME)
228
        start_parser.add_argument('--poke', action='store_true')
229
        start_parser.add_argument('--checked', action='store_true')
230 231 232 233 234
        start_parser.add_argument('project_or_path', nargs='?', type=str,
            default='.')
        start_parser.set_defaults(func=self.run)

    def run(self, args, pids):
235
        started_sky_somewhere = False
236 237
        if not args.poke:
            StopSky().run(args, pids)
238

239 240 241
            # Only install if the user did not specify a poke
            installer = InstallSky()
            if installer.needs_install(args):
242
                started_sky_somewhere = (installer.run(args, pids) == 0)
243

244 245 246 247 248
        project_or_path = os.path.abspath(args.project_or_path)

        if os.path.isdir(project_or_path):
            sky_server_root = project_or_path
            main_dart = os.path.join(project_or_path, 'lib', 'main.dart')
249
            missing_msg = 'Missing lib/main.dart in project: %s' % project_or_path
250
        else:
251
            sky_server_root = os.getcwd()
252
            main_dart = project_or_path
253
            missing_msg = '%s does not exist.' % main_dart
254 255

        if not os.path.isfile(main_dart):
256
            logging.error(missing_msg)
257 258 259 260
            return 2

        package_root = os.path.join(sky_server_root, 'packages')
        if not os.path.isdir(package_root):
261
            logging.error('%s is not a valid packages path.' % package_root)
262 263
            return 2

264
        android = AndroidDevice()
265
        # TODO(iansf): fix this so that we don't have to pass sky_server_root, main_dart, pid, and args.
266 267 268 269 270 271
        started_sky_on_android = android.setup_servers(sky_server_root, main_dart, pids, args)

        if started_sky_somewhere or started_sky_on_android:
            return 0
        else:
            return 2
272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315


class StopSky(object):
    def add_subparser(self, subparsers):
        stop_parser = subparsers.add_parser('stop',
            help=('kill all running SkyShell.apk processes'))
        stop_parser.set_defaults(func=self.run)

    def _run(self, args):
        with open('/dev/null', 'w') as dev_null:
            logging.info(' '.join(args))
            subprocess.call(args, stdout=dev_null, stderr=dev_null)

    def run(self, args, pids):
        self._run(['fuser', '-k', '%s/tcp' % SKY_SERVER_PORT])

        if 'remote_sky_server_port' in pids:
            port_string = 'tcp:%s' % pids['remote_sky_server_port']
            self._run([AndroidDevice().adb_path, 'reverse', '--remove', port_string])

        self._run([AndroidDevice().adb_path, 'shell', 'am', 'force-stop', ANDROID_PACKAGE])

        pids.clear()

class AndroidDevice(object):
    # _state used in this manner gives a simple way to treat AndroidDevice
    # as a singleton while easily allowing subclassing for mocks.  All
    # AndroidDevices created in a given session will share the same state.
    _state = {}
    def __init__(self):
        self.__dict__ = AndroidDevice._state
        self._update_paths()

        # Checking for lollipop only needs to be done if we are starting an
        # app, but it has an important side effect, which is to discard any
        # progress messages if the adb server is restarted.
        self._check_for_adb()
        self._check_for_lollipop_or_later()

    def _update_paths(self):
        if 'adb_path' in self.__dict__:
            return
        if 'ANDROID_HOME' in os.environ:
            android_home_dir = os.environ['ANDROID_HOME']
316 317 318 319 320 321 322 323 324
            adb_location1 = os.path.join(android_home_dir, 'sdk', 'platform-tools', 'adb')
            adb_location2 = os.path.join(android_home_dir, 'platform-tools', 'adb')
            if os.path.exists(adb_location1):
                self.adb_path = adb_location1
            elif os.path.exists(adb_location2):
                self.adb_path = adb_location2
            else:
                logging.warning('"adb" not found at\n  "%s" or\n  "%s"\nusing default path "%s"' % (adb_location1, adb_location2, ADB_PATH))
                self.adb_path = ADB_PATH
325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414
        else:
            self.adb_path = ADB_PATH

    def _is_valid_adb_version(self, adb_version):
        # Sample output: 'Android Debug Bridge version 1.0.31'
        version_fields = re.search('(\d+)\.(\d+)\.(\d+)', adb_version)
        if version_fields:
            major_version = int(version_fields.group(1))
            minor_version = int(version_fields.group(2))
            patch_version = int(version_fields.group(3))
            if major_version > 1:
                return True
            if major_version == 1 and minor_version > 0:
                return True
            if major_version == 1 and minor_version == 0 and patch_version >= 32:
                return True
            return False
        else:
            logging.warn('Unrecognized adb version string. Skipping version check.')
            return True

    def _check_for_adb(self):
        if 'has_valid_adb' in self.__dict__:
            return
        try:
            cmd = [self.adb_path, 'version']
            logging.info(' '.join(cmd))
            adb_version = subprocess.check_output(cmd)
            if self._is_valid_adb_version(adb_version):
                self.has_valid_adb = True
                return

            cmd = ['which', ADB_PATH]
            logging.info(' '.join(cmd))
            adb_path = subprocess.check_output(cmd).rstrip()
            logging.error('"%s" is too old. Need 1.0.32 or later. '
                'Try setting ANDROID_HOME to use Android builds. Android builds are unavailable.' % adb_path)
            self.has_valid_adb = False
        except OSError:
            logging.warning('"adb" (from the Android SDK) not in $PATH, Android builds are unavailable.')
            self.has_valid_adb = False

    def _check_for_lollipop_or_later(self):
        if 'has_valid_android' in self.__dict__:
            return
        try:
            # If the server is automatically restarted, then we get irrelevant
            # output lines like this, which we want to ignore:
            #   adb server is out of date.  killing..
            #   * daemon started successfully *
            cmd = [self.adb_path, 'start-server']
            logging.info(' '.join(cmd))
            subprocess.call(cmd)

            cmd = [self.adb_path, 'shell', 'getprop', 'ro.build.version.sdk']
            logging.info(' '.join(cmd))
            sdk_version = subprocess.check_output(cmd).rstrip()
            # Sample output: '22'
            if not sdk_version.isdigit():
                logging.error('Unexpected response from getprop: "%s".' % sdk_version)
                self.has_valid_android = False
                return

            if int(sdk_version) < 22:
                logging.error('Version "%s" of the Android SDK is too old. '
                              'Need Lollipop (22) or later. ' % sdk_version)
                self.has_valid_android = False
                return
        except subprocess.CalledProcessError as e:
            # adb printed the error, so we print nothing.
            self.has_valid_android = False
            return
        self.has_valid_android = True

    def is_package_installed(self, package_name):
        if not self.is_connected():
            return False
        pm_path_cmd = [self.adb_path, 'shell', 'pm', 'path', package_name]
        logging.info(' '.join(pm_path_cmd))
        return subprocess.check_output(pm_path_cmd).strip() != ''

    def get_device_apk_sha1(self, apk_path):
        # We might need to install a new APK, so check SHA1
        cmd = [self.adb_path, 'shell', 'cat', SHA1_PATH]
        logging.info(' '.join(cmd))
        return subprocess.check_output(cmd)

    def get_source_sha1(self, apk_path):
        return hashlib.sha1(open(apk_path, 'rb').read()).hexdigest()

415 416 417 418
    # TODO(iansf): get rid of need for args
    def get_apk_path(self, args):
        if args.android_build_available and args.use_release:
            return os.path.join(os.path.normpath(args.sky_src_path), args.android_release_build_path, 'apks', APK_NAME)
419
        elif args.android_build_available and args.local_build:
420 421 422 423
            return os.path.join(os.path.normpath(args.sky_src_path), args.android_debug_build_path, 'apks', APK_NAME)
        else:
            return os.path.join(APK_DIR, APK_NAME)

424 425 426
    def is_connected(self):
        return self.has_valid_android

427 428 429 430 431 432 433 434 435 436 437
    def needs_install(self, args):
        apk_path = self.get_apk_path(args)

        if not self.is_package_installed(ANDROID_PACKAGE):
            logging.info('%s is not on the device. Installing now...' % APK_NAME)
            return True
        elif self.get_device_apk_sha1(apk_path) != self.get_source_sha1(apk_path):
            logging.info('%s on the device is out of date. Installing now...' % APK_NAME)
            return True
        return False

438 439 440
    def install_apk(self, apk_path):
        if not os.path.exists(apk_path):
            logging.error('"%s" does not exist.' % apk_path)
441
            return False
442 443 444 445 446 447 448 449 450 451 452 453

        cmd = [self.adb_path, 'install', '-r', apk_path]
        logging.info(' '.join(cmd))
        subprocess.check_call(cmd)
        # record the SHA1 of the APK we just pushed
        with tempfile.NamedTemporaryFile() as fp:
            fp.write(self.get_source_sha1(apk_path))
            fp.seek(0)
            cmd = [self.adb_path, 'push', fp.name, SHA1_PATH]
            logging.info(' '.join(cmd))
            subprocess.check_call(cmd)

454 455 456
        return True


457 458 459
    # TODO(iansf): refactor setup_servers
    def setup_servers(self, sky_server_root, main_dart, pids, args):
        if not self.is_connected():
460
            return False
461

462 463
        # Set up port forwarding for observatory
        observatory_port_string = 'tcp:%s' % OBSERVATORY_PORT
464
        cmd = [
465
            self.adb_path,
466 467 468 469 470 471
            'forward',
            observatory_port_string,
            observatory_port_string
        ]
        logging.info(' '.join(cmd))
        subprocess.check_call(cmd)
472 473 474 475

        sky_server_port = SKY_SERVER_PORT
        pids['sky_server_port'] = sky_server_port
        if _port_in_use(sky_server_port):
476
            logging.info(('Port %s already in use. '
477 478 479 480 481 482 483
            ' Not starting server for %s') % (sky_server_port, sky_server_root))
        else:
            sky_server_pid = _start_http_server(sky_server_port, sky_server_root)
            pids['sky_server_pid'] = sky_server_pid
            pids['sky_server_root'] = sky_server_root

        port_string = 'tcp:%s' % sky_server_port
484
        cmd = [
485
            self.adb_path,
486 487 488 489 490 491
            'reverse',
            port_string,
            port_string
        ]
        logging.info(' '.join(cmd))
        subprocess.check_call(cmd)
492 493 494
        pids['remote_sky_server_port'] = sky_server_port

        # The load happens on the remote device, use the remote port.
495
        url = _url_for_path(pids['remote_sky_server_port'], sky_server_root,
496
            main_dart)
497 498
        if args.poke:
            url += '?rand=%s' % random.random()
499

500
        cmd = [
501
            self.adb_path, 'shell',
502 503
            'am', 'start',
            '-a', 'android.intent.action.VIEW',
504
            '-d', url,
505 506 507
        ]

        if args.checked:
508
            cmd += ['--ez', 'enable-checked-mode', 'true']
509

510
        cmd += [ANDROID_COMPONENT]
511
        logging.info(' '.join(cmd))
512
        subprocess.check_output(cmd)
513

514 515
        return True

516
    def logs(self, clear=False):
517
        def do_logs():
518 519 520 521 522 523 524 525 526
            if clear:
                cmd = [
                    self.adb_path,
                    'logcat',
                    '-c'
                ]
                logging.info(' '.join(cmd))
                subprocess.check_call(cmd)

527 528 529
            cmd = [
                self.adb_path,
                'logcat',
530 531
                '-v',
                'tag', # Only log the tag and the message
532 533 534 535 536 537 538 539
                '-s',
                'sky',
                'chromium',
            ]
            logging.info(' '.join(cmd))
            log_process = subprocess.Popen(cmd, bufsize=1, stdout=subprocess.PIPE)
            while True:
                try:
540 541 542 543 544 545
                    log_line = log_process.stdout.readline()
                    if log_line == '':
                        if log_process.poll() != None:
                            logging.error('The Android logging process has quit unexpectedly. Please call the "logs" command again.')
                            break
                    sys.stdout.write('ANDROID: ' + log_line)
546 547 548 549 550 551 552
                    sys.stdout.flush()
                except KeyboardInterrupt:
                    break
        log_reader = multiprocessing.Process(target=do_logs)
        log_reader.daemon = True
        log_reader.start()
        return log_reader
553 554


555 556 557 558 559 560
class IOSDevice(object):
    _has_ios_deploy = None
    @classmethod
    def has_ios_deploy(cls):
        if cls._has_ios_deploy is not None:
            return cls._has_ios_deploy
561 562 563 564 565
        try:
            cmd = [
                'which',
                'ios-deploy'
            ]
566
            logging.info(' '.join(cmd))
567 568 569 570 571
            out = subprocess.check_output(cmd)
            match = re.search(r'ios-deploy', out)
            cls._has_ios_deploy = match is not None
        except subprocess.CalledProcessError:
            cls._has_ios_deploy = False
572 573 574 575 576 577 578 579 580
        return cls._has_ios_deploy

    _is_connected = False
    @classmethod
    def is_connected(cls):
        if not cls.has_ios_deploy():
            return False
        if cls._is_connected:
            return True
581 582 583 584 585 586 587 588 589 590 591 592 593
        try:
            cmd = [
                'ios-deploy',
                '--detect',
                '--timeout',
                '1'
            ]
            logging.info(' '.join(cmd))
            out = subprocess.check_output(cmd)
            match = re.search(r'\[\.\.\.\.\] Found [^\)]*\) connected', out)
            cls._is_connected = match is not None
        except subprocess.CalledProcessError:
            cls._is_connected = False
594 595
        return cls._is_connected

596 597 598 599 600 601 602
    @classmethod
    def get_app_path(cls, args):
        if args.use_release:
            return os.path.join(args.sky_src_path, args.ios_release_build_path, IOS_APP_NAME)
        else:
            return os.path.join(args.sky_src_path, args.ios_debug_build_path, IOS_APP_NAME)

603 604 605 606
    @classmethod
    def needs_install(cls, args):
        return cls.is_connected()

607 608 609
    @classmethod
    def install_app(cls, ios_app_path):
        if not cls.has_ios_deploy():
610
            return False
611 612 613 614 615 616 617 618 619 620 621 622
        try:
            cmd = [
                'ios-deploy',
                '--justlaunch',
                '--timeout',
                '10', # Smaller timeouts cause it to exit before having launched the app
                '--bundle',
                ios_app_path
            ]
            logging.info(' '.join(cmd))
            subprocess.check_call(cmd)
        except subprocess.CalledProcessError:
623 624
            return False
        return True
625 626 627 628 629

    @classmethod
    def copy_file(cls, bundle_id, local_path, device_path):
        if not cls.has_ios_deploy():
            return
630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645
        try:
            cmd = [
                'ios-deploy',
                '-t',
                '1',
                '--bundle_id',
                bundle_id,
                '--upload',
                local_path,
                '--to',
                device_path
            ]
            logging.info(' '.join(cmd))
            subprocess.check_call(cmd)
        except subprocess.CalledProcessError:
            pass
646

647
    @classmethod
648
    def logs(cls, clear=False):
649 650 651 652 653 654 655 656 657 658 659
        try:
            cmd = [
                'which',
                'idevicesyslog'
            ]
            logging.info(' '.join(cmd))
            subprocess.check_call(cmd)
        except subprocess.CalledProcessError:
            logging.error('"log" command only works with iOS devices if you have installed idevicesyslog. Run "brew install libimobiledevice" to install it with homebrew.')
            return None

660 661 662 663 664 665 666 667 668
        def do_logs():
            cmd = [
                'idevicesyslog',
            ]
            logging.info(' '.join(cmd))
            log_process = subprocess.Popen(cmd, stdout=subprocess.PIPE)
            while True:
                try:
                    log_line = log_process.stdout.readline()
669 670 671 672
                    if log_line == '':
                        if log_process.poll() != None:
                            logging.error('The iOS logging process has quit unexpectedly. Please call the "logs" command again.')
                            break
673 674 675 676 677 678 679 680 681 682
                    if re.match(r'.*SkyShell.*', log_line) is not None:
                        sys.stdout.write('IOS DEV: ' + log_line)
                        sys.stdout.flush()
                except KeyboardInterrupt:
                    break
        log_reader = multiprocessing.Process(target=do_logs)
        log_reader.daemon = True
        log_reader.start()
        return log_reader

683 684 685 686

class IOSSimulator(object):
    @classmethod
    def is_booted(cls):
687 688
        if platform.system() != 'Darwin':
            return False
689 690
        return cls.get_simulator_device_id() is not None

691 692 693 694
    @classmethod
    def is_connected(cls):
        return cls.is_booted()

695 696 697 698 699
    _device_id = None
    @classmethod
    def get_simulator_device_id(cls):
        if cls._device_id is not None:
            return cls._device_id
700
        cmd = SIMCTL_PATH + [
701 702 703
            'list',
            'devices',
        ]
704
        logging.info(' '.join(cmd))
705 706 707 708 709 710
        out = subprocess.check_output(cmd)
        match = re.search(r'[^\(]+\(([^\)]+)\) \(Booted\)', out)
        if match is not None and match.group(1) is not None:
            cls._device_id = match.group(1)
            return cls._device_id
        else:
711
            logging.info('No running simulators found')
712 713 714 715 716 717 718 719 720 721 722
            # TODO: Maybe start the simulator?
            return None
        if err is not None:
            print(err)
            exit(-1)

    _simulator_path = None
    @classmethod
    def get_simulator_path(cls):
        if cls._simulator_path is not None:
            return cls._simulator_path
723
        home_dir = os.path.expanduser('~')
724 725 726 727 728 729 730 731 732 733 734 735 736 737 738
        device_id = cls.get_simulator_device_id()
        if device_id is None:
            # TODO: Maybe start the simulator?
            return None
        cls._simulator_path = os.path.join(home_dir, 'Library', 'Developer', 'CoreSimulator', 'Devices', device_id)
        return cls._simulator_path

    _simulator_app_id = None
    @classmethod
    def get_simulator_app_id(cls):
        if cls._simulator_app_id is not None:
            return cls._simulator_app_id
        simulator_path = cls.get_simulator_path()
        cmd = [
            'find',
739
            os.path.join(simulator_path, 'data', 'Containers', 'Data', 'Application'),
740 741 742
            '-name',
            SKY_SHELL_APP_ID
        ]
743
        logging.info(' '.join(cmd))
744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770
        out = subprocess.check_output(cmd)
        match = re.search(r'Data\/Application\/([^\/]+)\/Documents\/' + SKY_SHELL_APP_ID, out)
        if match is not None and match.group(1) is not None:
            cls._simulator_app_id = match.group(1)
            return cls._simulator_app_id
        else:
            logging.warning(SKY_SHELL_APP_ID + ' is not installed on the simulator')
            # TODO: Maybe install the app?
            return None
        if err is not None:
            print(err)
            exit(-1)

    _simulator_app_documents_dir = None
    @classmethod
    def get_simulator_app_documents_dir(cls):
        if cls._simulator_app_documents_dir is not None:
            return cls._simulator_app_documents_dir
        if not cls.is_booted():
            return None
        simulator_path = cls.get_simulator_path()
        simulator_app_id = cls.get_simulator_app_id()
        if simulator_app_id is None:
            return None
        cls._simulator_app_documents_dir = os.path.join(simulator_path, 'data', 'Containers', 'Data', 'Application', simulator_app_id, 'Documents')
        return cls._simulator_app_documents_dir

771 772 773 774 775 776 777
    @classmethod
    def get_app_path(cls, args):
        if args.use_release:
            return os.path.join(args.sky_src_path, args.ios_sim_release_build_path, IOS_APP_NAME)
        else:
            return os.path.join(args.sky_src_path, args.ios_sim_debug_build_path, IOS_APP_NAME)

778 779 780 781
    @classmethod
    def needs_install(cls, args):
        return cls.is_booted()

782
    @classmethod
783
    def logs(cls, clear=False):
784 785 786 787 788 789 790 791 792 793 794
        def do_logs():
            cmd = [
                'tail',
                '-f',
                os.path.expanduser('~/Library/Logs/CoreSimulator/' + cls.get_simulator_device_id() + '/system.log'),
            ]
            logging.info(' '.join(cmd))
            log_process = subprocess.Popen(cmd, stdout=subprocess.PIPE)
            while True:
                try:
                    log_line = log_process.stdout.readline()
795 796 797 798
                    if log_line == '':
                        if log_process.poll() != None:
                            logging.error('The iOS Simulator logging process has quit unexpectedly. Please call the "logs" command again.')
                            break
799 800 801 802 803 804 805 806 807 808
                    if re.match(r'.*SkyShell.*', log_line) is not None:
                        sys.stdout.write('IOS SIM: ' + log_line)
                        sys.stdout.flush()
                except KeyboardInterrupt:
                    break
        log_reader = multiprocessing.Process(target=do_logs)
        log_reader.daemon = True
        log_reader.start()
        return log_reader

809 810
    @classmethod
    def fork_install_app(cls, ios_app_path):
811 812 813 814 815 816 817 818 819 820 821 822 823
        try:
            cmd = [
                os.path.abspath(__file__),
                'ios_sim',
                '-p',
                ios_app_path,
                'launch'
            ]
            logging.info(' '.join(cmd))
            subprocess.check_call(cmd)
            return True
        except subprocess.CalledProcessError:
            return False
824

825 826 827 828 829 830 831 832 833 834 835
    def _process_args(self, args):
        if args.ios_sim_build_path is None:
            if args.ios_sim_build_available:
                if args.use_release:
                    args.ios_sim_build_path = os.path.join(args.sky_src_path, args.ios_sim_release_build_path, IOS_APP_NAME)
                elif args.local_build:
                    args.ios_sim_build_path = os.path.join(args.sky_src_path, args.ios_sim_debug_build_path, IOS_APP_NAME)
        if args.ios_sim_build_path is None:
            logging.error('ios_sim commands require a valid -p argument if not using the --release or --local-build global arguments')
            sys.exit(2)

836
    def get_application_identifier(self, path):
837 838 839 840 841 842 843 844
        cmd = PLIST_BUDDY_PATH + [
            '-c',
            'Print CFBundleIdentifier',
            os.path.join(path, 'Info.plist')
        ]
        logging.info(' '.join(cmd))
        identifier = subprocess.check_output(cmd)
        return identifier.strip()
845 846

    def is_simulator_booted(self):
847 848 849 850 851 852 853
        cmd = SIMCTL_PATH + [ 'list', 'devices' ]
        logging.info(' '.join(cmd))
        devices = subprocess.check_output(cmd).strip().split('\n')
        for device in devices:
            if re.search(r'\(Booted\)', device):
                return True
        return False
854 855 856

    # Launch whatever simulator the user last used, rather than try to guess which of their simulators they might want to use
    def boot_simulator(self, args, pids):
857 858
        # Guarantee that the args get processed, since all of the commands funnel through here.
        self._process_args(args)
859 860 861 862 863 864 865 866 867 868 869 870
        if self.is_simulator_booted():
            return
        # Use Popen here because launching the simulator from the command line in this manner doesn't return, so we can't check the result.
        if args.ios_sim_path:
            logging.info(args.ios_sim_path)
            subprocess.Popen(args.ios_sim_path)
        else:
            logging.info(IOS_SIM_PATH)
            subprocess.Popen(IOS_SIM_PATH)
        while not self.is_simulator_booted():
            print('Waiting for iOS Simulator to boot...')
            time.sleep(0.5)
871 872

    def install_app(self, args, pids):
873 874 875 876
        self.boot_simulator(args, pids)
        cmd = SIMCTL_PATH + [
            'install',
            'booted',
877
            args.ios_sim_build_path,
878 879 880
        ]
        logging.info(' '.join(cmd))
        return subprocess.check_call(cmd)
881 882

    def install_launch_and_wait(self, args, pids, wait):
883 884 885
        res = self.install_app(args, pids)
        if res != 0:
            return res
886
        identifier = self.get_application_identifier(args.ios_sim_build_path)
887 888 889 890 891 892 893 894 895 896 897 898 899
        launch_args = SIMCTL_PATH + ['launch']
        if wait:
            launch_args += [ '-w' ]
        launch_args += [
            'booted',
            identifier,
            '-target',
            args.target,
            '-server',
            args.server
        ]
        logging.info(' '.join(launch_args))
        return subprocess.check_output(launch_args).strip()
900 901

    def launch_app(self, args, pids):
902
        self.install_launch_and_wait(args, pids, False)
903 904

    def debug_app(self, args, pids):
905 906 907 908 909 910 911 912 913 914 915 916
        launch_res = self.install_launch_and_wait(args, pids, True)
        launch_pid = re.search('.*: (\d+)', launch_res).group(1)
        cmd = XCRUN_PATH + [
            'lldb',
            # TODO(iansf): get this working again
            # '-s',
            # os.path.join(os.path.dirname(__file__), 'lldb_start_commands.txt'),
            '-p',
            launch_pid,
        ]
        logging.info(' '.join(cmd))
        return subprocess.call(cmd)
917 918 919 920 921 922

    def add_subparser(self, subparsers):
        simulator_parser = subparsers.add_parser('ios_sim',
            help='A script that launches an'
                 ' application in the simulator and attaches'
                 ' the debugger to it.')
923 924 925 926 927
        simulator_parser.add_argument('-p', dest='ios_sim_build_path', required=False,
            help='Path to the simulator app build. Defaults to values specified by '
                 'the sky_src_path and ios_sim_[debug|release]_build_path parameters, '
                 'which are normally specified by using the local-build or release '
                 'parameters. Not normally required.')
928 929
        simulator_parser.add_argument('-t', dest='target', required=False,
            default='examples/demo_launcher/lib/main.dart',
930
            help='Sky server-relative path to the Sky app to run. Not normally required.')
931 932
        simulator_parser.add_argument('-s', dest='server', required=False,
            default='localhost:8080',
933
            help='Sky server address. Not normally required.')
934 935 936 937 938 939 940
        simulator_parser.add_argument('--ios_sim_path', dest='ios_sim_path',
            help='Path to your iOS Simulator executable. '
                 'Not normally required.')

        subparsers = simulator_parser.add_subparsers()
        install_parser = subparsers.add_parser('install', help='Install app')
        install_parser.set_defaults(func=self.install_app)
941 942 943
        launch_parser = subparsers.add_parser('launch', help='Launch app. Automatically installs.')
        launch_parser.set_defaults(func=self.launch_app)
        debug_parser = subparsers.add_parser('debug', help='Debug app. Automatically installs and launches.')
944 945 946 947
        debug_parser.set_defaults(func=self.debug_app)


class StartListening(object):
948 949 950
    def __init__(self):
        self.watch_cmd = None

951 952 953 954 955
    def add_subparser(self, subparsers):
        listen_parser = subparsers.add_parser('listen',
            help=('Listen for changes to files and reload the running app on all connected devices'))
        listen_parser.set_defaults(func=self.run)

956 957 958 959 960 961 962 963 964
    def watch_dir(self, directory):
        if self.watch_cmd is None:
            name = platform.system()
            if name == 'Linux':
                try:
                    cmd = [
                        'which',
                        'inotifywait'
                    ]
965
                    logging.info(' '.join(cmd))
966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983
                    out = subprocess.check_output(cmd)
                except subprocess.CalledProcessError:
                    logging.error('"listen" command is only useful if you have installed inotifywait on Linux.  Run "apt-get install inotify-tools" or equivalent to install it.')
                    return False

                self.watch_cmd = [
                    'inotifywait',
                    '-r',
                    '-e',
                    'modify,close_write,move,create,delete', # Only listen for events that matter, to avoid triggering constantly from the editor watching files
                    directory
                ]
            elif name == 'Darwin':
                try:
                    cmd = [
                        'which',
                        'fswatch'
                    ]
984
                    logging.info(' '.join(cmd))
985 986 987 988 989 990 991 992 993 994 995 996 997 998 999
                    out = subprocess.check_output(cmd)
                except subprocess.CalledProcessError:
                    logging.error('"listen" command is only useful if you have installed fswatch on Mac.  Run "brew install fswatch" to install it with homebrew.')
                    return False

                self.watch_cmd = [
                    'fswatch',
                    '-r',
                    '-v',
                    '-1',
                    directory
                ]
            else:
                logging.error('"listen" command is only available on Mac and Linux.')
                return False
1000

1001
        logging.info(' '.join(self.watch_cmd))
1002 1003 1004 1005
        subprocess.check_call(self.watch_cmd)
        return True

    def run(self, args, pids):
1006 1007 1008 1009 1010
        if args.use_release:
            logging.info('Note that the listen command is not compatible with the '
                         'release flag for iOS and iOS simulator builds. If you have '
                         'installed iOS release builds, your Sky app will fail to '
                         'reload while using listen.')
1011 1012
        tempdir = tempfile.mkdtemp()
        currdir = os.getcwd()
1013 1014 1015 1016 1017 1018 1019 1020 1021 1022
        while True:
            logging.info('Updating running Sky apps...')

            # Restart the app on Android.  Android does not currently restart using skyx files.
            cmd = [
                sys.executable,
                os.path.abspath(__file__),
                'start',
                '--poke'
            ]
1023
            logging.info(' '.join(cmd))
1024 1025
            subprocess.check_call(cmd)

1026
            if args.local_build:
1027 1028 1029
                # Currently sending to iOS only works if you are building Sky locally
                # since we aren't shipping the sky_snapshot binary yet.

1030 1031 1032 1033 1034 1035
                # Check if we can make a snapshot
                sky_snapshot_path = None
                if args.ios_sim_build_available:
                    sky_snapshot_path = os.path.join(args.sky_src_path, args.ios_sim_debug_build_path, 'clang_x64', 'sky_snapshot')
                elif args.ios_build_available:
                    sky_snapshot_path = os.path.join(args.sky_src_path, args.ios_debug_build_path, 'clang_x64', 'sky_snapshot')
1036

1037 1038 1039 1040 1041 1042 1043 1044
                if sky_snapshot_path is not None:
                    # If we can make a snapshot, do so and then send it to running iOS instances
                    cmd = [
                        sky_snapshot_path,
                        '--package-root=packages',
                        '--snapshot=' + os.path.join(tempdir, 'snapshot_blob.bin'),
                        os.path.join('lib', 'main.dart')
                    ]
1045
                    logging.info(' '.join(cmd))
1046
                    subprocess.check_call(cmd)
1047

1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058
                    os.chdir(tempdir)
                    # Turn the snapshot into an app.skyx file
                    cmd = [
                        'zip',
                        '-r',
                        'app.skyx',
                        'snapshot_blob.bin',
                        'action',
                        'content',
                        'navigation'
                    ]
1059
                    logging.info(' '.join(cmd))
1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070
                    subprocess.check_call(cmd)
                    os.chdir(currdir)

                    # Copy the app.skyx to the running simulator
                    simulator_app_documents_dir = IOSSimulator.get_simulator_app_documents_dir()
                    if simulator_app_documents_dir is not None:
                        cmd = [
                            'cp',
                            os.path.join(tempdir, 'app.skyx'),
                            simulator_app_documents_dir
                        ]
1071
                        logging.info(' '.join(cmd))
1072 1073 1074 1075 1076
                        subprocess.check_call(cmd)

                    # Copy the app.skyx to the attached iOS device
                    if IOSDevice.is_connected():
                        IOSDevice.copy_file(SKY_SHELL_APP_ID, os.path.join(tempdir, 'app.skyx'), 'Documents/app.skyx')
1077

1078 1079 1080 1081
            # Watch filesystem for changes
            if not self.watch_dir(currdir):
                return

1082

1083 1084 1085 1086 1087 1088 1089
class StartTracing(object):
    def add_subparser(self, subparsers):
        start_tracing_parser = subparsers.add_parser('start_tracing',
            help=('start tracing a running sky instance'))
        start_tracing_parser.set_defaults(func=self.run)

    def run(self, args, pids):
1090 1091 1092 1093 1094 1095 1096 1097 1098 1099
        cmd = [
            ADB_PATH,
            'shell',
            'am',
            'broadcast',
            '-a',
            'org.domokit.sky.shell.TRACING_START'
        ]
        logging.info(' '.join(cmd))
        subprocess.check_output(cmd)
1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112


TRACE_COMPLETE_REGEXP = re.compile('Trace complete')
TRACE_FILE_REGEXP = re.compile(r'Saving trace to (?P<path>\S+)')


class StopTracing(object):
    def add_subparser(self, subparsers):
        stop_tracing_parser = subparsers.add_parser('stop_tracing',
            help=('stop tracing a running sky instance'))
        stop_tracing_parser.set_defaults(func=self.run)

    def run(self, args, pids):
1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127
        cmd = [ADB_PATH, 'logcat', '-c']
        logging.info(' '.join(cmd))
        subprocess.check_output(cmd)

        cmd = [
            ADB_PATH,
            'shell',
            'am',
            'broadcast',
            '-a',
            'org.domokit.sky.shell.TRACING_STOP'
        ]
        logging.info(' '.join(cmd))
        subprocess.check_output(cmd)

1128 1129 1130 1131
        device_path = None
        is_complete = False
        while not is_complete:
            time.sleep(0.2)
1132 1133 1134
            cmd = [ADB_PATH, 'logcat', '-d']
            logging.info(' '.join(cmd))
            log = subprocess.check_output(cmd)
1135 1136 1137 1138 1139 1140
            if device_path is None:
                result = TRACE_FILE_REGEXP.search(log)
                if result:
                    device_path = result.group('path')
            is_complete = TRACE_COMPLETE_REGEXP.search(log) is not None

1141
        logging.info('Downloading trace %s ...' % os.path.basename(device_path))
1142 1143

        if device_path:
1144 1145 1146
            cmd = [ADB_PATH, 'root']
            logging.info(' '.join(cmd))
            output = subprocess.check_output(cmd)
Ian Fischer's avatar
Ian Fischer committed
1147
            match = re.match(r'.*cannot run as root.*', output)
1148 1149 1150 1151 1152 1153
            if match is not None:
                logging.error('Unable to download trace file %s\n'
                              'You need to be able to run adb as root '
                              'on your android device' % device_path)
                return 2

1154 1155 1156 1157 1158 1159 1160
            cmd = [ADB_PATH, 'pull', device_path]
            logging.info(' '.join(cmd))
            subprocess.check_output(cmd)

            cmd = [ADB_PATH, 'shell', 'rm', device_path]
            logging.info(' '.join(cmd))
            subprocess.check_output(cmd)
1161 1162 1163 1164 1165


class SkyShellRunner(object):
    def _check_for_dart(self):
        try:
1166 1167 1168
            cmd = [DART_PATH, '--version']
            logging.info(' '.join(cmd))
            subprocess.check_output(cmd, stderr=subprocess.STDOUT)
1169
        except OSError:
1170
            logging.error('"dart" (from the Dart SDK) not in $PATH, cannot continue.')
1171 1172 1173 1174
            return False
        return True

    def main(self):
1175
        logging.basicConfig(format='%(levelname)s: %(message)s', level=logging.WARNING)
1176 1177 1178
        real_path = os.path.realpath(__file__)
        if re.match(r'.*src\/sky\/packages\/sky\/', real_path) is not None:
            logging.warning('Using overridden sky package located at ' + os.path.dirname(os.path.dirname(real_path)))
1179

1180
        parser = argparse.ArgumentParser(description='Sky App Runner')
1181 1182
        parser.add_argument('--verbose', dest='verbose', action='store_true',
            help='Noisy logging, including all shell commands executed')
1183 1184 1185 1186 1187 1188
        parser.add_argument('--release', dest='use_release', action='store_true',
            help='Set this if you are building Sky locally and want to use the release build products. '
                 'When set, attempts to automaticaly determine sky-src-path if sky-src-path is '
                 'not set. Using this flag automatically turns on local-build as well, so you do not '
                 'need to specify both. Note that --release is not compatible with the listen command '
                 'on iOS devices and simulators. Not normally required.')
1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199
        parser.add_argument('--local-build', dest='local_build', action='store_true',
            help='Set this if you are building Sky locally and want to use those build products. '
                 'When set, attempts to automaticaly determine sky-src-path if sky-src-path is '
                 'not set. Not normally required.')
        parser.add_argument('--sky-src-path', dest='sky_src_path',
            help='Path to your Sky src directory, if you are building Sky locally. '
                 'Ignored if local-build is not set. Not normally required.')
        parser.add_argument('--android-debug-build-path', dest='android_debug_build_path',
            help='Path to your Android Debug out directory, if you are building Sky locally. '
                 'This path is relative to sky-src-path. Not normally required.',
            default='out/android_Debug/')
1200 1201 1202 1203
        parser.add_argument('--android-release-build-path', dest='android_release_build_path',
            help='Path to your Android Release out directory, if you are building Sky locally. '
                 'This path is relative to sky-src-path. Not normally required.',
            default='out/android_Release/')
1204 1205 1206 1207
        parser.add_argument('--ios-debug-build-path', dest='ios_debug_build_path',
            help='Path to your iOS Debug out directory, if you are building Sky locally. '
                 'This path is relative to sky-src-path. Not normally required.',
            default='out/ios_Debug/')
1208 1209 1210 1211
        parser.add_argument('--ios-release-build-path', dest='ios_release_build_path',
            help='Path to your iOS Release out directory, if you are building Sky locally. '
                 'This path is relative to sky-src-path. Not normally required.',
            default='out/ios_Release/')
1212 1213 1214 1215
        parser.add_argument('--ios-sim-debug-build-path', dest='ios_sim_debug_build_path',
            help='Path to your iOS Simulator Debug out directory, if you are building Sky locally. '
                 'This path is relative to sky-src-path. Not normally required.',
            default='out/ios_sim_Debug/')
1216 1217 1218 1219
        parser.add_argument('--ios-sim-release-build-path', dest='ios_sim_release_build_path',
            help='Path to your iOS Simulator Release out directory, if you are building Sky locally. '
                 'This path is relative to sky-src-path. Not normally required.',
            default='out/ios_sim_Release/')
1220

1221 1222
        subparsers = parser.add_subparsers(help='sub-command help')

1223
        for command in [SkyLogs(), InstallSky(), StartSky(), StopSky(), StartListening(), StartTracing(), StopTracing(), IOSSimulator()]:
1224 1225 1226
            command.add_subparser(subparsers)

        args = parser.parse_args()
1227 1228 1229
        if args.verbose:
            logging.getLogger().setLevel(logging.INFO)

1230 1231 1232
        if args.use_release:
            args.local_build = True

1233 1234 1235 1236 1237 1238
        # TODO(iansf): args is unfortunately just a global context variable.  For now, add some additional context to it.
        args.android_build_available = False
        args.ios_build_available = False
        args.ios_sim_build_available = False

        # Also make sure that args is consistent with machine state for local builds
1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262
        if args.local_build and args.sky_src_path is None:
            real_sky_path = os.path.realpath(os.path.join(PACKAGES_DIR, 'sky'))
            match = re.match(r'pub.dartlang.org/sky', real_sky_path)
            if match is not None:
                args.local_build = False
            else:
                sky_src_path = os.path.dirname(
                    os.path.dirname(
                        os.path.dirname(
                            os.path.dirname(real_sky_path))))
                if sky_src_path == '/' or sky_src_path == '':
                    args.local_build = False
                else:
                    args.sky_src_path = sky_src_path

            if not args.local_build:
                logging.warning('Unable to detect a valid sky install. Disabling local-build flag.\n'
                                'The recommended way to use a local build of Sky is to add the following\n'
                                'to your pubspec.yaml file and then run pub get again:\n'
                                'dependency_overrides:\n'
                                '  material_design_icons:\n'
                                '    path: /path/to/sky_engine/src/sky/packages/material_design_icons\n'
                                '  sky:\n'
                                '    path: /path/to/sky_engine/src/sky/packages/sky\n')
1263 1264 1265 1266 1267
        if args.local_build:
            if not os.path.isdir(args.sky_src_path):
                logging.warning('The selected sky-src-path (' + args.sky_src_path + ') does not exist.'
                                'Disabling local-build flag.')
                args.local_build = False
1268 1269 1270 1271 1272 1273 1274 1275
        if args.local_build and args.use_release:
            if os.path.isdir(os.path.join(args.sky_src_path, args.android_release_build_path)):
                args.android_build_available = True
            if os.path.isdir(os.path.join(args.sky_src_path, args.ios_release_build_path)):
                args.ios_build_available = True
            if os.path.isdir(os.path.join(args.sky_src_path, args.ios_sim_release_build_path)):
                args.ios_sim_build_available = True
        elif args.local_build:
1276 1277 1278 1279 1280 1281
            if os.path.isdir(os.path.join(args.sky_src_path, args.android_debug_build_path)):
                args.android_build_available = True
            if os.path.isdir(os.path.join(args.sky_src_path, args.ios_debug_build_path)):
                args.ios_build_available = True
            if os.path.isdir(os.path.join(args.sky_src_path, args.ios_sim_debug_build_path)):
                args.ios_sim_build_available = True
1282 1283 1284
        else:
            if os.path.isdir(APK_DIR):
                args.android_build_available = True
1285

1286 1287 1288
        if not self._check_for_dart():
            sys.exit(2)

1289
        pids = Pids.read_from(PID_FILE_PATH, PID_FILE_KEYS)
1290 1291 1292
        atexit.register(pids.write_to, PID_FILE_PATH)
        exit_code = 0
        try:
1293
            exit_code = args.func(args, pids)
1294
        except subprocess.CalledProcessError as e:
1295 1296 1297
            # Don't print a stack trace if the adb command fails.
            logging.error(e)
            exit_code = 2
1298 1299 1300 1301
        sys.exit(exit_code)


if __name__ == '__main__':
1302
    sys.exit(SkyShellRunner().main())