DXR will be turned off on Tuesday, December 29th. It will redirect to Searchfox.
See the announcement on Discourse.

DXR is a code search and navigation tool aimed at making sense of large projects. It supports full-text and regex searches as well as structural queries.

Mercurial (c68fe15a81fc)

VCS Links

Line Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 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 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 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 316 317 318 319 320 321 322 323 324 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 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.


from __future__ import absolute_import, print_function, unicode_literals

import os
import re
import subprocess
import subprocess
import sys
import tempfile
try:
    from urllib2 import urlopen
except ImportError:
except ImportError:
    from urllib.request import urlopen

from distutils.version import StrictVersion

from mozboot.base import BaseBootstrapper
from mozboot.base import BaseBootstrapper

HOMEBREW_BOOTSTRAP = 'https://raw.githubusercontent.com/Homebrew/install/master/install'
XCODE_APP_STORE = 'macappstore://itunes.apple.com/app/id497799835?mt=12'
XCODE_LEGACY = ('https://developer.apple.com/downloads/download.action?path=Developer_Tools/'
                'xcode_3.2.6_and_ios_sdk_4.3__final/xcode_3.2.6_and_ios_sdk_4.3.dmg')
JAVA_PATH = '/Library/Java/JavaVirtualMachines/adoptopenjdk-8.jdk/Contents/Home/bin'
JAVA_PATH = '/Library/Java/JavaVirtualMachines/adoptopenjdk-8.jdk/Contents/Home/bin'

MACPORTS_URL = {
    '14': 'https://distfiles.macports.org/MacPorts/MacPorts-2.5.4-10.14-Mojave.pkg',
    '13': 'https://distfiles.macports.org/MacPorts/MacPorts-2.5.4-10.13-HighSierra.pkg',
    '12': 'https://distfiles.macports.org/MacPorts/MacPorts-2.5.4-10.12-Sierra.pkg',
    '12': 'https://distfiles.macports.org/MacPorts/MacPorts-2.5.4-10.12-Sierra.pkg',
    '11': 'https://distfiles.macports.org/MacPorts/MacPorts-2.5.4-10.11-ElCapitan.pkg',
    '10': 'https://distfiles.macports.org/MacPorts/MacPorts-2.5.4-10.10-Yosemite.pkg',
    '9': 'https://distfiles.macports.org/MacPorts/MacPorts-2.5.4-10.9-Mavericks.pkg',
    '8': 'https://distfiles.macports.org/MacPorts/MacPorts-2.5.4-10.8-MountainLion.pkg',
    '7': 'https://distfiles.macports.org/MacPorts/MacPorts-2.5.4-10.7-Lion.pkg',
    '7': 'https://distfiles.macports.org/MacPorts/MacPorts-2.5.4-10.7-Lion.pkg',
    '6': 'https://distfiles.macports.org/MacPorts/MacPorts-2.5.4-10.6-SnowLeopard.pkg', }
    '6': 'https://distfiles.macports.org/MacPorts/MacPorts-2.5.4-10.6-SnowLeopard.pkg', }

RE_CLANG_VERSION = re.compile('Apple (?:clang|LLVM) version (\d+\.\d+)')

APPLE_CLANG_MINIMUM_VERSION = StrictVersion('4.2')


XCODE_REQUIRED = '''
Xcode is required to build Firefox. Please complete the install of Xcode
through the App Store.

It's possible Xcode is already installed on this machine but it isn't being
It's possible Xcode is already installed on this machine but it isn't being
detected. This is possible with developer preview releases of Xcode, for
example. To correct this problem, run:

  `xcode-select --switch /path/to/Xcode.app`.


e.g. `sudo xcode-select --switch /Applications/Xcode.app`.
'''

XCODE_REQUIRED_LEGACY = '''
You will need to download and install Xcode to build Firefox.

Please complete the Xcode download and then relaunch this script.
Please complete the Xcode download and then relaunch this script.
'''

XCODE_NO_DEVELOPER_DIRECTORY = '''
XCODE_NO_DEVELOPER_DIRECTORY = '''
xcode-select says you don't have a developer directory configured. We think
this is due to you not having Xcode installed (properly). We're going to
attempt to install Xcode through the App Store. If the App Store thinks you
have Xcode installed, please run xcode-select by hand until it stops
have Xcode installed, please run xcode-select by hand until it stops
complaining and then re-run this script.
'''

XCODE_COMMAND_LINE_TOOLS_MISSING = '''
The Xcode command line tools are required to build Firefox.
The Xcode command line tools are required to build Firefox.
'''

INSTALL_XCODE_COMMAND_LINE_TOOLS_STEPS = '''
Perform the following steps to install the Xcode command line tools:


    1) Open Xcode.app
    2) Click through any first-run prompts
    3) From the main Xcode menu, select Preferences (Command ,)
    4) Go to the Download tab (near the right)
    5) Install the "Command Line Tools"
    5) Install the "Command Line Tools"

When that has finished installing, please relaunch this script.
'''

UPGRADE_XCODE_COMMAND_LINE_TOOLS = '''
UPGRADE_XCODE_COMMAND_LINE_TOOLS = '''
An old version of the Xcode command line tools is installed. You will need to
install a newer version in order to compile Firefox. If Xcode itself is old,
install a newer version in order to compile Firefox. If Xcode itself is old,
its command line tools may be too old even if it claims there are no updates
available, so if you are seeing this message multiple times, please update
Xcode first.
'''


PACKAGE_MANAGER_INSTALL = '''
We will install the %s package manager to install required packages.


You will be prompted to install %s with its default settings. If you
You will be prompted to install %s with its default settings. If you
would prefer to do this manually, hit CTRL+c, install %s yourself, ensure
"%s" is in your $PATH, and relaunch bootstrap.
'''
'''

PACKAGE_MANAGER_PACKAGES = '''
We are now installing all required packages via %s. You will see a lot of
output as packages are built.
'''
'''

PACKAGE_MANAGER_OLD_CLANG = '''
We require a newer compiler than what is provided by your version of Xcode.

We will install a modern version of Clang through %s.
We will install a modern version of Clang through %s.
'''


PACKAGE_MANAGER_CHOICE = '''
Please choose a package manager you'd like:
  1. Homebrew
  2. MacPorts (Does not yet support bootstrapping GeckoView/Firefox for Android.)
Your choice: '''
Your choice: '''

NO_PACKAGE_MANAGER_WARNING = '''
It seems you don't have any supported package manager installed.
'''


PACKAGE_MANAGER_EXISTS = '''
Looks like you have %s installed. We will install all required packages via %s.
'''

MULTI_PACKAGE_MANAGER_EXISTS = '''
MULTI_PACKAGE_MANAGER_EXISTS = '''
It looks like you have multiple package managers installed.
'''

# May add support for other package manager on os x.
PACKAGE_MANAGER = {'Homebrew': 'brew',
PACKAGE_MANAGER = {'Homebrew': 'brew',
                   'MacPorts': 'port'}

PACKAGE_MANAGER_CHOICES = ['Homebrew', 'MacPorts']

PACKAGE_MANAGER_BIN_MISSING = '''
A package manager is installed. However, your current shell does
A package manager is installed. However, your current shell does
not know where to find '%s' yet. You'll need to start a new shell
to pick up the environment changes so it can be found.

Please start a new shell or terminal window and run this
bootstrapper again.

If this problem persists, you will likely want to adjust your
shell's init script (e.g. ~/.bash_profile) to export a PATH
environment variable containing the location of your package
environment variable containing the location of your package
manager binary. e.g.

Homebrew:
    export PATH=/usr/local/bin:$PATH


MacPorts:
    export PATH=/opt/local/bin:$PATH
'''

BAD_PATH_ORDER = '''
BAD_PATH_ORDER = '''
Your environment's PATH variable lists a system path directory (%s)
before the path to your package manager's binaries (%s).
This means that the package manager's binaries likely won't be
detected properly.


Modify your shell's configuration (e.g. ~/.profile or
~/.bash_profile) to have %s appear in $PATH before %s. e.g.

    export PATH=%s:$PATH


Once this is done, start a new shell (likely Command+T) and run
this bootstrap again.
'''



class OSXBootstrapper(BaseBootstrapper):
    def __init__(self, version, **kwargs):
        BaseBootstrapper.__init__(self, **kwargs)

        self.os_version = StrictVersion(version)
        self.os_version = StrictVersion(version)

        if self.os_version < StrictVersion('10.6'):
            raise Exception('OS X 10.6 or above is required.')


        self.minor_version = version.split('.')[1]

    def install_system_packages(self):
        self.ensure_xcode()

        choice = self.ensure_package_manager()
        self.package_manager = choice
        self.package_manager = choice
        _, hg_modern, _ = self.is_mercurial_modern()
        if not hg_modern:
            print("Mercurial wasn't found or is not sufficiently modern. "
                  "It will be installed with %s" % self.package_manager)
        getattr(self, 'ensure_%s_system_packages' % self.package_manager)(not hg_modern)
        getattr(self, 'ensure_%s_system_packages' % self.package_manager)(not hg_modern)

    def install_browser_packages(self):
        getattr(self, 'ensure_%s_browser_packages' % self.package_manager)()

    def install_browser_artifact_mode_packages(self):
    def install_browser_artifact_mode_packages(self):
        getattr(self, 'ensure_%s_browser_packages' % self.package_manager)(artifact_mode=True)

    def install_mobile_android_packages(self):
        getattr(self, 'ensure_%s_mobile_android_packages' % self.package_manager)()


    def install_mobile_android_artifact_mode_packages(self):
        getattr(self, 'ensure_%s_mobile_android_packages' %
                self.package_manager)(artifact_mode=True)


    def generate_mobile_android_mozconfig(self):
        return getattr(self, 'generate_%s_mobile_android_mozconfig' %
                       self.package_manager)()

    def generate_mobile_android_artifact_mode_mozconfig(self):
        getattr(self, 'suggest_%s_mobile_android_mozconfig' %
        return getattr(self, 'generate_%s_mobile_android_mozconfig' %
                       self.package_manager)(artifact_mode=True)

    def ensure_xcode(self):
        if self.os_version < StrictVersion('10.7'):
            if not os.path.exists('/Developer/Applications/Xcode.app'):
            if not os.path.exists('/Developer/Applications/Xcode.app'):
                print(XCODE_REQUIRED_LEGACY)

                subprocess.check_call(['open', XCODE_LEGACY])
                sys.exit(1)


        # OS X 10.7 have Xcode come from the app store. However, users can
        # still install Xcode into any arbitrary location. We honor the
        # location of Xcode as set by xcode-select. This should also pick up
        # developer preview releases of Xcode, which can be installed into
        # paths like /Applications/Xcode5-DP6.app.
        elif self.os_version >= StrictVersion('10.7'):
            select = self.which('xcode-select')
            try:
                output = self.check_output([select, '--print-path'],
                                           stderr=subprocess.STDOUT)
            except subprocess.CalledProcessError as e:
            except subprocess.CalledProcessError as e:
                # This seems to appear on fresh OS X machines before any Xcode
                # has been installed. It may only occur on OS X 10.9 and later.
                if b'unable to get active developer directory' in e.output:
                    print(XCODE_NO_DEVELOPER_DIRECTORY)
                    self._install_xcode_app_store()
                    self._install_xcode_app_store()
                    assert False  # Above should exit.

                output = e.output

            # This isn't the most robust check in the world. It relies on the
            # This isn't the most robust check in the world. It relies on the
            # default value not being in an application bundle, which seems to
            # hold on at least Mavericks.
            if b'.app/' not in output:
                self._install_xcode_app_store()
                print(XCODE_REQUIRED)
                self._install_xcode_app_store()
                assert False  # Above should exit.

        # Once Xcode is installed, you need to agree to the license before you can
        try:
        # use it.
        try:
            output = self.check_output(['/usr/bin/xcrun', 'clang'],
                                       stderr=subprocess.STDOUT)
        except subprocess.CalledProcessError as e:
            if b'license' in e.output:
                xcodebuild = self.which('xcodebuild')
                try:
                    self.check_output([xcodebuild, '-license'],
                                      stderr=subprocess.STDOUT)
                except subprocess.CalledProcessError as e:
                except subprocess.CalledProcessError as e:
                    if b'requires admin privileges' in e.output:
                        self.run_as_root([xcodebuild, '-license'])

        # Even then we're not done! We need to install the Xcode command line tools.
        # As of Mountain Lion, apparently the only way to do this is to go through a
        # As of Mountain Lion, apparently the only way to do this is to go through a
        # menu dialog inside Xcode itself. We're not making this up.
            if not os.path.exists('/usr/bin/clang'):
        if self.os_version >= StrictVersion('10.7'):
            if not os.path.exists('/usr/bin/clang'):
                print(XCODE_COMMAND_LINE_TOOLS_MISSING)
                print(INSTALL_XCODE_COMMAND_LINE_TOOLS_STEPS)
                sys.exit(1)

            output = self.check_output(['/usr/bin/clang', '--version'],
            output = self.check_output(['/usr/bin/clang', '--version'],
                                       universal_newlines=True)
            match = RE_CLANG_VERSION.search(output)
            if match is None:
                raise Exception('Could not determine Clang version.')


            version = StrictVersion(match.group(1))

            if version < APPLE_CLANG_MINIMUM_VERSION:
                print(UPGRADE_XCODE_COMMAND_LINE_TOOLS)
                print(INSTALL_XCODE_COMMAND_LINE_TOOLS_STEPS)
                print(INSTALL_XCODE_COMMAND_LINE_TOOLS_STEPS)
                sys.exit(1)

    def _install_xcode_app_store(self):
        subprocess.check_call(['open', XCODE_APP_STORE])
        print('Once the install has finished, please relaunch this script.')
        print('Once the install has finished, please relaunch this script.')
        sys.exit(1)

    def _ensure_homebrew_found(self):
            self.brew = self.which('brew')
        if not hasattr(self, 'brew'):
            self.brew = self.which('brew')
        # Earlier code that checks for valid package managers ensures
        # which('brew') is found.
        assert self.brew is not None
    def _ensure_homebrew_packages(self, packages, extra_brew_args=[]):

    def _ensure_homebrew_packages(self, packages, extra_brew_args=[]):
        self._ensure_homebrew_found()
        self._ensure_package_manager_updated()
        cmd = [self.brew] + extra_brew_args
        installed = set(self.check_output(cmd + ['list'],

        installed = set(self.check_output(cmd + ['list'],
                                          universal_newlines=True).split())
        to_install = set(
        # The "--quiet" tells "brew" to only list the package names, and not the
            package for package in packages if package not in installed)

        # The "--quiet" tells "brew" to only list the package names, and not the
        # comparison between current and new version.
        outdated = set(self.check_output(cmd + ['outdated', '--quiet'],
                                         universal_newlines=True).split())

        to_upgrade = set(package for package in packages if package in outdated)
            print(PACKAGE_MANAGER_PACKAGES % ('Homebrew',))

        if to_install or to_upgrade:
            print(PACKAGE_MANAGER_PACKAGES % ('Homebrew',))
        if 'python@2' in to_install:
            # Special handling for Python 2 since brew can't install it

            # out-of-the-box any more.
            to_install.remove('python@2')
            subprocess.check_call(
                cmd + ['install',
                       'https://raw.githubusercontent.com/Homebrew/homebrew-core'
        known_taps = self.check_output([self.brew, 'tap'])
                       '/86a44a0a552c673a05f11018459c9f5faae3becc'
                       '/Formula/python@2.rb'])
        if to_install:
            subprocess.check_call(cmd + ['install'] + list(to_install))
        if to_upgrade:

            subprocess.check_call(cmd + ['upgrade'] + list(to_upgrade))

    def _ensure_homebrew_casks(self, casks):
        self._ensure_homebrew_found()

        if b'caskroom/versions' in known_taps:
        known_taps = self.check_output([self.brew, 'tap'])


        # Ensure that we can access old versions of packages.
        if b'homebrew/cask-versions' not in known_taps:
            self.check_output([self.brew, 'tap', 'homebrew/cask-versions'])

        # We need to install Python because Mercurial requires the
        # "caskroom/versions" has been renamed to "homebrew/cask-versions", so
        # it is safe to remove the old tap. Removing the old tap is necessary
        # to avoid the error "Cask [name of cask] exists in multiple taps".
        # See https://bugzilla.mozilla.org/show_bug.cgi?id=1544981
        if b'caskroom/versions' in known_taps:
            'autoconf@2.13',
            self.check_output([self.brew, 'untap', 'caskroom/versions'])

        # Change |brew install cask| into |brew cask install cask|.
        self._ensure_homebrew_packages(casks, extra_brew_args=['cask'])

            'terminal-notifier',
    def ensure_homebrew_system_packages(self, install_mercurial):
        # We need to install Python because Mercurial requires the
        # Python development headers which are missing from OS X (at
        # least on 10.8) and because the build system wants a version
        # newer than what Apple ships.
        packages = [
            'autoconf@2.13',
    def ensure_homebrew_browser_packages(self, artifact_mode=False):
            'git',
            'gnu-tar',
            'node',
            'python',
            'yasm',
            'python@2',
            'terminal-notifier',
            'watchman',
        ]
        if install_mercurial:
        # Multi-part process:
            packages.append('mercurial')
        self._ensure_homebrew_packages(packages)

    def ensure_homebrew_browser_packages(self, artifact_mode=False):
        # TODO: Figure out what not to install for artifact mode
        packages = [
            'nasm',
            'yasm',
        ]
        ]
        self._ensure_homebrew_packages(packages)

    def ensure_homebrew_mobile_android_packages(self, artifact_mode=False):
        ]
        # Multi-part process:
        # 1. System packages.
        # 2. Android SDK. Android NDK only if we are not in artifact mode. Android packages.

        # 1. System packages.
            raise Exception('You need a 64-bit version of Mac OS X to build '
        packages = [
            'wget',

        ]
        self._ensure_homebrew_packages(packages)

        casks = [
            'adoptopenjdk8',
        self.ensure_java()
        ]
        self._ensure_homebrew_casks(casks)

        is_64bits = sys.maxsize > 2**32
        if not is_64bits:

            raise Exception('You need a 64-bit version of Mac OS X to build '
                            'GeckoView/Firefox for Android.')

        # 2. Android pieces.
        # Prefer homebrew's java binary by putting it on the path first.
        os.environ['PATH'] = \
    def _ensure_macports_packages(self, packages):
            '{}{}{}'.format(JAVA_PATH, os.pathsep, os.environ['PATH'])
        self.ensure_java()
        from mozboot import android

        android.ensure_android('macosx', artifact_mode=artifact_mode,
            self.check_output(
                               no_interactive=self.no_interactive)

    def generate_homebrew_mobile_android_mozconfig(self, artifact_mode=False):
        from mozboot import android
        return android.generate_mozconfig('macosx', artifact_mode=artifact_mode)
        if missing:

    def _ensure_macports_packages(self, packages):
        self.port = self.which('port')
        assert self.port is not None

        packages = [
        installed = set(
            self.check_output(
                [self.port, 'installed'],
                universal_newlines=True).split())

            'gnutar',
        missing = [package for package in packages if package not in installed]
        if missing:
            print(PACKAGE_MANAGER_PACKAGES % ('MacPorts',))
            self.run_as_root([self.port, '-v', 'install'] + missing)

            packages.append('mercurial')
    def ensure_macports_system_packages(self, install_mercurial):
        packages = [
            'python27',
            'python36',
            'py27-gnureadline',
            'autoconf213',
            'gnutar',
        active = ''
            'watchman',
            'nodejs8'
        ]
        if install_mercurial:
            packages.append('mercurial')

            self.run_as_root([self.port, 'select', '--set', 'python', 'python27'])
        self._ensure_macports_packages(packages)

        pythons = set(
            self.check_output(
                [self.port, 'select', '--list', 'python'],
        # TODO: Figure out what not to install for artifact mode
                universal_newlines=True).split('\n'))
        active = ''
        for python in pythons:
            if 'active' in python:
                active = python
        if 'python27' not in active:
            self.run_as_root([self.port, 'select', '--set', 'python', 'python27'])

        else:
            print('The right python version is already active.')

    def ensure_macports_browser_packages(self, artifact_mode=False):
        # TODO: Figure out what not to install for artifact mode

        packages = [
            'nasm',
            'wget',
            'yasm',
        ]
        ]

        self._ensure_macports_packages(packages)
        is_64bits = sys.maxsize > 2**32

    def ensure_macports_mobile_android_packages(self, artifact_mode=False):
        # Multi-part process:
        # 1. System packages.
        # 2. Android SDK. Android NDK only if we are not in artifact mode. Android packages.
        # 2. Android pieces.

        # 1. System packages.
        packages = [
            'wget',
        ]
        self._ensure_macports_packages(packages)


        is_64bits = sys.maxsize > 2**32
        android.suggest_mozconfig('macosx', artifact_mode=artifact_mode)
        if not is_64bits:
            raise Exception('You need a 64-bit version of Mac OS X to build '
                            'GeckoView/Firefox for Android.')

        '''
        # 2. Android pieces.
        self.ensure_java()
        from mozboot import android
        android.ensure_android('macosx', artifact_mode=artifact_mode,
                               no_interactive=self.no_interactive)
        installed = []

    def generate_macports_mobile_android_mozconfig(self, artifact_mode=False):
        from mozboot import android
        return android.generate_mozconfig('macosx', artifact_mode=artifact_mode)

        active_name, active_cmd = None, None
    def ensure_package_manager(self):
        '''
        Search package mgr in sys.path, if none is found, prompt the user to install one.
        If only one is found, use that one. If both are found, prompt the user to choose
        one.
            active_name = PACKAGE_MANAGER_CHOICES[choice - 1]
        '''
        installed = []
        for name, cmd in PACKAGE_MANAGER.items():
            if self.which(cmd) is not None:
                installed.append(name)
            active_name = installed[0]

        active_name, active_cmd = None, None

            choice = self.prompt_int(prompt=PACKAGE_MANAGER_CHOICE, low=1, high=2)
        if not installed:
            print(NO_PACKAGE_MANAGER_WARNING)
            choice = self.prompt_int(prompt=PACKAGE_MANAGER_CHOICE, low=1, high=2)
            active_name = PACKAGE_MANAGER_CHOICES[choice - 1]
            active_cmd = PACKAGE_MANAGER[active_name]
        # Ensure the active package manager is in $PATH and it comes before
            getattr(self, 'install_%s' % active_name.lower())()
        elif len(installed) == 1:
            print(PACKAGE_MANAGER_EXISTS % (installed[0], installed[0]))
            active_name = installed[0]
            active_cmd = PACKAGE_MANAGER[active_name]
        if not p:
        else:
            print(MULTI_PACKAGE_MANAGER_EXISTS)
            choice = self.prompt_int(prompt=PACKAGE_MANAGER_CHOICE, low=1, high=2)

            active_name = PACKAGE_MANAGER_CHOICES[choice - 1]
        for path in os.environ['PATH'].split(os.pathsep):
            active_cmd = PACKAGE_MANAGER[active_name]

        # Ensure the active package manager is in $PATH and it comes before
        # /usr/bin. If it doesn't come before /usr/bin, we'll pick up system

        # packages before package manager installed packages and the build may
            for check in ('/bin', '/usr/bin'):
        # break.
        p = self.which(active_cmd)
                    sys.exit(1)
        if not p:

            print(PACKAGE_MANAGER_BIN_MISSING % active_cmd)
            sys.exit(1)

        p_dir = os.path.dirname(p)
        from mozboot import static_analysis
        for path in os.environ['PATH'].split(os.pathsep):
            if path == p_dir:
                break

            for check in ('/bin', '/usr/bin'):
                if path == check:
        from mozboot import sccache
                    print(BAD_PATH_ORDER % (check, p_dir, p_dir, check, p_dir))
                    sys.exit(1)

        return active_name.lower()

                                        no_unpack=True)
    def ensure_clang_static_analysis_package(self, state_dir, checkout_root):
        from mozboot import static_analysis
        self.install_toolchain_static_analysis(
            state_dir, checkout_root, static_analysis.MACOS_CLANG_TIDY)

    def ensure_fix_stacks_packages(self, state_dir, checkout_root):
    def ensure_sccache_packages(self, state_dir, checkout_root):
        from mozboot import sccache

        self.install_toolchain_artifact(state_dir, checkout_root, sccache.MACOS_SCCACHE)
    def ensure_stylo_packages(self, state_dir, checkout_root):
        self.install_toolchain_artifact(state_dir, checkout_root,
                                        sccache.RUSTC_DIST_TOOLCHAIN,
                                        no_unpack=True)
        self.install_toolchain_artifact(state_dir, checkout_root,
                                        sccache.CLANG_DIST_TOOLCHAIN,
    def ensure_nasm_packages(self, state_dir, checkout_root):
                                        no_unpack=True)

    def ensure_fix_stacks_packages(self, state_dir, checkout_root):
        from mozboot import fix_stacks

        # XXX from necessary?
        self.install_toolchain_artifact(state_dir, checkout_root, fix_stacks.MACOS_FIX_STACKS)

    def ensure_stylo_packages(self, state_dir, checkout_root):
        from mozboot import stylo
        self.install_toolchain_artifact(state_dir, checkout_root, stylo.MACOS_CLANG)
        self.install_toolchain_artifact(state_dir, checkout_root, stylo.MACOS_CBINDGEN)
        from mozboot import minidump_stackwalk

    def ensure_nasm_packages(self, state_dir, checkout_root):
        # installed via ensure_browser_packages
        pass

    def install_homebrew(self):
    def ensure_node_packages(self, state_dir, checkout_root):
        # XXX from necessary?
        from mozboot import node
        self.install_toolchain_artifact(state_dir, checkout_root, node.OSX)


    def ensure_minidump_stackwalk_packages(self, state_dir, checkout_root):
        from mozboot import minidump_stackwalk

        self.install_toolchain_artifact(state_dir, checkout_root,
                                        minidump_stackwalk.MACOS_MINIDUMP_STACKWALK)
        if not url:

    def install_homebrew(self):
        print(PACKAGE_MANAGER_INSTALL % ('Homebrew', 'Homebrew', 'Homebrew', 'brew'))
        bootstrap = urlopen(url=HOMEBREW_BOOTSTRAP, timeout=20).read()
        with tempfile.NamedTemporaryFile() as tf:
        pkg = urlopen(url=url, timeout=300).read()
            tf.write(bootstrap)
            tf.flush()

            subprocess.check_call(['ruby', tf.name])

            self.run_as_root(['installer', '-pkg', tf.name, '-target', '/'])
    def install_macports(self):
        url = MACPORTS_URL.get(self.minor_version, None)
        if not url:
            raise Exception('We do not have a MacPorts install URL for your '
                            'OS X version. You will need to install MacPorts manually.')
            subprocess.check_call([self.brew, '-v', 'update'])

        print(PACKAGE_MANAGER_INSTALL % ('MacPorts', 'MacPorts', 'MacPorts', 'port'))
        pkg = urlopen(url=url, timeout=300).read()
        with tempfile.NamedTemporaryFile(suffix='.pkg') as tf:
            tf.write(pkg)
    def _upgrade_package(self, package):
            tf.flush()

            self.run_as_root(['installer', '-pkg', tf.name, '-target', '/'])

    def _update_package_manager(self):
                subprocess.check_output([self.brew, '-v', 'upgrade', package],
        if self.package_manager == 'homebrew':
            subprocess.check_call([self.brew, '-v', 'update'])
        else:
            assert self.package_manager == 'macports'
            self.run_as_root([self.port, 'selfupdate'])
        else:

    def _upgrade_package(self, package):
        self._ensure_package_manager_updated()

        if self.package_manager == 'homebrew':
            try:
        self._upgrade_package('mercurial')
                subprocess.check_output([self.brew, '-v', 'upgrade', package],
                                        stderr=subprocess.STDOUT)
            except subprocess.CalledProcessError as e:
            self._upgrade_package('python')
                if b'already installed' not in e.output:
                    raise
        else:
            assert self.package_manager == 'macports'

            self.run_as_root([self.port, 'upgrade', package])

    def upgrade_mercurial(self, current):
        self._upgrade_package('mercurial')

    def upgrade_python(self, current):
        if self.package_manager == 'homebrew':
            self._upgrade_package('python')
        else:
            self._upgrade_package('python27')