Exemple #1
0
def __install(package, *args, **kwargs):
    """
    Python2/3-compatible Pip install function.
    
    :param package: package name
    :param args:    options to be used with the pip install command
    :param kwargs:  keyword-arguments to be used with the pip install command
    """
    global pip_proc
    __check_pip_req_tracker()
    if "-v" in args or "--verbose" in args:
        verbose = True
    else:
        verbose = False
        args += ("-v", )
    error = kwargs.pop("error", False)
    cmd = ["install", "-U"] + __parse_args(*args, **kwargs) + [package.strip()]
    for l in __pip_run(cmd):
        if verbose:
            print(l)
        if not error:
            continue
        if l.startswith("pip._internal.exceptions") or \
           l.startswith("DistributionNotFound"):
            pip_proc.kill()
            raise PipError(l.split(": ", 1)[1])
        elif l.startswith("Successfully installed"):
            m = list(filter(lambda p: p[0] == package, PREGEX.findall(l[23:])))
            if len(m) == 0:
                raise PipError("Installation of {} failed".format(package))
    return PipPackage(package, error)
    def open_in_editor(self, options, args):
        editor = self._determine_editor(options)

        fname = self.configuration.get_file_to_edit()
        if fname is None:
            raise PipError("Could not determine appropriate file.")

        try:
            subprocess.check_call([editor, fname])
        except subprocess.CalledProcessError as e:
            raise PipError("Editor Subprocess exited with exit code {}".format(
                e.returncode))
Exemple #3
0
    def _determine_file(self, options, need_value):
        # type: (Values, bool) -> Optional[Kind]
        file_options = [
            key for key, value in (
                (kinds.USER, options.user_file),
                (kinds.GLOBAL, options.global_file),
                (kinds.SITE, options.site_file),
            ) if value
        ]

        if not file_options:
            if not need_value:
                return None
            # Default to user, unless there's a site file.
            elif any(
                    os.path.exists(site_config_file) for site_config_file in
                    get_configuration_files()[kinds.SITE]):
                return kinds.SITE
            else:
                return kinds.USER
        elif len(file_options) == 1:
            return file_options[0]

        raise PipError("Need exactly one file to operate upon "
                       "(--user, --site, --global) to perform.")
Exemple #4
0
 def __init__(self, name, error=True):
     self.name = name
     self.top_level = []
     cmd = ["show", name]
     venv = os.environ.get('VIRTUAL_ENV', "")
     for i in range(2):
         for line in globals()['__pip_run'](cmd, False):
             try:
                 k, v = line.strip().split(": ")
                 k = slugify(k).replace("-", "_")
                 if k.startswith("require"):
                     v = v.split(", ")
                 setattr(self, k, v)
             except ValueError:
                 continue
         if hasattr(self, "version") or venv == "":
             break
         else:  # after the first guess, if the package was not found in the
             #  virtual environment, deactivate it to retry with main Pip
             globals()['__deactivate']()
     # afterwards, re-enable the virtual environment if relevant
     if venv != "":
         globals()['__activate'](venv)
     if not hasattr(self, "version"):
         if error:
             raise PipError("Pip package not found: {}".format(name))
     else:
         name = "{}-{}*".format(self.name, self.version)
         try:
             pkgloc = list(Path(self.location).find(name))[0]
             tl = list(pkgloc.find("top_level.txt"))[0]
             self.top_level = tl.read_lines()
         except IndexError:
             pass
Exemple #5
0
 def _determine_editor(self, options):
     if options.editor is not None:
         return options.editor
     elif "VISUAL" in os.environ:
         return os.environ["VISUAL"]
     elif "EDITOR" in os.environ:
         return os.environ["EDITOR"]
     else:
         raise PipError("Could not determine editor to use.")
Exemple #6
0
 def _save_configuration(self) -> None:
     # We successfully ran a modifying command. Need to save the
     # configuration.
     try:
         self.configuration.save()
     except Exception:
         logger.exception(
             "Unable to save configuration. Please report this as a bug.")
         raise PipError("Internal Error.")
Exemple #7
0
    def _determine_file(self, options, need_value):
        # Convert legacy venv_file option to site_file or error
        if options.venv_file and not options.site_file:
            if running_under_virtualenv():
                options.site_file = True
                deprecated(
                    "The --venv option has been deprecated.",
                    replacement="--site",
                    gone_in="19.3",
                )
            else:
                raise PipError(
                    "Legacy --venv option requires a virtual environment. "
                    "Use --site instead."
                )

        file_options = [
            key
            for key, value in (
                (kinds.USER, options.user_file),
                (kinds.GLOBAL, options.global_file),
                (kinds.SITE, options.site_file),
            )
            if value
        ]

        if not file_options:
            if not need_value:
                return None
            # Default to user, unless there's a site file.
            elif any(
                os.path.exists(site_config_file)
                for site_config_file in get_configuration_files()[kinds.SITE]
            ):
                return kinds.SITE
            else:
                return kinds.USER
        elif len(file_options) == 1:
            return file_options[0]

        raise PipError(
            "Need exactly one file to operate upon "
            "(--user, --site, --global) to perform."
        )
Exemple #8
0
 def _save_configuration(self):
     # We successfully ran a modifying command. Need to save the
     # settings.py.
     try:
         self.configuration.save()
     except Exception:
         logger.error(
             "Unable to save settings.py. Please report this as a bug.",
             exc_info=1)
         raise PipError("Internal Error.")
Exemple #9
0
    def _get_n_args(self, args: List[str], example: str, n: int) -> Any:
        """Helper to make sure the command got the right number of arguments"""
        if len(args) != n:
            msg = ("Got unexpected number of arguments, expected {}. "
                   '(example: "{} config {}")').format(n, get_prog(), example)
            raise PipError(msg)

        if n == 1:
            return args[0]
        else:
            return args
Exemple #10
0
    def _get_n_args(self, args, example, n):
        """Helper to make sure the job_commands got the right number of arguments
        """
        if len(args) != n:
            msg = ('Got unexpected number of arguments, expected {}. '
                   '(example: "{} config {}")').format(n, get_prog(), example)
            raise PipError(msg)

        if n == 1:
            return args[0]
        else:
            return args
Exemple #11
0
    def open_in_editor(self, options: Values, args: List[str]) -> None:
        editor = self._determine_editor(options)

        fname = self.configuration.get_file_to_edit()
        if fname is None:
            raise PipError("Could not determine appropriate file.")
        elif '"' in fname:
            # This shouldn't happen, unless we see a username like that.
            # If that happens, we'd appreciate a pull request fixing this.
            raise PipError(
                f'Can not open an editor for a file name containing "\n{fname}'
            )

        try:
            subprocess.check_call(f'{editor} "{fname}"', shell=True)
        except FileNotFoundError as e:
            if not e.filename:
                e.filename = editor
            raise
        except subprocess.CalledProcessError as e:
            raise PipError("Editor Subprocess exited with exit code {}".format(
                e.returncode))
Exemple #12
0
    def _determine_file(self, options, need_value):
        file_options = {
            kinds.USER: options.user_file,
            kinds.GLOBAL: options.global_file,
            kinds.VENV: options.venv_file
        }

        if sum(file_options.values()) == 0:
            if not need_value:
                return None
            # Default to user, unless there's a virtualenv file.
            elif os.path.exists(venv_config_file):
                return kinds.VENV
            else:
                return kinds.USER
        elif sum(file_options.values()) == 1:
            # There's probably a better expression for this.
            return [key for key in file_options if file_options[key]][0]

        raise PipError("Need exactly one file to operate upon "
                       "(--user, --venv, --global) to perform.")