# Copyright 2013 The Servo Project Developers. See the COPYRIGHT
# file at the top-level directory of this distribution.
#
# Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
# http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
# <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
# option. This file may not be copied, modified, or distributed
# except according to those terms.
import os
from os import path
import contextlib
import subprocess
from subprocess import PIPE
import sys
import toml
from mach.registrar import Registrar
@contextlib.contextmanager
def cd(new_path):
    """Context manager for changing the current working directory"""
    previous_path = os.getcwd()
    try:
        os.chdir(new_path)
        yield
    finally:
        os.chdir(previous_path)
def host_triple():
    os_type = subprocess.check_output(["uname", "-s"]).strip().lower()
    if os_type == "linux":
        os_type = "unknown-linux-gnu"
    elif os_type == "darwin":
        os_type = "apple-darwin"
    elif os_type == "android":
        os_type = "linux-androideabi"
    else:
        os_type = "unknown"
    cpu_type = subprocess.check_output(["uname", "-m"]).strip().lower()
    if cpu_type in ["i386", "i486", "i686", "i768", "x86"]:
        cpu_type = "i686"
    elif cpu_type in ["x86_64", "x86-64", "x64", "amd64"]:
        cpu_type = "x86_64"
    elif cpu_type == "arm":
        cpu_type = "arm"
    else:
        cpu_type = "unknown"
    return "%s-%s" % (cpu_type, os_type)
class CommandBase(object):
    """Base class for mach command providers.
    This mostly handles configuration management, such as .servobuild."""
    def __init__(self, context):
        self.context = context
        def resolverelative(category, key):
            # Allow ~
            self.config[category][key] = path.expanduser(self.config[category][key])
            # Resolve relative paths
            self.config[category][key] = path.join(context.topdir,
                                                   self.config[category][key])
        if not hasattr(self.context, "bootstrapped"):
            self.context.bootstrapped = False
        config_path = path.join(context.topdir, ".servobuild")
        if path.exists(config_path):
            with open(config_path) as f:
                self.config = toml.loads(f.read())
        else:
            self.config = {}
        # Handle missing/default items
        self.config.setdefault("tools", {})
        default_cache_dir = os.environ.get("SERVO_CACHE_DIR",
                                           path.join(context.topdir, ".servo"))
        self.config["tools"].setdefault("cache-dir", default_cache_dir)
        resolverelative("tools", "cache-dir")
        self.config["tools"].setdefault("cargo-home-dir",
                                        path.join(context.topdir, ".cargo"))
        resolverelative("tools", "cargo-home-dir")
        context.sharedir = self.config["tools"]["cache-dir"]
        self.config["tools"].setdefault("system-rust", False)
        self.config["tools"].setdefault("system-cargo", False)
        self.config["tools"].setdefault("rust-root", "")
        self.config["tools"].setdefault("cargo-root", "")
        if not self.config["tools"]["system-rust"]:
            self.config["tools"]["rust-root"] = path.join(
                context.sharedir, "rust", self.rust_snapshot_path())
        if not self.config["tools"]["system-cargo"]:
            self.config["tools"]["cargo-root"] = path.join(
                context.sharedir, "cargo", self.cargo_build_id())
        self.config["tools"].setdefault("rustc-with-gold", True)
        self.config.setdefault("build", {})
        self.config["build"].setdefault("android", False)
        self.config["build"].setdefault("mode", "")
        self.config["build"].setdefault("debug-mozjs", False)
        self.config["build"].setdefault("ccache", "")
        self.config.setdefault("android", {})
        self.config["android"].setdefault("sdk", "")
        self.config["android"].setdefault("ndk", "")
        self.config["android"].setdefault("toolchain", "")
        self.config["android"].setdefault("target", "arm-linux-androideabi")
        self.config.setdefault("gonk", {})
        self.config["gonk"].setdefault("b2g", "")
        self.config["gonk"].setdefault("product", "flame")
    _rust_snapshot_path = None
    _cargo_build_id = None
    def rust_snapshot_path(self):
        if self._rust_snapshot_path is None:
            filename = path.join(self.context.topdir, "rust-snapshot-hash")
            with open(filename) as f:
                snapshot_hash = f.read().strip()
            self._rust_snapshot_path = ("%s/rustc-nightly-%s" %
                                        (snapshot_hash, host_triple()))
        return self._rust_snapshot_path
    def cargo_build_id(self):
        if self._cargo_build_id is None:
            filename = path.join(self.context.topdir, "cargo-nightly-build")
            with open(filename) as f:
                self._cargo_build_id = f.read().strip()
        return self._cargo_build_id
    def get_top_dir(self):
        return self.context.topdir
    def get_target_dir(self):
        if "CARGO_TARGET_DIR" in os.environ:
            return os.environ["CARGO_TARGET_DIR"]
        else:
            return path.join(self.context.topdir, "target")
    def get_binary_path(self, release, dev, android=False):
        base_path = self.get_target_dir()
        if android:
            base_path = path.join(base_path, self.config["android"]["target"])
        release_path = path.join(base_path, "release", "servo")
        dev_path = path.join(base_path, "debug", "servo")
        # Prefer release if both given
        if release and dev:
            dev = False
        release_exists = path.exists(release_path)
        dev_exists = path.exists(dev_path)
        if not release_exists and not dev_exists:
            print("No Servo binary found. Please run './mach build' and try again.")
            sys.exit()
        if release and release_exists:
            return release_path
        if dev and dev_exists:
            return dev_path
        if not dev and not release and release_exists and dev_exists:
            print("You have multiple profiles built. Please specify which "
                  "one to run with '--release' or '--dev'.")
            sys.exit()
        if not dev and not release:
            if release_exists:
                return release_path
            else:
                return dev_path
        print("The %s profile is not built. Please run './mach build%s' "
              "and try again." % ("release" if release else "dev",
                                  " --release" if release else ""))
        sys.exit()
    def build_env(self, gonk=False, hosts_file_path=None):
        """Return an extended environment dictionary."""
        env = os.environ.copy()
        extra_path = []
        extra_lib = []
        if not self.config["tools"]["system-rust"] \
                or self.config["tools"]["rust-root"]:
            env["RUST_ROOT"] = self.config["tools"]["rust-root"]
            # These paths are for when rust-root points to an unpacked installer
            extra_path += [path.join(self.config["tools"]["rust-root"], "rustc", "bin")]
            extra_lib += [path.join(self.config["tools"]["rust-root"], "rustc", "lib")]
            # These paths are for when rust-root points to a rustc sysroot
            extra_path += [path.join(self.config["tools"]["rust-root"], "bin")]
            extra_lib += [path.join(self.config["tools"]["rust-root"], "lib")]
        if not self.config["tools"]["system-cargo"] \
                or self.config["tools"]["cargo-root"]:
            # This path is for when rust-root points to an unpacked installer
            extra_path += [
                path.join(self.config["tools"]["cargo-root"], "cargo", "bin")]
            # This path is for when rust-root points to a rustc sysroot
            extra_path += [
                path.join(self.config["tools"]["cargo-root"], "bin")]
        if extra_path:


Answer:             env["PATH"] = "%s%s%s" % (