Exemplo n.º 1
0
    def test_use_webservice_valid_user(self):
        config = Configuration()
        config.set_auth(FAKE_USER, FAKE_PASSWORD)

        with mock.patch("enstaller.config.web_auth") as mocked_auth:
            authenticate(config)
            self.assertTrue(mocked_auth.called)
Exemplo n.º 2
0
    def test_use_webservice_invalid_user(self):
        config = Configuration()
        config.set_auth(FAKE_USER, FAKE_PASSWORD)

        with mock.patch("enstaller.config.web_auth") as mocked_auth:
            mocked_auth.return_value = {"is_authenticated": False}

            with self.assertRaises(AuthFailedError):
                authenticate(config)
Exemplo n.º 3
0
    def test_use_remote_invalid(self):
        config = Configuration()
        config.use_webservice = False
        config.set_auth(FAKE_USER, FAKE_PASSWORD)

        remote = mock.Mock()

        for klass in KeyError, Exception:
            attrs = {"connect.side_effect": klass()}
            remote.configure_mock(**attrs)

            with self.assertRaises(AuthFailedError):
                authenticate(config, remote)
Exemplo n.º 4
0
    def test_use_remote(self):
        config = Configuration()
        config.use_webservice = False
        config.set_auth(FAKE_USER, FAKE_PASSWORD)

        remote = mock.Mock()
        user = authenticate(config, remote)
        self.assertEqual(user, {"is_authenticated": True})
Exemplo n.º 5
0
 def _check_auth():
     """
     Check the user's credentials against the web API.
     """
     user = {}
     try:
         user = config.authenticate(config.get_auth())
         assert(user['is_authenticated'])
         # An EPD Free user who is trying to install a package not in
         # EPD free.  Print out subscription level and fail.
         print config.subscription_message(user)
         _done(FAILURE)
     except Exception as e:
         print e.message
         # No credentials.
         print ""
         _prompt_for_auth()
Exemplo n.º 6
0
def search(enpkg, pat=None):
    """
    Print the packages that are available in the (remote) KVS.
    """
    # Flag indicating if the user received any 'not subscribed to'
    # messages
    SUBSCRIBED = True

    print FMT4 % ('Name', '  Versions', 'Product', 'Note')
    print 80 * '='

    names = {}
    for key, info in enpkg.query_remote():
        names[info['name']] = name_egg(key)

    installed = {}
    for key, info in enpkg.query_installed():
        installed[info['name']] = VB_FMT % info

    for name in sorted(names, key=string.lower):
        if pat and not pat.search(name):
            continue
        disp_name = names[name]
        installed_version = installed.get(name)
        for info in enpkg.info_list_name(name):
            version = VB_FMT % info
            disp_ver = (('* ' if installed_version == version else '  ') +
                        version)
            available = info.get('available', True)
            product = info.get('product', '')
            if not(available):
                SUBSCRIBED = False
            print FMT4 % (disp_name, disp_ver, product,
                   '' if available else 'not subscribed to')
            disp_name = ''

    # if the user's search returns any packages that are not available
    # to them, attempt to authenticate and print out their subscriber
    # level
    if config.get('use_webservice') and not(SUBSCRIBED):
        user = {}
        try:
            user = config.authenticate(config.get_auth())
        except Exception as e:
            print e.message
        print config.subscription_message(user)
Exemplo n.º 7
0
def main(argv=None):
    if argv is None:
        argv = sys.argv[1:]

    try:
        user_base = site.USER_BASE
    except AttributeError:
        user_base = abs_expanduser('~/.local')

    p = ArgumentParser(description=__doc__)
    p.add_argument('cnames', metavar='NAME', nargs='*',
                   help='package(s) to work on')
    p.add_argument("--add-url", metavar='URL',
                   help="add a repository URL to the configuration file")
    p.add_argument("--config", action="store_true",
                   help="display the configuration and exit")
    p.add_argument('-f', "--force", action="store_true",
                   help="force install the main package "
                        "(not its dependencies, see --forceall)")
    p.add_argument("--forceall", action="store_true",
                   help="force install of all packages "
                        "(i.e. including dependencies)")
    p.add_argument("--freeze", help=argparse.SUPPRESS, action="store_true")
    p.add_argument("--hook", action="store_true",
                   help="don't install into site-packages (experimental)")
    p.add_argument("--imports", action="store_true",
                   help="show which packages can be imported")
    p.add_argument('-i', "--info", action="store_true",
                   help="show information about a package")
    p.add_argument("--log", action="store_true", help="print revision log")
    p.add_argument('-l', "--list", action="store_true",
                   help="list the packages currently installed on the system")
    p.add_argument('-n', "--dry-run", action="store_true",
               help="show what would have been downloaded/removed/installed")
    p.add_argument('-N', "--no-deps", action="store_true",
                   help="neither download nor install dependencies")
    p.add_argument("--env", action="store_true",
                   help="based on the configuration, display how to set "
                        "environment variables")
    p.add_argument("--prefix", metavar='PATH',
                   help="install prefix (disregarding any settings in "
                        "the config file)")
    p.add_argument("--proxy", metavar='PROXYSTR',
                   help="use a proxy for downloads."
                        " <proxy protocol>://[<proxy username>"
                        "[:<proxy password>@]]<proxy server>:<proxy port>")
    p.add_argument("--remove", action="store_true", help="remove a package")
    p.add_argument("--remove-enstaller", action="store_true",
                   help="remove enstaller (will break enpkg)")
    p.add_argument("--requirements", help=argparse.SUPPRESS)
    p.add_argument("--revert", metavar="REV#",
                   help="revert to a previous set of packages (does not revert "
                   "enstaller itself)")
    p.add_argument('-s', "--search", action="store_true",
                   help="search the online repo index "
                        "and display versions available")
    p.add_argument("--sys-config", action="store_true",
                   help="use <sys.prefix>/.enstaller4rc (even when "
                        "~/.enstaller4rc exists)")
    p.add_argument("--sys-prefix", action="store_true",
                   help="use sys.prefix as the install prefix")
    p.add_argument("--update-all", action="store_true",
                   help="update all installed packages")
    p.add_argument("--user", action="store_true",
               help="install into user prefix, i.e. --prefix=%r" % user_base)
    p.add_argument("--userpass", action="store_true",
                   help="prompt for Enthought authentication, and save in "
                   "configuration file .enstaller4rc")
    p.add_argument('-v', "--verbose", action="store_true")
    p.add_argument('--version', action="version",
                   version='enstaller version: ' + __version__)
    p.add_argument("--whats-new", action="store_true",
                   help="display available updates for installed packages")

    args = p.parse_args(argv)

    config_filename = get_config_filename(args.sys_config)
    if not os.path.isfile(config_filename):
        write_default_config(config_filename)

    config = Configuration.from_file(config_filename)

    # Check for incompatible actions and options
    # Action options which take no package name pattern:
    simple_standalone_actions = (args.config, args.env, args.userpass,
                                args.revert, args.log, args.whats_new,
                                args.update_all, args.remove_enstaller,
                                args.add_url, args.freeze, args.requirements)
    # Action options which can take a package name pattern:
    complex_standalone_actions = (args.list, args.imports,
                                 args.search, args.info, args.remove)

    count_simple_actions = sum(bool(opt) for opt in simple_standalone_actions)
    count_complex_actions = sum(bool(opt) for opt in complex_standalone_actions)

    if count_simple_actions + count_complex_actions > 1:
        p.error('Multiple action options specified')
    if count_simple_actions > 0 and len(args.cnames) > 0:
        p.error("Option takes no arguments")

    if args.user:
        args.prefix = user_base

    if args.prefix and args.sys_prefix:
        p.error("Options --prefix and --sys-prefix exclude each other")

    if args.force and args.forceall:
        p.error("Options --force and --forceall exclude each other")

    pat = None
    if (args.list or args.search) and args.cnames:
        pat = re.compile(args.cnames[0], re.I)

    # make prefix
    if args.sys_prefix:
        prefix = sys.prefix
    elif args.prefix:
        prefix = args.prefix
    else:
        prefix = config.prefix

    # now make prefixes
    if prefix == sys.prefix:
        prefixes = [sys.prefix]
    else:
        prefixes = [prefix, sys.prefix]

    if args.user:
        try:
            check_prefixes(prefixes)
        except InvalidPythonPathConfiguration:
            warnings.warn("Using the --user option, but your PYTHONPATH is not setup " \
                          "accordingly")

    exit_if_sudo_on_venv(prefix)

    if args.verbose:
        print("Prefixes:")
        for prefix in prefixes:
            print('    %s%s' % (prefix, ['', ' (sys)'][prefix == sys.prefix]))
        print()

    if args.env:                                  # --env
        env_option(prefixes)
        return

    if args.log:                                  # --log
        if args.hook:
            raise NotImplementedError
        from history import History
        h = History(prefix)
        h.update()
        h.print_log()
        return

    if args.freeze:
        from .eggcollect import EggCollection, JoinedEggCollection
        collection = JoinedEggCollection(
            [EggCollection(prefix, False, None) for prefix in prefixes]
        )
        full_names = [
            "{0} {1}-{2}".format(req["name"], req["version"], req["build"])
            for name, req in collection.query(type="egg")
        ]
        for full_name in sorted(full_names):
            print(full_name)
        return

    if args.list:                                 # --list
        list_option(prefixes, args.hook, pat)
        return

    if args.proxy:                                # --proxy
        setup_proxy(args.proxy)
    elif config.proxy:
        setup_proxy(config.proxy)
    else:
        setup_proxy()

    evt_mgr = None

    if config.use_webservice:
        remote = None # Enpkg will create the default
    else:
        urls = [fill_url(u) for u in config.IndexedRepos]
        remote = create_joined_store(config, urls)

    enpkg = Enpkg(remote, prefixes=prefixes, hook=args.hook,
                  evt_mgr=evt_mgr, verbose=args.verbose, config=config)


    if args.config:                               # --config
        print_config(config, enpkg.remote, prefixes[0])
        return

    if args.add_url:                              # --add-url
        add_url(config_filename, enpkg.config, args.add_url, args.verbose)
        return

    if args.userpass:                             # --userpass
        n_trials = 3
        for i in range(n_trials):
            username, password = input_auth()
            if username:
                break
            else:
                print("Please enter a non empty username ({0} trial(s) left)". \
                      format(n_trials - i - 1))
        else:
            print("No valid username entered (no modification was written).")
            sys.exit(-1)

        config.set_auth(username, password)
        try:
            config._checked_change_auth(config_filename)
        except AuthFailedError as e:
            msg = ("Could not authenticate. Please check your credentials "
                   "and try again.\nNo modification was written.")
            print(msg)
            sys.exit(-1)
        return

    if not config.is_auth_configured:
        print(PLEASE_AUTH_MESSAGE)
        sys.exit(-1)

    try:
        config.get_auth()
    except InvalidConfiguration:
        print(PLEASE_AUTH_MESSAGE)
        sys.exit(-1)
    else:
        try:
            authenticate(config, enpkg.remote)
        except AuthFailedError as e:
            login, _ = config.get_auth()
            print("Could not authenticate with user '{0}'.".format(login))
            print("You can change your authentication details with 'enpkg --userpass'")
            sys.exit(-1)

    if args.dry_run:
        def print_actions(actions):
            for item in actions:
                print('%-8s %s' % item)
        enpkg.execute = print_actions

    if args.imports:                              # --imports
        assert not args.hook
        imports_option(enpkg, pat)
        return

    if args.revert:                               # --revert
        if isfile(args.revert):
            arg = parse_list(args.revert)
        else:
            arg = args.revert
        try:
            actions = enpkg.revert_actions(arg)
            if not actions:
                print("Nothing to do")
                return
            enpkg.execute(actions)
        except EnpkgError as e:
            print(e.message)
        return

    # Try to auto-update enstaller
    if update_enstaller(enpkg, args):
        print("Enstaller has been updated.\n"
              "Please re-run your previous command.")
        return

    if args.search:                               # --search
        search(enpkg, pat)
        return

    if args.info:                                 # --info
        if len(args.cnames) != 1:
            p.error("Option requires one argument (name of package)")
        info_option(enpkg, args.cnames[0])
        return

    if args.whats_new:                            # --whats-new
        whats_new(enpkg)
        return

    if args.update_all:                           # --update-all
        update_all(enpkg, args)
        return

    if args.requirements:
        with open(args.requirements, "r") as fp:
            for req in fp:
                args.no_deps = True
                install_req(enpkg, req, args)
        return

    if len(args.cnames) == 0 and not args.remove_enstaller:
        p.error("Requirement(s) missing")
    elif len(args.cnames) == 2:
        pat = re.compile(r'\d+\.\d+')
        if pat.match(args.cnames[1]):
            args.cnames = ['-'.join(args.cnames)]

    reqs = []
    for arg in args.cnames:
        if '-' in arg:
            name, version = arg.split('-', 1)
            reqs.append(Req(name + ' ' + version))
        else:
            reqs.append(Req(arg))

    # This code assumes we have already upgraded enstaller if needed
    if needs_to_downgrade_enstaller(enpkg, reqs):
        warnings.warn("Enstaller in requirement list: enstaller will be downgraded !")
    else:
        print("Enstaller is already up to date, not upgrading.")
        reqs = [req for req in reqs if req.name != "enstaller"]

    if args.verbose:
        print("Requirements:")
        for req in reqs:
            print('    %r' % req)
        print()

    print("prefix:", prefix)

    REMOVE_ENSTALLER_WARNING = ("Removing enstaller package will break enpkg "
                                "and is not recommended.")
    if args.remove:
        if any(req.name == 'enstaller' for req in reqs):
            print(REMOVE_ENSTALLER_WARNING)
            print("If you are sure you wish to remove enstaller, use:")
            print("    enpkg --remove-enstaller")
            return

    if args.remove_enstaller:
        print(REMOVE_ENSTALLER_WARNING)
        yn = raw_input("Really remove enstaller? (y/[n]) ")
        if yn.lower() in set(['y', 'yes']):
            args.remove = True
            reqs = [Req('enstaller')]

    if any(req.name == 'epd' for req in reqs):
        if args.remove:
            p.error("Can't remove 'epd'")
        elif len(reqs) > 1:
            p.error("Can't combine 'enpkg epd' with other packages.")
            return
        elif not epd_install_confirm():
            return

    for req in reqs:
        if args.remove:                               # --remove
            try:
                enpkg.execute(enpkg.remove_actions(req))
            except EnpkgError as e:
                print(e.message)
        else:
            install_req(enpkg, req, args)             # install (default)
Exemplo n.º 8
0
 def _print_invalid_permissions():
     user = authenticate(enpkg.config)
     print("No package found to fulfill your requirement at your "
           "subscription level:")
     for line in subscription_message(enpkg.config, user).splitlines():
         print(" " * 4 + line)