Ejemplo n.º 1
0
 def __init__(self, filename="Pipfile.lock", extra=None, **kwargs):
     extra = kwargs.pop("extra", [])
     message = "{} {} {}".format(
         crayons.normal("You need to run", bold=True),
         crayons.red("$ pipenv lock", bold=True),
         crayons.normal("before you can continue.", bold=True))
     super().__init__(filename, message=message, extra=extra, **kwargs)
Ejemplo n.º 2
0
 def __init__(self, path, **kwargs):
     message = "{} {}\n{}".format(
         crayons.cyan("Corrupt cache file"),
         crayons.normal(f"{path!s}"),
         crayons.normal('Consider trying "pipenv lock --clear" to clear the cache.')
     )
     PipenvException.__init__(self, message=message)
Ejemplo n.º 3
0
 def __init__(self, req=None):
     from .utils import VCS_LIST
     keys = ("name", "path",) + VCS_LIST + ("line", "uri", "url", "relpath")
     if req is not None:
         possible_display_values = [getattr(req, value, None) for value in keys]
         req_value = next(iter(
             val for val in possible_display_values if val is not None
         ), None)
         if not req_value:
             getstate_fn = getattr(req, "__getstate__", None)
             slots = getattr(req, "__slots__", None)
             keys_fn = getattr(req, "keys", None)
             if getstate_fn:
                 req_value = getstate_fn()
             elif slots:
                 slot_vals = [
                     (k, getattr(req, k, None)) for k in slots
                     if getattr(req, k, None)
                 ]
                 req_value = "\n".join([
                     f"    {k}: {v}" for k, v in slot_vals
                 ])
             elif keys_fn:
                 values = [(k, req.get(k)) for k in keys_fn() if req.get(k)]
                 req_value = "\n".join([
                     f"    {k}: {v}" for k, v in values
                 ])
             else:
                 req_value = getattr(req.line_instance, "line", None)
     message = "{} {}".format(
         crayons.normal(decode_for_output("Failed creating requirement instance")),
         crayons.normal(decode_for_output(f"{req_value!r}"))
     )
     extra = [str(req)]
     PipenvException.__init__(self, message, extra=extra)
Ejemplo n.º 4
0
 def __init__(self, filename, message=None, **kwargs):
     extra = kwargs.pop("extra", [])
     if not message:
         message = crayons.normal("Please ensure that the file exists!", bold=True)
     message = self.formatted_message.format(
         crayons.normal(f"{filename} not found!", bold=True),
         message
     )
     FileError.__init__(self, filename=filename, hint=decode_for_output(message), **kwargs)
     self.extra = extra
Ejemplo n.º 5
0
 def show(self, file=None):
     if file is None:
         file = vistir.misc.get_text_stderr()
     message = "{}\n{}".format(
         crayons.normal("Failed parsing JSON results:", bold=True),
         decode_for_output(self.message.strip(), file))
     click_echo(message, err=True)
     if self.error_text:
         click_echo("{} {}".format(crayons.normal("ERROR TEXT:", bold=True),
                                   decode_for_output(self.error_text,
                                                     file)),
                    err=True)
Ejemplo n.º 6
0
 def show(self, file=None):
     if file is None:
         file = vistir.misc.get_text_stderr()
     click_echo("{} {}".format(
         crayons.red("Error running command: "),
         crayons.normal(decode_for_output(f"$ {self.cmd}", file),
                        bold=True)),
                err=True)
     if self.out:
         click_echo("{} {}".format(crayons.normal("OUTPUT: "),
                                   decode_for_output(self.out, file)),
                    err=True)
     if self.err:
         click_echo("{} {}".format(crayons.normal("STDERR: "),
                                   decode_for_output(self.err, file)),
                    err=True)
Ejemplo n.º 7
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
Ejemplo n.º 8
0
 def __init__(self, filename="Pipfile", extra=None, **kwargs):
     extra = kwargs.pop("extra", [])
     message = ("{} {}".format(
         crayons.red("Aborting!", bold=True),
         crayons.normal(
             "Please ensure that the file exists and is located in your"
             " project root directory.",
             bold=True)))
     super().__init__(filename, message=message, extra=extra, **kwargs)
Ejemplo n.º 9
0
 def __init__(self, message=None, ctx=None, **kwargs):
     formatted_message = "{0}: {1}"
     msg_prefix = crayons.red("ERROR:", bold=True)
     if not message:
         message = "Pipenv encountered a problem and had to exit."
     message = formatted_message.format(msg_prefix, crayons.normal(message, bold=True))
     self.message = message
     extra = kwargs.pop("extra", [])
     UsageError.__init__(self, decode_for_output(message), ctx)
     self.extra = extra
Ejemplo n.º 10
0
 def __init__(self, package, **kwargs):
     package_message = ""
     if package is not None:
         package_message = "Couldn't install package: {}\n".format(
             crayons.normal(f"{package!s}", bold=True))
     message = "{} {}".format(
         f"{package_message}",
         crayons.yellow("Package installation failed..."))
     extra = kwargs.pop("extra", [])
     PipenvException.__init__(self, message=message, extra=extra, **kwargs)
Ejemplo n.º 11
0
 def __init__(self, option_name="system", message=None, ctx=None, **kwargs):
     extra = kwargs.pop("extra", [])
     extra += [
         "{}: --system is intended to be used for Pipfile installation, "
         "not installation of specific packages. Aborting.".format(
             crayons.red("Warning", bold=True)
         ),
     ]
     if message is None:
         message = str(
             crayons.cyan("See also: {}".format(crayons.normal("--deploy flag.")))
         )
     super().__init__(option_name, message=message, ctx=ctx, extra=extra, **kwargs)
Ejemplo n.º 12
0
def shell(
    state,
    fancy=False,
    shell_args=None,
    anyway=False,
):
    """Spawns a shell within the virtualenv."""
    from ..core import do_shell, load_dot_env

    # Prevent user from activating nested environments.
    if "PIPENV_ACTIVE" in os.environ:
        # If PIPENV_ACTIVE is set, VIRTUAL_ENV should always be set too.
        venv_name = os.environ.get("VIRTUAL_ENV",
                                   "UNKNOWN_VIRTUAL_ENVIRONMENT")
        if not anyway:
            echo(
                "{} {} {}\nNo action taken to avoid nested environments.".
                format(
                    crayons.normal("Shell for"),
                    crayons.green(venv_name, bold=True),
                    crayons.normal("already activated.", bold=True),
                ),
                err=True,
            )
            sys.exit(1)
    # Load .env file.
    load_dot_env(state.project)
    # Use fancy mode for Windows.
    if os.name == "nt":
        fancy = True
    do_shell(
        state.project,
        three=state.three,
        python=state.python,
        fancy=fancy,
        shell_args=shell_args,
        pypi_mirror=state.pypi_mirror,
    )
Ejemplo n.º 13
0
 def __init__(self, package, command, return_values, return_code, **kwargs):
     extra = [
         "{} {}".format(crayons.cyan("Attempted to run command: "),
                        crayons.yellow(f"$ {command!r}", bold=True))
     ]
     extra.extend([
         crayons.cyan(line.strip()) for line in return_values.splitlines()
     ])
     if isinstance(package, (tuple, list, set)):
         package = " ".join(package)
     message = "{!s} {!s}...".format(
         crayons.normal("Failed to uninstall package(s)"),
         crayons.yellow(f"{package}!s", bold=True))
     self.exit_code = return_code
     PipenvException.__init__(self, message=message, extra=extra)
     self.extra = extra
Ejemplo n.º 14
0
        default=False,
        help="Output Python interpreter information.")
@option("--envs",
        is_flag=True,
        default=False,
        help="Output Environment Variable options.")
@option("--rm", is_flag=True, default=False, help="Remove the virtualenv.")
@option("--bare", is_flag=True, default=False, help="Minimal output.")
@option("--man", is_flag=True, default=False, help="Display manpage.")
@option(
    "--support",
    is_flag=True,
    help="Output diagnostic information for use in GitHub issues.",
)
@general_options
@version_option(prog_name=crayons.normal("pipenv", bold=True),
                version=__version__)
@pass_state
@pass_context
def cli(
    ctx,
    state,
    where=False,
    venv=False,
    py=False,
    envs=False,
    rm=False,
    bare=False,
    man=False,
    support=None,
    help=False,
Ejemplo n.º 15
0
def cli(
    ctx,
    state,
    where=False,
    venv=False,
    py=False,
    envs=False,
    rm=False,
    bare=False,
    man=False,
    support=None,
    help=False,
    site_packages=None,
    **kwargs,
):
    from pipenv.utils.spinner import create_spinner

    from ..core import (
        cleanup_virtualenv,
        do_clear,
        do_py,
        do_where,
        ensure_project,
        format_help,
        system_which,
        warn_in_virtualenv,
    )

    if man:
        if system_which("man"):
            path = os.path.join(os.path.dirname(os.path.dirname(__file__)),
                                "pipenv.1")
            os.execle(system_which("man"), "man", path, os.environ)
            return 0
        else:
            secho(
                "man does not appear to be available on your system.",
                fg="yellow",
                bold=True,
                err=True,
            )
            return 1
    if envs:
        echo(
            "The following environment variables can be set, to do various things:\n"
        )
        for key in state.project.__dict__:
            if key.startswith("PIPENV"):
                echo(f"  - {crayons.normal(key, bold=True)}")
        echo("\nYou can learn more at:\n   {}".format(
            crayons.green(
                "https://pipenv.pypa.io/en/latest/advanced/#configuration-with-environment-variables"
            )))
        return 0
    warn_in_virtualenv(state.project)
    if ctx.invoked_subcommand is None:
        # --where was passed...
        if where:
            do_where(state.project, bare=True)
            return 0
        elif py:
            do_py(state.project, ctx=ctx)
            return 0
        # --support was passed...
        elif support:
            from ..help import get_pipenv_diagnostics

            get_pipenv_diagnostics(state.project)
            return 0
        # --clear was passed...
        elif state.clear:
            do_clear(state.project)
            return 0
        # --venv was passed...
        elif venv:
            # There is no virtualenv yet.
            if not state.project.virtualenv_exists:
                echo(
                    "{}({}){}".format(
                        crayons.red(
                            "No virtualenv has been created for this project"),
                        crayons.normal(state.project.project_directory,
                                       bold=True),
                        crayons.red(" yet!"),
                    ),
                    err=True,
                )
                ctx.abort()
            else:
                echo(state.project.virtualenv_location)
                return 0
        # --rm was passed...
        elif rm:
            # Abort if --system (or running in a virtualenv).
            if state.project.s.PIPENV_USE_SYSTEM or environments.is_in_virtualenv(
            ):
                echo(
                    crayons.red(
                        "You are attempting to remove a virtualenv that "
                        "Pipenv did not create. Aborting."))
                ctx.abort()
            if state.project.virtualenv_exists:
                loc = state.project.virtualenv_location
                echo(
                    crayons.normal("{} ({})...".format(
                        crayons.normal("Removing virtualenv", bold=True),
                        crayons.green(loc),
                    )))
                with create_spinner(text="Running...",
                                    setting=state.project.s):
                    # Remove the virtualenv.
                    cleanup_virtualenv(state.project, bare=True)
                return 0
            else:
                echo(
                    crayons.red(
                        "No virtualenv has been created for this project yet!",
                        bold=True,
                    ),
                    err=True,
                )
                ctx.abort()
    # --python or --three was passed...
    if (state.python or state.three is not None) or state.site_packages:
        ensure_project(
            state.project,
            three=state.three,
            python=state.python,
            warn=True,
            site_packages=state.site_packages,
            pypi_mirror=state.pypi_mirror,
            clear=state.clear,
        )
    # Check this again before exiting for empty ``pipenv`` command.
    elif ctx.invoked_subcommand is None:
        # Display help to user, if no commands were passed.
        echo(format_help(ctx.get_help()))
Ejemplo n.º 16
0
def update(ctx, state, bare=False, dry_run=None, outdated=False, **kwargs):
    """Runs lock, then sync."""
    from ..core import do_lock, do_outdated, do_sync, ensure_project

    ensure_project(
        state.project,
        three=state.three,
        python=state.python,
        pypi_mirror=state.pypi_mirror,
        warn=(not state.quiet),
        site_packages=state.site_packages,
        clear=state.clear,
    )
    if not outdated:
        outdated = bool(dry_run)
    if outdated:
        do_outdated(
            state.project,
            clear=state.clear,
            pre=state.installstate.pre,
            pypi_mirror=state.pypi_mirror,
        )
    packages = [p for p in state.installstate.packages if p]
    editable = [p for p in state.installstate.editables if p]
    if not packages:
        echo("{} {} {} {}{}".format(
            crayons.normal("Running", bold=True),
            crayons.yellow("$ pipenv lock", bold=True),
            crayons.normal("then", bold=True),
            crayons.yellow("$ pipenv sync", bold=True),
            crayons.normal(".", bold=True),
        ))
    else:
        for package in packages + editable:
            if package not in state.project.all_packages:
                echo(
                    "{}: {} was not found in your Pipfile! Aborting."
                    "".format(
                        crayons.red("Warning", bold=True),
                        crayons.green(package, bold=True),
                    ),
                    err=True,
                )
                ctx.abort()
    do_lock(
        state.project,
        ctx=ctx,
        clear=state.clear,
        pre=state.installstate.pre,
        keep_outdated=state.installstate.keep_outdated,
        pypi_mirror=state.pypi_mirror,
        write=not state.quiet,
    )
    do_sync(
        state.project,
        dev=state.installstate.dev,
        three=state.three,
        python=state.python,
        bare=bare,
        dont_upgrade=not state.installstate.keep_outdated,
        user=False,
        clear=state.clear,
        unused=False,
        sequential=state.installstate.sequential,
        pypi_mirror=state.pypi_mirror,
    )
Ejemplo n.º 17
0
 def __init__(self, message=None, **kwargs):
     if not message:
         message = str(crayons.normal("Aborting deploy", bold=True))
     extra = kwargs.pop("extra", [])
     PipenvUsageError.__init__(self, message=message, extra=extra, **kwargs)