Beispiel #1
0
    def _perform_install(last_try=False):
        """
        Try to perform the install.

        If 'use_webservice' and the install fails, check the user's
        credentials (_check_auth), else _done.
        """
        try:
            mode = 'root' if opts.no_deps else 'recur'
            actions = enpkg.install_actions(
                    req,
                    mode=mode,
                    force=opts.force, forceall=opts.forceall)
            enpkg.execute(actions)
            if len(actions) == 0:
                print "No update necessary, %r is up-to-date." % req.name
                print_install_time(enpkg, req.name)
        except EnpkgError, e:
            if mode == 'root' or e.req is None or e.req == req:
                # trying to install just one requirement - try to give more info
                info_list = enpkg.info_list_name(req.name)
                if info_list:
                    print "Versions for package %r are:\n%s" % (req.name,
                        pretty_print_packages(info_list))
                    if any(not i.get('available', True) for i in info_list):
                        if config.get('use_webservice') and not(last_try):
                            _check_auth()
                        else:
                            _done(FAILURE)
                else:
                    print e.message
                    _done(FAILURE)
            elif mode == 'recur':
                print e.message
                print '\n'.join(textwrap.wrap(
                    "You may be able to force an install of just this "
                    "egg by using the --no-deps enpkg commandline argument "
                    "after installing another version of the dependency. "))
                if e.req:
                    info_list = enpkg.info_list_name(e.req.name)
                    if info_list:
                        print ("Available versions of the required package "
                               "%r are:\n%s") % (
                            e.req.name, pretty_print_packages(info_list))
                        if any(not i.get('available', True) for i in info_list):
                            if config.get('use_webservice') and not(last_try):
                                _check_auth()
                            else:
                                _done(FAILURE)
            _done(FAILURE)
def update_enstaller(enpkg, opts):
    """
    Check if Enstaller is up to date, and if not, ask the user if he
    wants to update.  Return boolean indicating whether enstaller was
    updated.
    """
    updated = False
    # exit early if autoupdate=False
    if not config.get('autoupdate', True):
        return updated
    if not IS_RELEASED:
        return updated
    try:
        # Ugly: we create a new enpkg class to merge a
        # fake local repo to take into account our locally
        # installed enstaller
        new_enpkg = _create_enstaller_update_enpkg(enpkg)
        if len(new_enpkg._install_actions_enstaller()) > 0:
            yn = raw_input("Enstaller is out of date.  Update? ([y]/n) ")
            if yn in set(['y', 'Y', '', None]):
                install_req(enpkg, 'enstaller', opts)
                updated = True
    except EnpkgError as e:
        print "Can't update enstaller:", e
    return updated
Beispiel #3
0
    def __init__(self, url):
        self.root = url

        # Use handlers from urllib2's default opener, since we already
        # added our proxy handler to it.
        opener = urllib2._opener
        http_handlers = [urllib2.HTTPHandler, urllib2.HTTPSHandler]
        handlers = opener.handlers if opener is not None else http_handlers

        # Add our handlers to the default handlers.
        handlers_ = [CompressedHandler, CachedHandler(config.get('local'))] + \
                    handlers

        self.opener = urllib2.build_opener(*handlers_)
Beispiel #4
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)
Beispiel #5
0
def get_status():
    # the result is a dict mapping cname to ...
    res = {}
    for cname in egginst.get_installed_cnames(sys.prefix):
        d = defaultdict(str)
        info = get_installed_info(sys.prefix, cname)
        if info is None:
            continue
        d.update(info)
        res[cname] = d

    c = Chain(config.get('IndexedRepos'))

    for cname in c.groups.iterkeys():
        dist = c.get_dist(Req(cname))
        if dist is None:
            continue
        repo, fn = dist_naming.split_dist(dist)
        n, v, b = dist_naming.split_eggname(fn)
        if cname not in res:
            d = defaultdict(str)
            d['name'] = n
            res[cname] = d
        res[cname]['a-egg'] = fn
        res[cname]['a-ver'] = '%s-%d' % (v, b)

    def vb_egg(fn):
        try:
            n, v, b = dist_naming.split_eggname(fn)
            return comparable_version(v), b
        except:
            return None

    for d in res.itervalues():
        if d['egg_name']:                    # installed
            if d['a-egg']:
                if vb_egg(d['egg_name']) >= vb_egg(d['a-egg']):
                    d['status'] = 'up-to-date'
                else:
                    d['status'] = 'updateable'
            else:
                d['status'] = 'installed'
        else:                                # not installed
            if d['a-egg']:
                d['status'] = 'installable'
    return res
Beispiel #6
0
def get_status():
    # the result is a dict mapping cname to ...
    res = {}
    for cname in egginst.get_installed_cnames(sys.prefix):
        d = defaultdict(str)
        info = get_installed_info(sys.prefix, cname)
        if info is None:
            continue
        d.update(info)
        res[cname] = d

    c = Chain(config.get('IndexedRepos'))

    for cname in c.groups.iterkeys():
        dist = c.get_dist(Req(cname))
        if dist is None:
            continue
        repo, fn = dist_naming.split_dist(dist)
        n, v, b = dist_naming.split_eggname(fn)
        if cname not in res:
            d = defaultdict(str)
            d['name'] = n
            res[cname] = d
        res[cname]['a-egg'] = fn
        res[cname]['a-ver'] = '%s-%d' % (v, b)

    def vb_egg(fn):
        try:
            n, v, b = dist_naming.split_eggname(fn)
            return comparable_version(v), b
        except:
            return None

    for d in res.itervalues():
        if d['egg_name']:  # installed
            if d['a-egg']:
                if vb_egg(d['egg_name']) >= vb_egg(d['a-egg']):
                    d['status'] = 'up-to-date'
                else:
                    d['status'] = 'updateable'
            else:
                d['status'] = 'installed'
        else:  # not installed
            if d['a-egg']:
                d['status'] = 'installable'
    return res
Beispiel #7
0
def update_enstaller(enpkg, opts):
    """
    Check if Enstaller is up to date, and if not, ask the user if he
    wants to update.  Return boolean indicating whether enstaller was
    updated.
    """
    updated = False
    # exit early if autoupdate=False
    if not config.get('autoupdate', True):
        return updated
    try:
        if len(enpkg.install_actions('enstaller')) > 0:
            yn = raw_input("Enstaller is out of date.  Update? ([y]/n) ")
            if yn in set(['y', 'Y', '', None]):
                install_req(enpkg, 'enstaller', opts)
                updated = True
    except EnpkgError as e:
        print "Can't update enstaller:", e
    return updated
Beispiel #8
0
def main():
    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("--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("--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()

    # 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)
    # 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.get('prefix', sys.prefix)

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

    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.sys_config:                           # --sys-config
        config.get_path = lambda: config.system_config_path

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

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

    if 0: # for testing event manager only
        from encore.events.api import EventManager
        from encore.terminal.api import ProgressDisplay
        evt_mgr = EventManager()
        display = ProgressDisplay(evt_mgr)
    else:
        evt_mgr = None

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

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


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

    if args.userpass:                             # --userpass
        username, password = config.input_auth()
        config.checked_change_auth(username, password, enpkg.remote)
        return

    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.add_url:                              # --add-url
        add_url(args.add_url, args.verbose)
        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.", \
            "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 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))

    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)
Beispiel #9
0
def add_url(url, verbose):
    url = fill_url(url)
    if url in config.get('IndexedRepos'):
        print "Already configured:", url
        return
    config.prepend_url(url)
 def __init__(self, url, cache_dir=None):
     super(RemoteHTTPIndexedStore, self).__init__()
     self.root = url
     if cache_dir is None:
         cache_dir = config.get('local')
     self.cache_dir = cache_dir
Beispiel #11
0
 def __init__(self, url, cache_dir=None):
     self.root = url
     if cache_dir is None:
         cache_dir = config.get('local')
     self.cache_dir = cache_dir
Beispiel #12
0
 def __init__(self, url):
     self.root = url
     self.opener = urllib2.build_opener(CompressedHandler,
                                        CachedHandler(config.get('local')),
                                        urllib2.HTTPHandler,
                                        urllib2.HTTPSHandler)