Beispiel #1
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
Beispiel #2
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
Beispiel #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:
            click.secho(f"Failed to load paths: {c.stderr}", fg="yellow")
            click.secho(f"Output: {c.stdout}", fg="yellow")
        return None
Beispiel #4
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"
Beispiel #5
0
 def _run(self, *args, **kwargs):
     timeout = kwargs.pop("timeout", 30)
     shell = kwargs.pop("shell", False)
     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, shell=shell)
     if c.returncode != 0:
         raise InstallerError(f"failed to run {args}", c)
     return c
Beispiel #6
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
Beispiel #7
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"]
Beispiel #8
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:
            click.secho(f"Failed to load paths: {c.stderr}", fg="yellow")
            click.secho(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 {}
Beispiel #9
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:
            click.echo(f"Failed to load paths: {c.stderr}", fg="yellow")
            click.echo(f"Output: {c.stdout}", fg="yellow")
        return None
Beispiel #10
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 == []
Beispiel #11
0
def test_pipenv_run_with_special_chars_windows(PipenvInstance):
    with PipenvInstance():
        c = subprocess_run(["pipenv", "run", "echo", "[3-1]"])
        assert c.returncode == 0, c.stderr
Beispiel #12
0
def test_man(PipenvInstance):
    with PipenvInstance():
        c = subprocess_run(["pipenv", "--man"])
        assert c.returncode == 0, c.stderr
Beispiel #13
0
def check_for_mercurial():
    c = subprocess_run("hg --help", shell=True)
    return c.returncode == 0