sky_tool 50.2 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


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):
        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])

292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310
        try:
            # Because the server gets forked by dart, pids.get(['sky_server_pid']) returns an invalid pid,
            # so just force things closed.
            if platform.system() == 'Darwin':
                cmd = ['lsof', '-i', ':%s' % SKY_SERVER_PORT, '-t']
                logging.info(' '.join(cmd))
                pid = subprocess.check_output(cmd)

                # Killing a pid with a shell command from within python is hard,
                # so use a library command, but it's still nice to give the
                # equivalent command when doing verbose logging.
                logging.info('kill %s' % pid)
                os.kill(int(pid), signal.SIGTERM)
            else:
                # This usage of fuser is not valid on OS X
                self._run(['fuser', '-k', '%s/tcp' % SKY_SERVER_PORT])
        except subprocess.CalledProcessError as e:
            pass

311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332
        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']
333 334 335 336 337 338 339 340 341
            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
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 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431
        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()

432 433 434 435
    # 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)
436
        elif args.android_build_available and args.local_build:
437 438 439 440
            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)

441 442 443
    def is_connected(self):
        return self.has_valid_android

444 445 446 447 448 449 450 451 452 453 454
    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

455 456 457
    def install_apk(self, apk_path):
        if not os.path.exists(apk_path):
            logging.error('"%s" does not exist.' % apk_path)
458
            return False
459 460 461 462 463 464 465 466 467 468 469 470

        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)

471 472 473
        return True


474 475 476
    # TODO(iansf): refactor setup_servers
    def setup_servers(self, sky_server_root, main_dart, pids, args):
        if not self.is_connected():
477
            return False
478

479 480
        # Set up port forwarding for observatory
        observatory_port_string = 'tcp:%s' % OBSERVATORY_PORT
481
        cmd = [
482
            self.adb_path,
483 484 485 486 487 488
            'forward',
            observatory_port_string,
            observatory_port_string
        ]
        logging.info(' '.join(cmd))
        subprocess.check_call(cmd)
489 490 491 492

        sky_server_port = SKY_SERVER_PORT
        pids['sky_server_port'] = sky_server_port
        if _port_in_use(sky_server_port):
493
            logging.info(('Port %s already in use. '
494 495 496 497 498 499 500
            ' 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
501
        cmd = [
502
            self.adb_path,
503 504 505 506 507 508
            'reverse',
            port_string,
            port_string
        ]
        logging.info(' '.join(cmd))
        subprocess.check_call(cmd)
509 510 511
        pids['remote_sky_server_port'] = sky_server_port

        # The load happens on the remote device, use the remote port.
512
        url = _url_for_path(pids['remote_sky_server_port'], sky_server_root,
513
            main_dart)
514 515
        if args.poke:
            url += '?rand=%s' % random.random()
516

517
        cmd = [
518
            self.adb_path, 'shell',
519 520
            'am', 'start',
            '-a', 'android.intent.action.VIEW',
521
            '-d', url,
522 523 524
        ]

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

527
        cmd += [ANDROID_COMPONENT]
528
        logging.info(' '.join(cmd))
529
        subprocess.check_output(cmd)
530

531 532
        return True

533
    def logs(self, clear=False):
534
        def do_logs():
535 536 537 538 539 540 541 542 543
            if clear:
                cmd = [
                    self.adb_path,
                    'logcat',
                    '-c'
                ]
                logging.info(' '.join(cmd))
                subprocess.check_call(cmd)

544 545 546
            cmd = [
                self.adb_path,
                'logcat',
547 548
                '-v',
                'tag', # Only log the tag and the message
549 550 551 552 553 554 555 556
                '-s',
                'sky',
                'chromium',
            ]
            logging.info(' '.join(cmd))
            log_process = subprocess.Popen(cmd, bufsize=1, stdout=subprocess.PIPE)
            while True:
                try:
557 558 559 560 561 562
                    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)
563 564 565 566 567 568 569
                    sys.stdout.flush()
                except KeyboardInterrupt:
                    break
        log_reader = multiprocessing.Process(target=do_logs)
        log_reader.daemon = True
        log_reader.start()
        return log_reader
570 571


572 573 574 575 576 577
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
578 579 580 581 582
        try:
            cmd = [
                'which',
                'ios-deploy'
            ]
583
            logging.info(' '.join(cmd))
584 585 586 587 588
            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
589 590 591 592 593 594 595 596 597
        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
598 599 600 601 602 603 604 605 606 607 608 609 610
        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
611 612
        return cls._is_connected

613 614 615 616 617 618 619
    @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)

620 621 622 623
    @classmethod
    def needs_install(cls, args):
        return cls.is_connected()

624 625 626
    @classmethod
    def install_app(cls, ios_app_path):
        if not cls.has_ios_deploy():
627
            return False
628 629 630 631 632 633 634 635 636 637 638 639
        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:
640 641
            return False
        return True
642 643 644 645 646

    @classmethod
    def copy_file(cls, bundle_id, local_path, device_path):
        if not cls.has_ios_deploy():
            return
647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662
        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
663

664
    @classmethod
665
    def logs(cls, clear=False):
666 667 668 669 670 671 672 673 674 675 676
        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

677 678 679 680 681 682 683 684 685
        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()
686 687 688 689
                    if log_line == '':
                        if log_process.poll() != None:
                            logging.error('The iOS logging process has quit unexpectedly. Please call the "logs" command again.')
                            break
690 691 692 693 694 695 696 697 698 699
                    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

700 701 702 703

class IOSSimulator(object):
    @classmethod
    def is_booted(cls):
704 705
        if platform.system() != 'Darwin':
            return False
706 707
        return cls.get_simulator_device_id() is not None

708 709 710 711
    @classmethod
    def is_connected(cls):
        return cls.is_booted()

712 713 714 715 716
    _device_id = None
    @classmethod
    def get_simulator_device_id(cls):
        if cls._device_id is not None:
            return cls._device_id
717
        cmd = SIMCTL_PATH + [
718 719 720
            'list',
            'devices',
        ]
721
        logging.info(' '.join(cmd))
722 723 724 725 726 727
        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:
728
            logging.info('No running simulators found')
729 730 731 732 733 734 735 736 737 738 739
            # 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
740
        home_dir = os.path.expanduser('~')
741 742 743 744 745 746 747 748 749 750 751 752 753 754 755
        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',
756
            os.path.join(simulator_path, 'data', 'Containers', 'Data', 'Application'),
757 758 759
            '-name',
            SKY_SHELL_APP_ID
        ]
760
        logging.info(' '.join(cmd))
761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787
        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

788 789 790 791 792 793 794
    @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)

795 796 797 798
    @classmethod
    def needs_install(cls, args):
        return cls.is_booted()

799
    @classmethod
800
    def logs(cls, clear=False):
801 802 803 804 805 806 807 808 809 810 811
        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()
812 813 814 815
                    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
816 817 818 819 820 821 822 823 824 825
                    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

826 827
    @classmethod
    def fork_install_app(cls, ios_app_path):
828 829 830 831 832 833 834 835 836 837 838 839 840
        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
841

842 843 844 845 846 847 848 849 850 851 852
    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)

853
    def get_application_identifier(self, path):
854 855 856 857 858 859 860 861
        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()
862 863

    def is_simulator_booted(self):
864 865 866 867 868 869 870
        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
871 872 873

    # 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):
874 875
        # Guarantee that the args get processed, since all of the commands funnel through here.
        self._process_args(args)
876 877 878 879 880 881 882 883 884 885 886 887
        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)
888 889

    def install_app(self, args, pids):
890 891 892 893
        self.boot_simulator(args, pids)
        cmd = SIMCTL_PATH + [
            'install',
            'booted',
894
            args.ios_sim_build_path,
895 896 897
        ]
        logging.info(' '.join(cmd))
        return subprocess.check_call(cmd)
898 899

    def install_launch_and_wait(self, args, pids, wait):
900 901 902
        res = self.install_app(args, pids)
        if res != 0:
            return res
903
        identifier = self.get_application_identifier(args.ios_sim_build_path)
904 905 906 907 908 909 910 911 912 913 914 915 916
        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()
917 918

    def launch_app(self, args, pids):
919
        self.install_launch_and_wait(args, pids, False)
920 921

    def debug_app(self, args, pids):
922 923 924 925 926 927 928 929 930 931 932 933
        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)
934 935 936 937 938 939

    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.')
940 941 942 943 944
        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.')
945 946
        simulator_parser.add_argument('-t', dest='target', required=False,
            default='examples/demo_launcher/lib/main.dart',
947
            help='Sky server-relative path to the Sky app to run. Not normally required.')
948 949
        simulator_parser.add_argument('-s', dest='server', required=False,
            default='localhost:8080',
950
            help='Sky server address. Not normally required.')
951 952 953 954 955 956 957
        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)
958 959 960
        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.')
961 962 963 964
        debug_parser.set_defaults(func=self.debug_app)


class StartListening(object):
965 966 967
    def __init__(self):
        self.watch_cmd = None

968 969 970 971 972
    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)

973 974 975 976 977 978 979 980 981
    def watch_dir(self, directory):
        if self.watch_cmd is None:
            name = platform.system()
            if name == 'Linux':
                try:
                    cmd = [
                        'which',
                        'inotifywait'
                    ]
982
                    logging.info(' '.join(cmd))
983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000
                    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'
                    ]
1001
                    logging.info(' '.join(cmd))
1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016
                    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
1017

1018
        logging.info(' '.join(self.watch_cmd))
1019 1020 1021 1022
        subprocess.check_call(self.watch_cmd)
        return True

    def run(self, args, pids):
1023 1024 1025 1026 1027
        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.')
1028 1029
        tempdir = tempfile.mkdtemp()
        currdir = os.getcwd()
1030 1031 1032 1033 1034 1035 1036 1037 1038 1039
        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'
            ]
1040
            logging.info(' '.join(cmd))
1041 1042
            subprocess.check_call(cmd)

1043
            if args.local_build:
1044 1045 1046
                # Currently sending to iOS only works if you are building Sky locally
                # since we aren't shipping the sky_snapshot binary yet.

1047 1048 1049 1050 1051 1052
                # 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')
1053

1054 1055 1056 1057 1058 1059 1060 1061
                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')
                    ]
1062
                    logging.info(' '.join(cmd))
1063
                    subprocess.check_call(cmd)
1064

1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075
                    os.chdir(tempdir)
                    # Turn the snapshot into an app.skyx file
                    cmd = [
                        'zip',
                        '-r',
                        'app.skyx',
                        'snapshot_blob.bin',
                        'action',
                        'content',
                        'navigation'
                    ]
1076
                    logging.info(' '.join(cmd))
1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087
                    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
                        ]
1088
                        logging.info(' '.join(cmd))
1089 1090 1091 1092 1093
                        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')
1094

1095 1096 1097 1098
            # Watch filesystem for changes
            if not self.watch_dir(currdir):
                return

1099

1100 1101 1102 1103 1104 1105 1106
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):
1107 1108 1109 1110 1111 1112 1113 1114 1115 1116
        cmd = [
            ADB_PATH,
            'shell',
            'am',
            'broadcast',
            '-a',
            'org.domokit.sky.shell.TRACING_START'
        ]
        logging.info(' '.join(cmd))
        subprocess.check_output(cmd)
1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129


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):
1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144
        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)

1145 1146 1147 1148
        device_path = None
        is_complete = False
        while not is_complete:
            time.sleep(0.2)
1149 1150 1151
            cmd = [ADB_PATH, 'logcat', '-d']
            logging.info(' '.join(cmd))
            log = subprocess.check_output(cmd)
1152 1153 1154 1155 1156 1157
            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

1158
        logging.info('Downloading trace %s ...' % os.path.basename(device_path))
1159 1160

        if device_path:
1161 1162 1163
            cmd = [ADB_PATH, 'root']
            logging.info(' '.join(cmd))
            output = subprocess.check_output(cmd)
Ian Fischer's avatar
Ian Fischer committed
1164
            match = re.match(r'.*cannot run as root.*', output)
1165 1166 1167 1168 1169 1170
            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

1171 1172 1173 1174 1175 1176 1177
            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)
1178 1179 1180 1181 1182


class SkyShellRunner(object):
    def _check_for_dart(self):
        try:
1183 1184 1185
            cmd = [DART_PATH, '--version']
            logging.info(' '.join(cmd))
            subprocess.check_output(cmd, stderr=subprocess.STDOUT)
1186
        except OSError:
1187
            logging.error('"dart" (from the Dart SDK) not in $PATH, cannot continue.')
1188 1189 1190 1191
            return False
        return True

    def main(self):
1192
        logging.basicConfig(format='%(levelname)s: %(message)s', level=logging.WARNING)
1193 1194 1195
        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)))
1196

1197
        parser = argparse.ArgumentParser(description='Sky App Runner')
1198 1199
        parser.add_argument('--verbose', dest='verbose', action='store_true',
            help='Noisy logging, including all shell commands executed')
1200 1201 1202 1203 1204 1205
        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.')
1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216
        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/')
1217 1218 1219 1220
        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/')
1221 1222 1223 1224
        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/')
1225 1226 1227 1228
        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/')
1229 1230 1231 1232
        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/')
1233 1234 1235 1236
        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/')
1237

1238 1239
        subparsers = parser.add_subparsers(help='sub-command help')

1240
        for command in [SkyLogs(), InstallSky(), StartSky(), StopSky(), StartListening(), StartTracing(), StopTracing(), IOSSimulator()]:
1241 1242 1243
            command.add_subparser(subparsers)

        args = parser.parse_args()
1244 1245 1246
        if args.verbose:
            logging.getLogger().setLevel(logging.INFO)

1247 1248 1249
        if args.use_release:
            args.local_build = True

1250 1251 1252 1253 1254 1255
        # 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
1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279
        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')
1280 1281 1282 1283 1284
        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
1285 1286 1287 1288 1289 1290 1291 1292
        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:
1293 1294 1295 1296 1297 1298
            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
1299 1300 1301
        else:
            if os.path.isdir(APK_DIR):
                args.android_build_available = True
1302

1303 1304 1305
        if not self._check_for_dart():
            sys.exit(2)

1306
        pids = Pids.read_from(PID_FILE_PATH, PID_FILE_KEYS)
1307 1308 1309
        atexit.register(pids.write_to, PID_FILE_PATH)
        exit_code = 0
        try:
1310
            exit_code = args.func(args, pids)
1311
        except subprocess.CalledProcessError as e:
1312 1313 1314
            # Don't print a stack trace if the adb command fails.
            logging.error(e)
            exit_code = 2
1315 1316 1317 1318
        sys.exit(exit_code)


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