Esempio n. 1
0
    def get_paths(self):
        # type: () -> Optional[Dict[str, str]]
        """
        Get the paths for the environment by running a subcommand

        :return: The python paths for the environment
        :rtype: Dict[str, str]
        """
        tmpfile = vistir.path.create_tracked_tempfile(suffix=".json")
        tmpfile.close()
        tmpfile_path = make_posix(tmpfile.name)
        py_command = self.build_command(python_lib=True,
                                        python_inc=True,
                                        scripts=True,
                                        py_version=True)
        command = [self.python, "-c", py_command.format(tmpfile_path)]
        c = subprocess_run(command)
        if c.returncode == 0:
            paths = {}
            with open(tmpfile_path, "r", encoding="utf-8") as fh:
                paths = json.load(fh)
            if "purelib" in paths:
                paths["libdir"] = paths["purelib"] = make_posix(
                    paths["purelib"])
            for key in ("platlib", "scripts", "platstdlib", "stdlib",
                        "include", "platinclude"):
                if key in paths:
                    paths[key] = make_posix(paths[key])
            return paths
        else:
            vistir.misc.echo(f"Failed to load paths: {c.stderr}", fg="yellow")
            vistir.misc.echo(f"Output: {c.stdout}", fg="yellow")
        return None
Esempio n. 2
0
def check_github_ssh():
    res = False
    try:
        # `ssh -T [email protected]` will return successfully with return_code==1
        # and message 'Hi <username>! You've successfully authenticated, but
        # GitHub does not provide shell access.' if ssh keys are available and
        # registered with GitHub. Otherwise, the command will fail with
        # return_code=255 and say 'Permission denied (publickey).'
        c = subprocess_run(
            'ssh -o StrictHostKeyChecking=no -o CheckHostIP=no -T [email protected]',
            timeout=30,
            shell=True)
        res = True if c.returncode == 1 else False
    except KeyboardInterrupt:
        warnings.warn("KeyboardInterrupt while checking GitHub ssh access",
                      RuntimeWarning)
    except Exception:
        pass
    global HAS_WARNED_GITHUB
    if not res and not HAS_WARNED_GITHUB:
        warnings.warn('Cannot connect to GitHub via SSH', RuntimeWarning)
        warnings.warn('Will skip tests requiring SSH access to GitHub',
                      RuntimeWarning)
        HAS_WARNED_GITHUB = True
    return res
Esempio n. 3
0
    def get_include_path(self):
        # type: () -> Optional[Dict[str, str]]
        """Get the include path for the environment

        :return: The python include path for the environment
        :rtype: Dict[str, str]
        """
        tmpfile = vistir.path.create_tracked_tempfile(suffix=".json")
        tmpfile.close()
        tmpfile_path = make_posix(tmpfile.name)
        py_command = (
            "import distutils.sysconfig, io, json, sys; paths = {{u'include': "
            "u'{{0}}'.format(distutils.sysconfig.get_python_inc(plat_specific=0)), "
            "u'platinclude': u'{{0}}'.format(distutils.sysconfig.get_python_inc("
            "plat_specific=1)) }}; value = u'{{0}}'.format(json.dumps(paths));"
            "fh = io.open('{0}', 'w'); fh.write(value); fh.close()")
        command = [self.python, "-c", py_command.format(tmpfile_path)]
        c = subprocess_run(command)
        if c.returncode == 0:
            paths = []
            with open(tmpfile_path, "r", encoding="utf-8") as fh:
                paths = json.load(fh)
            for key in ("include", "platinclude"):
                if key in paths:
                    paths[key] = make_posix(paths[key])
            return paths
        else:
            vistir.misc.echo(f"Failed to load paths: {c.stderr}", fg="yellow")
            vistir.misc.echo(f"Output: {c.stdout}", fg="yellow")
        return None
Esempio n. 4
0
def run_open(state, module, *args, **kwargs):
    """View a given module in your editor.

    This uses the EDITOR environment variable. You can temporarily override it,
    for example:

        EDITOR=atom pipenv open requests
    """
    from ..core import ensure_project, inline_activate_virtual_environment

    # Ensure that virtualenv is available.
    ensure_project(
        state.project,
        three=state.three,
        python=state.python,
        validate=False,
        pypi_mirror=state.pypi_mirror,
    )
    c = subprocess_run([
        state.project._which("python"), "-c",
        "import {0}; print({0}.__file__)".format(module)
    ])
    if c.returncode:
        echo(crayons.red("Module not found!"))
        sys.exit(1)
    if "__init__.py" in c.stdout:
        p = os.path.dirname(c.stdout.strip().rstrip("cdo"))
    else:
        p = c.stdout.strip().rstrip("cdo")
    echo(crayons.normal(f"Opening {p!r} in your EDITOR.", bold=True))
    inline_activate_virtual_environment(state.project)
    edit(filename=p)
    return 0
Esempio n. 5
0
 def _run(self, *args, **kwargs):
     timeout = kwargs.pop('timeout', 30)
     if kwargs:
         k = list(kwargs.keys())[0]
         raise TypeError(f'unexpected keyword argument {k!r}')
     args = (self.cmd, ) + tuple(args)
     c = subprocess_run(args, timeout=timeout)
     if c.returncode != 0:
         raise InstallerError(f'failed to run {args}', c)
     return c
Esempio n. 6
0
def test_install_local_vcs_not_in_lockfile(PipenvInstance):
    with PipenvInstance(chdir=True) as p:
        # six_path = os.path.join(p.path, "six")
        six_path = p._pipfile.get_fixture_path("git/six/").as_posix()
        c = subprocess_run(["git", "clone", six_path, "./six"])
        assert c.returncode == 0
        c = p.pipenv("install -e ./six")
        assert c.returncode == 0
        six_key = list(p.pipfile["packages"].keys())[0]
        # we don't need the rest of the test anymore, this just works on its own
        assert six_key == "six"
Esempio n. 7
0
def test_env(PipenvInstance):
    with PipenvInstance(pipfile=False, chdir=True) as p:
        with open(os.path.join(p.path, ".env"), "w") as f:
            f.write("HELLO=WORLD")
        c = subprocess_run([
            'pipenv', 'run', 'python', '-c',
            "import os; print(os.environ['HELLO'])"
        ],
                           env=p.env)
        assert c.returncode == 0
        assert 'WORLD' in c.stdout
Esempio n. 8
0
def test_local_vcs_urls_work(PipenvInstance, tmpdir):
    six_dir = tmpdir.join("six")
    six_path = Path(six_dir.strpath)
    with PipenvInstance(chdir=True) as p:
        c = subprocess_run(
            ["git", "clone", "https://github.com/benjaminp/six.git", six_dir.strpath]
        )
        assert c.returncode == 0

        c = p.pipenv("install git+{0}#egg=six".format(six_path.as_uri()))
        assert c.returncode == 0
        assert "six" in p.pipfile["packages"]
Esempio n. 9
0
    def sys_prefix(self):
        # type: () -> str
        """
        The prefix run inside the context of the environment

        :return: The python prefix inside the environment
        :rtype: :data:`sys.prefix`
        """

        command = [self.python, "-c", "import sys; print(sys.prefix)"]
        c = subprocess_run(command)
        sys_prefix = Path(c.stdout.strip()).as_posix()
        return sys_prefix
Esempio n. 10
0
    def get_lib_paths(self):
        # type: () -> Dict[str, str]
        """Get the include path for the environment

        :return: The python include path for the environment
        :rtype: Dict[str, str]
        """
        tmpfile = vistir.path.create_tracked_tempfile(suffix=".json")
        tmpfile.close()
        tmpfile_path = make_posix(tmpfile.name)
        py_command = self.build_command(python_lib=True)
        command = [self.python, "-c", py_command.format(tmpfile_path)]
        c = subprocess_run(command)
        paths = None
        if c.returncode == 0:
            paths = {}
            with open(tmpfile_path, "r", encoding="utf-8") as fh:
                paths = json.load(fh)
            if "purelib" in paths:
                paths["libdir"] = paths["purelib"] = make_posix(
                    paths["purelib"])
            for key in ("platlib", "platstdlib", "stdlib"):
                if key in paths:
                    paths[key] = make_posix(paths[key])
            return paths
        else:
            vistir.misc.echo(f"Failed to load paths: {c.stderr}", fg="yellow")
            vistir.misc.echo(f"Output: {c.stdout}", fg="yellow")
        if not paths:
            if not self.prefix.joinpath("lib").exists():
                return {}
            stdlib_path = next(
                iter([
                    p for p in self.prefix.joinpath("lib").iterdir()
                    if p.name.startswith("python")
                ]), None)
            lib_path = None
            if stdlib_path:
                lib_path = next(
                    iter([
                        p.as_posix() for p in stdlib_path.iterdir()
                        if p.name == "site-packages"
                    ]))
                paths = {"stdlib": stdlib_path.as_posix()}
                if lib_path:
                    paths["purelib"] = lib_path
                return paths
        return {}
Esempio n. 11
0
def test_system_and_deploy_work(PipenvInstance):
    with PipenvInstance(chdir=True) as p:
        c = p.pipenv("install tablib")
        assert c.returncode == 0
        c = p.pipenv("--rm")
        assert c.returncode == 0
        c = subprocess_run(["virtualenv", ".venv"])
        assert c.returncode == 0
        c = p.pipenv("install --system --deploy")
        assert c.returncode == 0
        c = p.pipenv("--rm")
        assert c.returncode == 0
        Path(p.pipfile_path).write_text("""
[packages]
tablib = "*"
        """.strip())
        c = p.pipenv("install --system")
        assert c.returncode == 0
Esempio n. 12
0
def test_requirements_to_pipfile(PipenvInstance, pypi):

    with PipenvInstance(pipfile=False, chdir=True) as p:

        # Write a requirements file
        with open("requirements.txt", "w") as f:
            f.write(f"-i {pypi.url}\nrequests[socks]==2.19.1\n")

        c = p.pipenv("install")
        assert c.returncode == 0
        print(c.stdout)
        print(c.stderr)
        print(subprocess_run(["ls", "-l"]).stdout)

        # assert stuff in pipfile
        assert "requests" in p.pipfile["packages"]
        assert "extras" in p.pipfile["packages"]["requests"]

        # assert stuff in lockfile
        assert "requests" in p.lockfile["default"]
        assert "chardet" in p.lockfile["default"]
        assert "idna" in p.lockfile["default"]
        assert "urllib3" in p.lockfile["default"]
        assert "pysocks" in p.lockfile["default"]
Esempio n. 13
0
def test_proper_names_unamanged_virtualenv(PipenvInstance):
    with PipenvInstance(chdir=True):
        c = subprocess_run(['python', '-m', 'virtualenv', '.venv'])
        assert c.returncode == 0
        project = Project()
        assert project.proper_names == []
Esempio n. 14
0
def check_for_mercurial():
    c = subprocess_run("hg --help", shell=True)
    return c.returncode == 0
Esempio n. 15
0
def test_man(PipenvInstance):
    with PipenvInstance():
        c = subprocess_run(["pipenv", "--man"])
        assert c.returncode == 0, c.stderr