コード例 #1
0
ファイル: config.py プロジェクト: singulared/poetry
    def __init__(self):
        from poetry.config import Config

        super(ConfigCommand, self).__init__()

        self._config = Config.create("config.toml")
        self._auth_config = Config.create("auth.toml")
コード例 #2
0
ファイル: config.py プロジェクト: uSpike/poetry
    def __init__(self):
        from poetry.config import Config

        super(ConfigCommand, self).__init__()

        self._config = Config.create("config.toml")
        self._auth_config = Config.create("auth.toml")
コード例 #3
0
ファイル: config.py プロジェクト: freewayz/poetry
    def __init__(self):
        from poetry.config import Config

        super().__init__()

        self._config = Config.create('config.toml')
        self._auth_config = Config.create('auth.toml')
コード例 #4
0
    def __init__(self, name, url, disable_cache=False):
        if name == "pypi":
            raise ValueError("The name [pypi] is reserved for repositories")

        self._packages = []
        self._name = name
        self._url = url.rstrip("/")
        self._cache_dir = Path(CACHE_DIR) / "cache" / "repositories" / name

        self._cache = CacheManager(
            {
                "default": "releases",
                "serializer": "json",
                "stores": {
                    "releases": {"driver": "file", "path": str(self._cache_dir)},
                    "packages": {"driver": "dict"},
                    "matches": {"driver": "dict"},
                },
            }
        )

        self._session = CacheControl(
            requests.session(), cache=FileCache(str(self._cache_dir / "_http"))
        )

        url_parts = urlparse.urlparse(self._url)
        if not url_parts.username:
            self._session.auth = get_http_basic_auth(
                Config.create("auth.toml"), self.name
            )

        self._disable_cache = disable_cache
コード例 #5
0
def test_list_displays_set_get_setting(app, config):
    command = app.find("config")
    command._settings_config = Config(config.file)
    tester = CommandTester(command)

    tester.execute("settings.virtualenvs.create false")

    command._settings_config = Config(config.file)
    tester.execute("--list")

    expected = """settings.virtualenvs.create = false
settings.virtualenvs.in-project = false
settings.virtualenvs.path = "."
repositories = {}
"""

    assert expected == tester.io.fetch_output()
コード例 #6
0
def test_display_single_setting(app, config):
    command = app.find("config")
    command._settings_config = Config(config.file)
    tester = CommandTester(command)

    tester.execute("settings.virtualenvs.create")

    expected = """true
"""

    assert expected == tester.io.fetch_output()
コード例 #7
0
def test_list_displays_set_get_setting(app, config):
    command = app.find("config")
    command._config = Config(config.file)
    tester = CommandTester(command)

    tester.execute([
        ("command", command.get_name()),
        ("key", "settings.virtualenvs.create"),
        ("value", ["false"]),
    ])

    command._config = Config(config.file)
    tester.execute([("command", command.get_name()), ("--list", True)])

    expected = """settings.virtualenvs.create = false
settings.virtualenvs.in-project = false
settings.virtualenvs.path = "."
repositories = {}
"""

    assert tester.get_display(True) == expected
コード例 #8
0
def test_display_single_setting(app, config):
    command = app.find("config")
    command._config = Config(config.file)
    tester = CommandTester(command)

    tester.execute([("command", command.get_name()),
                    ("key", "settings.virtualenvs.create")])

    expected = """true
"""

    assert tester.get_display(True) == expected
コード例 #9
0
    def get(cls, reload=False, cwd=None):  # type: (IO, bool) -> Env
        if cls._env is not None and not reload:
            return cls._env

        # Check if we are inside a virtualenv or not
        in_venv = (os.environ.get("VIRTUAL_ENV") is not None
                   or hasattr(sys, "real_prefix")
                   or (hasattr(sys, "base_prefix")
                       and sys.base_prefix != sys.prefix))

        if not in_venv:
            # Checking if a local virtualenv exists
            if cwd and (cwd / ".venv").exists():
                venv = cwd / ".venv"

                return VirtualEnv(Path(venv))

            config = Config.create("config.toml")
            create_venv = config.setting("settings.virtualenvs.create", True)

            if not create_venv:
                return SystemEnv(Path(sys.prefix))

            venv_path = config.setting("settings.virtualenvs.path")
            if venv_path is None:
                venv_path = Path(CACHE_DIR) / "virtualenvs"
            else:
                venv_path = Path(venv_path)

            if cwd is None:
                cwd = Path.cwd()

            name = cwd.name
            name = "{}-py{}".format(
                name, ".".join([str(v) for v in sys.version_info[:2]]))

            venv = venv_path / name

            if not venv.exists():
                return SystemEnv(Path(sys.prefix))

            return VirtualEnv(venv)

        if os.environ.get("VIRTUAL_ENV") is not None:
            prefix = Path(os.environ["VIRTUAL_ENV"])
            base_prefix = None
        else:
            prefix = Path(sys.prefix)
            base_prefix = cls.get_base_prefix()

        return VirtualEnv(prefix, base_prefix)
コード例 #10
0
ファイル: env.py プロジェクト: simoncoulton/poetry
    def get(cls, cwd, reload=False):  # type: (Path, bool) -> Env
        if cls._env is not None and not reload:
            return cls._env

        # Check if we are inside a virtualenv or not
        in_venv = os.environ.get("VIRTUAL_ENV") is not None

        if not in_venv:
            config = Config.create("config.toml")

            # Checking if a local virtualenv exists
            venv_name = config.setting("settings.virtualenvs.name", ".venv")
            if (cwd / venv_name).exists():
                venv = cwd / venv_name

                return VirtualEnv(venv)

            create_venv = config.setting("settings.virtualenvs.create", True)

            if not create_venv:
                return SystemEnv(Path(sys.prefix))

            venv_path = config.setting("settings.virtualenvs.path")
            if venv_path is None:
                venv_path = Path(CACHE_DIR) / "virtualenvs"
            else:
                venv_path = Path(venv_path)

            name = cwd.name
            name = "{}-py{}".format(
                name, ".".join([str(v) for v in sys.version_info[:2]]))

            venv = venv_path / name

            if not venv.exists():
                return SystemEnv(Path(sys.prefix))

            return VirtualEnv(venv)

        if os.environ.get("VIRTUAL_ENV") is not None:
            prefix = Path(os.environ["VIRTUAL_ENV"])
            base_prefix = None
        else:
            prefix = Path(sys.prefix)
            base_prefix = cls.get_base_prefix()

        return VirtualEnv(prefix, base_prefix)
コード例 #11
0
ファイル: venv.py プロジェクト: singulared/poetry
    def create(cls, io, name=None, cwd=None):  # type: (...) -> Venv
        if "VIRTUAL_ENV" not in os.environ:
            # Not in a virtualenv
            # Checking if we need to create one

            # First we check if there is a .venv
            # at the root of the project.
            if cwd and (cwd / ".venv").exists():
                venv = cwd / ".venv"
            else:
                config = Config.create("config.toml")

                create_venv = config.setting("settings.virtualenvs.create")
                root_venv = config.setting("settings.virtualenvs.in-project")

                venv_path = config.setting("settings.virtualenvs.path")
                if root_venv:
                    if not cwd:
                        raise RuntimeError(
                            "Unable to determine the project's directory"
                        )

                    venv_path = cwd / ".venv"
                elif venv_path is None:
                    venv_path = Path(CACHE_DIR) / "virtualenvs"
                else:
                    venv_path = Path(venv_path)

                if not name:
                    name = Path.cwd().name

                name = "{}-py{}".format(
                    name, ".".join([str(v) for v in sys.version_info[:2]])
                )

                if root_venv:
                    venv = venv_path
                else:
                    venv = venv_path / name

                if not venv.exists():
                    if create_venv is False:
                        io.writeln(
                            "<fg=black;bg=yellow>"
                            "Skipping virtualenv creation, "
                            "as specified in config file."
                            "</>"
                        )

                        return cls()

                    io.writeln(
                        "Creating virtualenv <info>{}</> in {}".format(
                            name, str(venv_path)
                        )
                    )

                    cls.build(str(venv))
                else:
                    if io.is_very_verbose():
                        io.writeln(
                            "Virtualenv <info>{}</> already exists.".format(name)
                        )

            os.environ["VIRTUAL_ENV"] = str(venv)

        # venv detection:
        # stdlib venv may symlink sys.executable, so we can't use realpath.
        # but others can symlink *to* the venv Python,
        # so we can't just use sys.executable.
        # So we just check every item in the symlink tree (generally <= 3)
        p = os.path.normcase(sys.executable)
        paths = [p]
        while os.path.islink(p):
            p = os.path.normcase(os.path.join(os.path.dirname(p), os.readlink(p)))
            paths.append(p)

        p_venv = os.path.normcase(os.environ["VIRTUAL_ENV"])
        if any(p.startswith(p_venv) for p in paths):
            # Running properly in the virtualenv, don't need to do anything
            return cls()

        venv = os.environ["VIRTUAL_ENV"]

        return cls(venv)
コード例 #12
0
    def __init__(self):
        super().__init__()

        self._config = Config.create('config.toml')
        self._auth_config = Config.create('auth.toml')
コード例 #13
0
def get_http_basic_auth(repository_name):  # type: (str) -> tuple
    config = Config.create("auth.toml")
    repo_auth = config.setting("http-basic.{}".format(repository_name))
    if repo_auth:
        return repo_auth["username"], repo_auth["password"]
    return None
コード例 #14
0
ファイル: env.py プロジェクト: mgasner/poetry
    def __init__(self, config=None):  # type: (Config) -> None
        if config is None:
            config = Config.create("config.toml")

        self._config = config
コード例 #15
0
    def create_venv(cls, cwd, io, name=None):  # type: (Path, IO, bool) -> Env
        if cls._env is not None:
            return cls._env

        env = cls.get(cwd)
        if env.is_venv():
            # Already inside a virtualenv.
            return env

        config = Config.create("config.toml")

        create_venv = config.setting("settings.virtualenvs.create")
        root_venv = config.setting("settings.virtualenvs.in-project")

        venv_path = config.setting("settings.virtualenvs.path")
        if root_venv:
            venv_path = cwd / ".venv"
        elif venv_path is None:
            venv_path = Path(CACHE_DIR) / "virtualenvs"
        else:
            venv_path = Path(venv_path)

        if not name:
            name = cwd.name

        name = "{}-py{}".format(
            name, ".".join([str(v) for v in sys.version_info[:2]]))

        if root_venv:
            venv = venv_path
        else:
            venv = venv_path / name

        if not venv.exists():
            if create_venv is False:
                io.writeln("<fg=black;bg=yellow>"
                           "Skipping virtualenv creation, "
                           "as specified in config file."
                           "</>")

                return SystemEnv(Path(sys.prefix))

            io.writeln("Creating virtualenv <info>{}</> in {}".format(
                name, str(venv_path)))

            cls.build_venv(str(venv))
        else:
            if io.is_very_verbose():
                io.writeln(
                    "Virtualenv <info>{}</> already exists.".format(name))

        # venv detection:
        # stdlib venv may symlink sys.executable, so we can't use realpath.
        # but others can symlink *to* the venv Python,
        # so we can't just use sys.executable.
        # So we just check every item in the symlink tree (generally <= 3)
        p = os.path.normcase(sys.executable)
        paths = [p]
        while os.path.islink(p):
            p = os.path.normcase(
                os.path.join(os.path.dirname(p), os.readlink(p)))
            paths.append(p)

        p_venv = os.path.normcase(str(venv))
        if any(p.startswith(p_venv) for p in paths):
            # Running properly in the virtualenv, don't need to do anything
            return SystemEnv(Path(sys.prefix), cls.get_base_prefix())

        return VirtualEnv(venv)
コード例 #16
0
    def install(self, package, update=False):
        if package.source_type == "directory":
            self.install_directory(package, update=update)

            return

        if package.source_type == "git":
            self.install_git(package)

            return

        args = ["install", "--no-deps"]

        if package.source_type == "legacy" and package.source_url:
            parsed = urlparse.urlparse(package.source_url)
            if parsed.scheme == "http":
                self._io.write_error(
                    "    <warning>Installing from unsecure host: {}</warning>".
                    format(parsed.hostname))
                args += ["--trusted-host", parsed.hostname]

            auth = get_http_basic_auth(Config.create("auth.toml"),
                                       package.source_reference)
            if auth:
                index_url = "{scheme}://{username}:{password}@{netloc}{path}".format(
                    scheme=parsed.scheme,
                    username=auth[0],
                    password=auth[1],
                    netloc=parsed.netloc,
                    path=parsed.path,
                )
            else:
                index_url = package.source_url

            args += ["--index-url", index_url]

        if update:
            args.append("-U")

        if package.hashes and not package.source_type:
            # Format as a requirements.txt
            # We need to create a requirements.txt file
            # for each package in order to check hashes.
            # This is far from optimal but we do not have any
            # other choice since this is the only way for pip
            # to verify hashes.
            req = self.create_temporary_requirement(package)
            args += ["-r", req]

            try:
                self.run(*args)
            finally:
                os.unlink(req)
        else:
            req = self.requirement(package)
            if not isinstance(req, list):
                args.append(req)
            else:
                args += req

            self.run(*args)
コード例 #17
0
    def create(cls, io, name=None, cwd=None):  # type: (...) -> Venv
        if 'VIRTUAL_ENV' not in os.environ:
            # Not in a virtualenv
            # Checking if we need to create one

            # First we check if there is a .venv
            # at the root of the project.
            if cwd and (cwd / '.venv').exists():
                venv = cwd / '.venv'
            else:
                config = Config.create('config.toml')

                create_venv = config.setting('settings.virtualenvs.create')
                root_venv = config.setting('settings.virtualenvs.in-project')

                venv_path = config.setting('settings.virtualenvs.path')
                if root_venv:
                    if not cwd:
                        raise RuntimeError('Unbale to determine the project\'s directory')

                    venv_path = (cwd / '.venv')
                elif venv_path is None:
                    venv_path = Path(CACHE_DIR) / 'virtualenvs'
                else:
                    venv_path = Path(venv_path)

                if not name:
                    name = Path.cwd().name

                name = '{}-py{}'.format(
                    name, '.'.join([str(v) for v in sys.version_info[:2]])
                )

                if root_venv:
                    venv = venv_path
                else:
                    venv = venv_path / name

                if not venv.exists():
                    if create_venv is False:
                        io.writeln(
                            '<fg=black;bg=yellow>'
                            'Skipping virtualenv creation, '
                            'as specified in config file.'
                            '</>'
                        )

                        return cls()

                    io.writeln(
                        'Creating virtualenv <info>{}</> in {}'.format(
                            name, str(venv_path)
                        )
                    )

                    cls.build(str(venv))
                else:
                    if io.is_very_verbose():
                        io.writeln(
                            'Virtualenv <info>{}</> already exists.'.format(name)
                        )

            os.environ['VIRTUAL_ENV'] = str(venv)

        # venv detection:
        # stdlib venv may symlink sys.executable, so we can't use realpath.
        # but others can symlink *to* the venv Python,
        # so we can't just use sys.executable.
        # So we just check every item in the symlink tree (generally <= 3)
        p = os.path.normcase(sys.executable)
        paths = [p]
        while os.path.islink(p):
            p = os.path.normcase(
                os.path.join(os.path.dirname(p), os.readlink(p)))
            paths.append(p)

        p_venv = os.path.normcase(os.environ['VIRTUAL_ENV'])
        if any(p.startswith(p_venv) for p in paths):
            # Running properly in the virtualenv, don't need to do anything
            return cls()

        venv = os.environ['VIRTUAL_ENV']

        return cls(venv)
コード例 #18
0
ファイル: conftest.py プロジェクト: zymergen-luke/poetry
def config():  # type: () -> Config
    with tempfile.NamedTemporaryFile() as f:
        f.close()

        return Config(TomlFile(f.name))
コード例 #19
0
    def create(cls, io, name=None) -> 'Venv':
        if 'VIRTUAL_ENV' not in os.environ:
            # Not in a virtualenv
            # Checking if we need to create one
            config = Config.create('config.toml')

            create_venv = config.setting('settings.virtualenvs.create')

            venv_path = config.setting('settings.virtualenvs.path')
            if venv_path is None:
                venv_path = Path(CACHE_DIR) / 'virtualenvs'
            else:
                venv_path = Path(venv_path)

            if not name:
                name = Path.cwd().name

            name = f'{name}-py{".".join([str(v) for v in sys.version_info[:2]])}'

            venv = venv_path / name
            if not venv.exists():
                if create_venv is False:
                    io.writeln(
                        '<fg=black;bg=yellow>'
                        'Skipping virtualenv creation, '
                        'as specified in config file.'
                        '</>'
                    )

                    return cls()

                io.writeln(
                    f'Creating virtualenv <info>{name}</> in {str(venv_path)}'
                )
                builder = EnvBuilder(with_pip=True)
                builder.create(str(venv))
            else:
                if io.is_very_verbose():
                    io.writeln(f'Virtualenv <info>{name}</> already exists.')

            os.environ['VIRTUAL_ENV'] = str(venv)

        # venv detection:
        # stdlib venv may symlink sys.executable, so we can't use realpath.
        # but others can symlink *to* the venv Python,
        # so we can't just use sys.executable.
        # So we just check every item in the symlink tree (generally <= 3)
        p = os.path.normcase(sys.executable)
        paths = [p]
        while os.path.islink(p):
            p = os.path.normcase(
                os.path.join(os.path.dirname(p), os.readlink(p)))
            paths.append(p)

        p_venv = os.path.normcase(os.environ['VIRTUAL_ENV'])
        if any(p.startswith(p_venv) for p in paths):
            # Running properly in the virtualenv, don't need to do anything
            return cls()

        venv = os.environ['VIRTUAL_ENV']

        return cls(venv)