Exemple #1
0
def interactive_get_token():
    bs = get_binstar()
    config = get_config()

    url = config.get('url', 'https://api.binstar.org')

    token = None
    username = input('Username: '******'s " % username)
            password = getpass.getpass(stream=sys.stderr)
            token = bs.authenticate(username,
                                    password,
                                    'binstar_client:%s' %
                                    (socket.gethostname()),
                                    url,
                                    created_with=' '.join(sys.argv))
            break
        except Unauthorized:
            log.error(
                'Invalid Username password combination, please try again')
            continue

    if token is None:
        raise BinstarError(
            'Sorry. Please try again (go to https://binstar.org/account/forgot_password to reset your password)'
        )

    return token
Exemple #2
0
def add_parser(subparsers):

    config = get_config()

    parser = subparsers.add_parser(
        'register',
        formatter_class=argparse.RawDescriptionHelpFormatter,
        help='Register a package on binstar',
        description=__doc__)

    parser.add_argument(
        'filename',
        help='Inspect this file, to get the package name and summary',
        default=None)

    parser.add_argument('-u',
                        '--user',
                        help='User account, defaults to the current user')
    parser.add_argument(
        '-p',
        '--package',
        help='Defaults to the packge name in the uploaded file')
    parser.add_argument('-s', '--summary', help='Summary of the package')

    perms = parser.add_mutually_exclusive_group()

    package_access = config.get('package_access', 'personal')
    perms.desciption = 'The package permissions'

    perms.add_argument(
        '--private',
        action='store_const',
        dest='access',
        const='private',
        default=package_access == 'private',
        help=
        'Set the permissions of the package to private (if it does not exist)')

    perms.add_argument(
        '--publish',
        action='store_const',
        dest='access',
        const='publish',
        default=package_access == 'publish',
        help=
        ('Set the permissions of the package to public and '
         'publish this package to the global public repositories - if it does not exist. '
         '(default %(default)s)'))
    perms.add_argument(
        '--personal',
        action='store_const',
        dest='access',
        const='personal',
        default=package_access == 'personal',
        help=
        ('Set the permissions of the package to public. '
         'Do not publish this to the global public repo. This package will be kept in you user repository.'
         ))

    parser.set_defaults(main=main)
Exemple #3
0
def interactive_get_token(args):
    bs = get_binstar(args)
    config = get_config(remote_site=args.site)

    url = config.get('url', 'https://api.binstar.org')

    token = None
    hostname = getattr(args, 'hostname', platform.node())
    username = input('Username: '******'binstar_client:'
    site = args.site or config.get('default_site')
    if site and site != 'binstar':
        # For testing with binstar alpha site
        auth_name += '%s:' % site

    auth_name += '%s@%s' % (getpass.getuser(), hostname)

    password = None
    for _ in range(3):
        try:
            sys.stderr.write("%s's " % username)

            if password is None:
                password = getpass.getpass(stream=sys.stderr)

            token = bs.authenticate(username, password, auth_name, url,
                                    created_with=' '.join(sys.argv),
                                    fail_if_already_exists=True,
                                    hostname=hostname)
            break

        except errors.Unauthorized:
            log.error('Invalid Username password combination, please try again')
            password = None
            continue

        except errors.BinstarError as err:
            if err.args[1] == 400:
                log.error('It appears you are already logged in from host %s' % socket.gethostname())
                log.error('Logging in again will remove the previous token.')
                log.error('Otherwise you can login again and specify a '
                          'different hostname with "--hostname"')
                if bool_input("Would you like to continue"):
                    bs.remove_authentication(auth_name)
                    continue
                else:
                    raise


    if token is None:
        msg = ('Sorry. Please try again '
               '(go to https://binstar.org/account/forgot_password '
               'to reset your password)')
        raise errors.BinstarError(msg)

    return token
Exemple #4
0
def main(args):
    
    config = get_config()
    kr = get_keyring()
    token = kr.get_password('binstar-token', getpass.getuser())
    url = config.get('url', 'https://api.binstar.org')
    bs = Binstar(token, domain=url)
    bs.remove_authentication(token)
    kr.delete_password('binstar-token', getpass.getuser())
Exemple #5
0
def main(args):
    config = get_config()

    if args.show:
        fmt = ' + %s: %r'
        log.info('Site Config: %s' % SITE_CONFIG)
        for key_value in get_config(user=False).items():
            log.info(fmt % key_value)
        log.info("")
        log.info('User Config: %s' % USER_CONFIG)
        for key_value in get_config(site=False).items():
            log.info(fmt % key_value)
        log.info("")
        return

    if args.get:
        if args.get in config:
            log.info(config[args.get])
        else:
            log.info("The value of '%s' is not set." % args.get)
        return

    if args.files:
        log.info('User Config: %s' % USER_CONFIG)
        log.info('Site Config: %s' % SITE_CONFIG)
        return

    config = get_config(args.user, not args.user)

    for key, value in args.set:
        recursive_set(config, key, value, args.type)
        config[key] = args.type(value)

    for key in args.remove:
        try:
            recursive_remove(config, key)
        except KeyError:
            log.error("Key %s does not exist" % key)

    if not (args.set or args.remove):
        raise ShowHelp()

    set_config(config, args.user)
def main(args):
    config = get_config()

    if args.show:
        fmt = " + %s: %r"
        log.info("Site Config: %s" % SITE_CONFIG)
        for key_value in get_config(user=False).items():
            log.info(fmt % key_value)
        log.info("")
        log.info("User Config: %s" % USER_CONFIG)
        for key_value in get_config(site=False).items():
            log.info(fmt % key_value)
        log.info("")
        return

    if args.get:
        if args.get in config:
            log.info(config[args.get])
        else:
            log.info("The value of '%s' is not set." % args.get)
        return

    if args.files:
        log.info("User Config: %s" % USER_CONFIG)
        log.info("Site Config: %s" % SITE_CONFIG)
        return

    config = get_config(args.user, not args.user)

    for key, value in args.set:
        recursive_set(config, key, value, args.type)
        config[key] = args.type(value)

    for key in args.remove:
        try:
            recursive_remove(config, key)
        except KeyError:
            log.error("Key %s does not exist" % key)

    if not (args.set or args.remove):
        raise ShowHelp()

    set_config(config, args.user)
Exemple #7
0
def main(args):
    config = get_config()
    
    if args.show:
        print 'Site Config:', SITE_CONFIG
        print get_config(user=False)
        print 'User Config:', USER_CONFIG
        print get_config(site=False)
    
    if args.get:
        print config[args.get]
        return
    
    if args.files:
        print 'User Config:', USER_CONFIG 
        print 'Site Config:', SITE_CONFIG
    
    config = get_config(args.user, not args.user)
    
    for key, value in args.set:
        config[key] = args.type(value)
    
    for key in args.remove:
        if key in config:
            del config[key]
    
    set_config(config, args.user)
def main(args):
    config = get_config()

    binstar = get_binstar()

    spec = args.spec[0]
    org = spec.org
    name = spec.name

    if args.show:
        if name:
            show_collection(binstar, spec)
        else:
            show_collections(binstar, spec)
        return

    if not name:
        raise BinstarError('invaid collection spec')

    if args.create:
        public = True if args.public is None else args.public

        binstar.add_collection(org, name,
                               public=public, description=args.description)

    if args.update:
        binstar.update_collection(org, name,
                               public=args.public, description=args.description)

    if args.remove:
        binstar.remove_collection(org, name)

    if args.add_package:
        package = args.add_package

        binstar.collection_add_packages(org, name,
                                        owner=package.org, package=package.name)

    if args.remove_package:
        package = args.remove_package

        binstar.collection_remove_packages(org, name,
                                        owner=package.org, package=package.name)

    if args.clone_from:
        binstar.collection_clone(args.clone_from.org, args.clone_from.name,
                                 org, name)
    if args.pull_from:
        binstar.collection_pull(args.pull_from.org, args.pull_from.name,
                                 org, name)
Exemple #9
0
def main(args):
    
    config = get_config()
    kr = get_keyring()
    token = kr.get_password('binstar-token', getpass.getuser())
    url = config.get('url', 'https://api.binstar.org')
    bs = Binstar(token, domain=url,)
    
    username = raw_input('Username: '******'Binstar-Cli', url, ['packages'])
    kr.set_password('binstar-token', getpass.getuser(), token)
    print 'login successful'
def main(args):
    config = get_config()

    if args.show:
        fmt = " + %s: %r"
        log.info("Site Config: %s" % SITE_CONFIG)
        for key_value in get_config(user=False).items():
            log.info(fmt % key_value)
        log.info("")
        log.info("User Config: %s" % USER_CONFIG)
        for key_value in get_config(site=False).items():
            log.info(fmt % key_value)
        log.info("")
        return

    if args.get:
        log.info(config[args.get])
        return

    if args.files:
        log.info("User Config: %s" % USER_CONFIG)
        log.info("Site Config: %s" % SITE_CONFIG)
        return

    config = get_config(args.user, not args.user)

    for key, value in args.set:
        config[key] = args.type(value)

    for key in args.remove:
        if key in config:
            del config[key]

    if not (args.set or args.remove):
        raise ShowHelp()

    set_config(config, args.user)
Exemple #11
0
def main(args):
    config = get_config()

    if args.show:
        fmt = ' + %s: %r'
        log.info('Site Config: %s' % SITE_CONFIG)
        for key_value in get_config(user=False).items():
            log.info(fmt % key_value)
        log.info("")
        log.info('User Config: %s' % USER_CONFIG)
        for key_value in get_config(site=False).items():
            log.info(fmt % key_value)
        log.info("")
        return

    if args.get:
        log.info(config[args.get])
        return

    if args.files:
        log.info('User Config: %s' % USER_CONFIG)
        log.info('Site Config: %s' % SITE_CONFIG)
        return

    config = get_config(args.user, not args.user)

    for key, value in args.set:
        config[key] = args.type(value)

    for key in args.remove:
        if key in config:
            del config[key]

    if not (args.set or args.remove):
        raise ShowHelp()

    set_config(config, args.user)
Exemple #12
0
def main(args):
    config = get_config()
    
    if args.show:
        fmt = ' + %s: %r'
        print 'Site Config:', SITE_CONFIG
        for key_value in get_config(user=False).items():
            print fmt % key_value
        print
        print 'User Config:', USER_CONFIG
        for key_value in get_config(site=False).items():
            print fmt % key_value
        print
        return
    
    if args.get:
        print config[args.get]
        return
    
    if args.files:
        print 'User Config:', USER_CONFIG 
        print 'Site Config:', SITE_CONFIG
    
    config = get_config(args.user, not args.user)
    
    for key, value in args.set:
        config[key] = args.type(value)
    
    for key in args.remove:
        if key in config:
            del config[key]
            
    if not (args.set or args.remove):
        raise ShowHelp()
    
    set_config(config, args.user)
def add_parser(subparsers):

    description = 'Upload packages to Anaconda Cloud'
    parser = subparsers.add_parser('upload',
                                   formatter_class=argparse.RawDescriptionHelpFormatter,
                                   help=description, description=description,
                                   epilog=__doc__)

    parser.add_argument('files', nargs='+', help='Distributions to upload', default=[], type=windows_glob)

    label_help = (
        '{deprecation}Add this file to a specific {label}. '
        'Warning: if the file {label}s do not include "main",'
        'the file will not show up in your user {label}')

    parser.add_argument('-c', '--channel', action='append', default=[], dest='labels',
                        help=label_help.format(deprecation='[DEPRECATED]\n', label='channel'),
                        metavar='CHANNELS')
    parser.add_argument('-l', '--label', action='append', dest='labels',
                        help=label_help.format(deprecation='', label='label'))
    parser.add_argument('--no-progress', help="Don't show upload progress", action='store_true')
    parser.add_argument('-u', '--user', help='User account, defaults to the current user')

    mgroup = parser.add_argument_group('metadata options')
    mgroup.add_argument('-p', '--package', help='Defaults to the package name in the uploaded file')
    mgroup.add_argument('-v', '--version', help='Defaults to the package version in the uploaded file')
    mgroup.add_argument('-s', '--summary', help='Set the summary of the package')
    mgroup.add_argument('-t', '--package-type', help='Set the package type, defaults to autodetect')
    mgroup.add_argument('-d', '--description', help='description of the file(s)')
    mgroup.add_argument('--thumbnail', help='Notebook\'s thumbnail image')

    register_group = parser.add_mutually_exclusive_group()
    register_group.add_argument("--no-register", dest="auto_register", action="store_false",
                        help='Don\'t create a new package namespace if it does not exist')
    register_group.add_argument("--register", dest="auto_register", action="store_true",
                        help='Create a new package namespace if it does not exist')
    parser.set_defaults(auto_register=bool(get_config().get('auto_register', True)))
    parser.add_argument('--build-id', help='Anaconda Cloud Build ID (internal only)')

    group = parser.add_mutually_exclusive_group()
    group.add_argument('-i', '--interactive', action='store_const', help='Run an interactive prompt if any packages are missing',
                        dest='mode', const='interactive')
    group.add_argument('-f', '--fail', help='Fail if a package or release does not exist (default)',
                                        action='store_const', dest='mode', const='fail')
    group.add_argument('--force', help='Force a package upload regardless of errors',
                                        action='store_const', dest='mode', const='force')

    parser.set_defaults(main=main)
Exemple #14
0
    def get_binstar_token(url):
        try:
            try:
                from binstar_client.utils import get_config, load_token
            except ImportError:
                log.debug("Could not import binstar_client.")
                return None

            binstar_default_url = 'https://api.anaconda.org'
            url_parts = urlparse(url)
            base_url = '%s://%s' % (url_parts.scheme, url_parts.netloc)
            if DEFAULT_CHANNEL_ALIAS.startswith(base_url):
                base_url = binstar_default_url

            with disable_logger('binstar'):
                config = get_config(remote_site=base_url)
                url_from_bs_config = config.get('url', base_url)
                token = load_token(url_from_bs_config)
                return token
        except Exception as e:
            log.warn("Warning: could not capture token from anaconda-client (%r)", e)
            return None
Exemple #15
0
def interactive_get_token():
    bs = get_binstar()
    config = get_config()

    url = config.get('url', 'https://api.binstar.org')

    token = None
    for _ in range(3):
        try:
            username = raw_input('Username: '******'Binstar-Cli', url,
                                    created_with=' '.join(sys.argv))
            break
        except Unauthorized:
            log.error('Invalid Username password combination, please try again')
            continue

    if token is None:
        raise BinstarError('Sorry. Please try again (go to https://binstar.org/account/forgot_password to reset your password)')

    return token
def add_parser(subparsers):

    config = get_config()

    parser = subparsers.add_parser('register',
                                      formatter_class=argparse.RawDescriptionHelpFormatter,
                                      help='Register a package on binstar',
                                      description=__doc__)

    parser.add_argument('filename', help='Inspect this file, to get the package name and summary', default=None)

    parser.add_argument('-u', '--user', help='User account, defaults to the current user')
    parser.add_argument('-p', '--package', help='Defaults to the packge name in the uploaded file')
    parser.add_argument('-s', '--summary', help='Summary of the package')

    perms = parser.add_mutually_exclusive_group()
    
    package_access = config.get('package_access', 'personal')
    perms.desciption = 'The package permissions'
    
    perms.add_argument('--private', action='store_const',
                       dest='access', const='private',
                       default=package_access == 'private',
                       help='Set the permissions of the package to private (if it does not exist)')
    
    perms.add_argument('--publish', action='store_const',
                       dest='access', const='publish',
                       default=package_access == 'publish',
                       help=('Set the permissions of the package to public and '
                             'publish this package to the global public repositories - if it does not exist. '
                            '(default %(default)s)'))
    perms.add_argument('--personal', action='store_const',
                       dest='access', const='personal',
                       default=package_access == 'personal',
                       help=('Set the permissions of the package to public. '
                             'Do not publish this to the global public repo. This package will be kept in you user repository.'))

    parser.set_defaults(main=main)
Exemple #17
0
    def get_binstar_token(url):
        try:
            log.debug("Attempting to binstar collect token for url %s", url)
            try:
                from binstar_client.utils import get_config, load_token
            except ImportError:
                log.debug("Could not import binstar_client.")
                return None

            binstar_default_url = 'https://api.anaconda.org'
            url_parts = urlparse(url)
            base_url = '%s://%s' % (url_parts.scheme, url_parts.netloc)
            if DEFAULT_CHANNEL_ALIAS.startswith(base_url):
                base_url = binstar_default_url

            config = get_config()  # remote_site is site name, not url
            url_from_bs_config = config.get('url', base_url)
            token = load_token(url_from_bs_config)

            return token
        except Exception as e:
            log.warn("Warning: could not capture token from anaconda-client (%r)", e)
            return None
Exemple #18
0
def add_parser(subparsers):

    config = get_config()

    parser = subparsers.add_parser('upload',
                                      help='Upload a file to binstar',
                                      description=__doc__)

    parser.add_argument('files', nargs='*', help='Distributions to upload', default=[])

    parser.add_argument('-u', '--user', help='User account, defaults to the current user')
    parser.add_argument('-p', '--package', help='Defaults to the packge name in the uploaded file')
    parser.add_argument('-v', '--version', help='Defaults to the packge version in the uploaded file')
    parser.add_argument('-t', '--package-type', help='Set the package type, defaults to autodetect')
    parser.add_argument('-d', '--description', help='description of the file(s)')
    parser.add_argument('-m', '--metadata', help='json encoded metadata default is to autodetect')

    perms = parser.add_mutually_exclusive_group()
    perms.desciption = 'The package permissions'
    perms.add_argument('--public', action='store_true', default=config.get('public') or config.get('publish', True),
                       help='Set the permissions of the package to public (if it does not exist) (default %(default)s)')
    perms.add_argument('--private', action='store_false', dest='public',
                       help='Set the permissions of the package to private (if it does not exist)')
    perms.add_argument('--publish', action='store_true', default=config.get('publish', True),
                       help=('Set the permissions of the package to public and '
                             'publish this package to the global public repositories - if it does not exist. '
                            '(default %(default)s)'))
    perms.add_argument('--personal', action='store_false', dest='publish',
                       help=('Set the permissions of the package to public. '
                             'Do not publish this to the global public repo. This package will be kept in you user repository.'))
    group = parser.add_mutually_exclusive_group()
    group.add_argument('-i', '--interactive', action='store_const', help='Run an interactive prompt if any packages are missing',
                        dest='mode', const='interactive')
    group.add_argument('-f', '--fail', help='Fail if a package or release does not exist (default)',
                                        action='store_const', dest='mode', const='fail')

    parser.set_defaults(main=main)
Exemple #19
0
def add_parser(subparsers):

    config = get_config()

    parser = subparsers.add_parser('upload',
                                      help='Upload a file to binstar',
                                      description=__doc__)

    parser.add_argument('files', nargs='*', help='Distributions to upload', default=[])

    parser.add_argument('-u', '--user', help='User account, defaults to the current user')
    parser.add_argument('-p', '--package', help='Defaults to the packge name in the uploaded file')
    parser.add_argument('-v', '--version', help='Defaults to the packge version in the uploaded file')
    parser.add_argument('-t', '--package-type', help='Set the package type, defaults to autodetect')
    parser.add_argument('-d', '--description', help='description of the file(s)')
    parser.add_argument('-m', '--metadata', help='json encoded metadata default is to autodetect')

    perms = parser.add_mutually_exclusive_group()
    perms.desciption = 'The package permissions'
    perms.add_argument('--public', action='store_true', default=config.get('public') or config.get('publish', True),
                       help='Set the permissions of the package to public (if it does not exist) (default %(default)s)')
    perms.add_argument('--private', action='store_false', dest='public',
                       help='Set the permissions of the package to private (if it does not exist)')
    perms.add_argument('--publish', action='store_true', default=config.get('publish', True),
                       help=('Set the permissions of the package to public and '
                             'publish this package to the global public repositories - if it does not exist. '
                            '(default %(default)s)'))
    perms.add_argument('--personal', action='store_false', dest='publish',
                       help=('Set the permissions of the package to public. '
                             'Do not publish this to the global public repo. This package will be kept in you user repository.'))
    group = parser.add_mutually_exclusive_group()
    group.add_argument('-i', '--interactive', action='store_const', help='Run an interactive prompt if any packages are missing',
                        dest='mode', const='interactive')
    group.add_argument('-f', '--fail', help='Fail if a package or release does not exist (default)',
                                        action='store_const', dest='mode', const='fail')

    parser.set_defaults(main=main)
Exemple #20
0
    def get_binstar_token(url):
        try:
            log.debug("Attempting to binstar collect token for url %s", url)
            try:
                from binstar_client.utils import get_config, load_token
            except ImportError:
                log.debug("Could not import binstar_client.")
                return None

            binstar_default_url = 'https://api.anaconda.org'
            url_parts = urlparse(url)
            base_url = '%s://%s' % (url_parts.scheme, url_parts.netloc)
            if DEFAULT_CHANNEL_ALIAS.startswith(base_url):
                base_url = binstar_default_url
            with captured() as c:
                config = get_config(remote_site=base_url)
                url_from_bs_config = config.get('url', base_url)
                token = load_token(url_from_bs_config)
            log.debug("binstar stdout >> %s\n"
                      "binstar stderr >> %s", c.stdout, c.stderr)
            return token
        except Exception as e:
            log.warn("Warning: could not capture token from anaconda-client (%r)", e)
            return None
 def get_api_url():
     """Get the anaconda client url configuration."""
     return get_config().get('url', 'https://api.anaconda.org')
Exemple #22
0
def interactive_get_token(args, fail_if_already_exists=True):
    bs = get_server_api(args.token, args.site, args.log_level)
    config = get_config(remote_site=args.site)

    url = config.get('url', 'https://api.anaconda.org')
    parsed_url = urlparse(url)
    token = None
    hostname = getattr(args, 'hostname', platform.node())
    if getattr(args, 'login_username', None):
        username = args.login_username
    else:
        username = input('Username: '******'binstar_client:'
    site = args.site or config.get('default_site')
    if site and site != 'binstar':
        # For testing with binstar alpha site
        auth_name += '%s:' % site

    auth_name += '%s@%s' % (getpass.getuser(), hostname)

    password = getattr(args, 'login_password', None)

    for _ in range(3):
        try:
            sys.stderr.write("%s's " % username)

            if password is None:
                password = getpass.getpass(stream=sys.stderr)

            token = bs.authenticate(
                username,
                password,
                auth_name,
                url,
                created_with=' '.join(sys.argv),
                fail_if_already_exists=fail_if_already_exists,
                hostname=hostname)
            break

        except errors.Unauthorized:
            log.error(
                'Invalid Username password combination, please try again')
            password = None
            continue

        except errors.BinstarError as err:
            if fail_if_already_exists is True and err.args[1] == 400:
                log.warn('It appears you are already logged in from host %s' %
                         socket.gethostname())
                log.warn(
                    'Logging in again will remove the previous token. '
                    ' (This could cause troubles with virtual machines with the same hostname)'
                )
                log.warn('Otherwise you can login again and specify a '
                         'different hostname with "--hostname"')
                if bool_input("Would you like to continue"):
                    fail_if_already_exists = False
                    continue
                else:
                    raise

    if token is None:
        if parsed_url.netloc.startswith('api.anaconda.org'):
            netloc = 'anaconda.org'
        else:
            netloc = parsed_url.netloc
        hostparts = (parsed_url.scheme, netloc)
        msg = ('Sorry. Please try again ' + \
               '(go to %s://%s/account/forgot_password ' % hostparts + \
               'to reset your password)')
        raise errors.BinstarError(msg)

    return token
def main(args):
    config = get_config(site=args.site)

    aserver_api = get_server_api(token=args.token, site=args.site, config=config)
    aserver_api.check_server()

    validate_username = True

    if args.user:
        username = args.user
    elif 'upload_user' in config:
        username = config['upload_user']
    else:
        validate_username = False
        user = aserver_api.user()
        username = user['login']

    logger.info('Using "%s" as upload username', username)

    if validate_username:
        try:
            aserver_api.user(username)
        except errors.NotFound:
            message = 'User "{}" does not exist'.format(username)
            logger.error(message)
            raise errors.BinstarError(message)

    uploaded_packages = []
    uploaded_projects = []

    # Flatten file list because of 'windows_glob' function
    files = [f for fglob in args.files for f in fglob]

    if args.all:
        files += get_convert_files(files)

    for filename in files:
        if not exists(filename):
            message = 'File "{}" does not exist'.format(filename)
            logger.error(message)
            raise errors.BinstarError(message)
        else:
            logger.info("Processing '%s'", filename)

        package_type = determine_package_type(filename, args)

        if package_type == 'project':
            uploaded_projects.append(upload_project(filename, args, username))
        else:
            if package_type == 'ipynb' and not args.mode == 'force':
                try:
                    nbformat.read(open(filename), nbformat.NO_CONVERT)
                except Exception as error:
                    logger.error("Invalid notebook file '%s': %s", filename, error)
                    logger.info("Use --force to upload the file anyways")
                    continue

            package_info = upload_package(
                filename,
                package_type=package_type,
                aserver_api=aserver_api,
                username=username,
                args=args)

            if package_info is not None and len(package_info) == 2:
                _package, _upload_info = package_info
                if _upload_info:
                    uploaded_packages.append(package_info)

    for package, upload_info in uploaded_packages:
        package_url = upload_info.get('url', 'https://anaconda.org/%s/%s' % (username, package))
        logger.info("{} located at:\n{}\n".format(verbose_package_type(package_type), package_url))

    for project_name, url in uploaded_projects:
        logger.info("Project {} uploaded to {}.\n".format(project_name, url))
 def set_api_url(url):
     """Set the anaconda client url configuration."""
     data = get_config()
     data['url'] = url
     set_config(data)
Exemple #25
0
def interactive_get_token(args, fail_if_already_exists=True):
    bs = get_server_api(args.token, args.site, args.log_level)
    config = get_config(remote_site=args.site)

    token = None
    # This function could be called from a totally different CLI, so we don't
    # know if the attribute hostname exists.
    hostname = getattr(args, 'hostname', platform.node())
    site = args.site or config.get('default_site')
    url = config.get('url', 'https://api.anaconda.org')

    auth_name = 'binstar_client:'
    if site and site != 'binstar':
        # For testing with binstar alpha site
        auth_name += '%s:' % site

    auth_name += '%s@%s' % (getpass.getuser(), hostname)

    bs.check_server()
    auth_type = bs.authentication_type()

    if auth_type == 'kerberos':
        token = try_replace_token(
            bs.krb_authenticate,
            application=auth_name,
            application_url=url,
            created_with=' '.join(sys.argv),
            fail_if_already_exists=fail_if_already_exists,
            hostname=hostname,
        )

        if token is None:
            raise errors.BinstarError(
                'Unable to authenticate via Kerberos. Try refreshing your '
                'authentication using `kinit`')

    else:

        if getattr(args, 'login_username', None):
            username = args.login_username
        else:
            username = input('Username: '******'login_password', None)

        for _ in range(3):
            try:
                sys.stderr.write("%s's " % username)

                if password is None:
                    password = getpass.getpass(stream=sys.stderr)

                token = try_replace_token(
                    bs.authenticate,
                    username=username,
                    password=password,
                    application=auth_name,
                    application_url=url,
                    created_with=' '.join(sys.argv),
                    fail_if_already_exists=fail_if_already_exists,
                    hostname=hostname,
                )
                break

            except errors.Unauthorized:
                log.error(
                    'Invalid Username password combination, please try again')
                password = None
                continue

        if token is None:
            parsed_url = urlparse(url)
            if parsed_url.netloc.startswith('api.anaconda.org'):
                netloc = 'anaconda.org'
            else:
                netloc = parsed_url.netloc
            hostparts = (parsed_url.scheme, netloc)
            msg = ('Sorry. Please try again ' + \
                   '(go to %s://%s/account/forgot_password ' % hostparts + \
                   'to reset your password)')
            raise errors.BinstarError(msg)

    return token
Exemple #26
0
def interactive_get_token(args, fail_if_already_exists=True):
    bs = get_binstar(args)
    config = get_config(remote_site=args.site)

    url = config.get("url", "https://api.anaconda.org")

    token = None
    hostname = getattr(args, "hostname", platform.node())
    if getattr(args, "login_username", None):
        username = args.login_username
    else:
        username = input("Username: "******"binstar_client:"
    site = args.site or config.get("default_site")
    if site and site != "binstar":
        # For testing with binstar alpha site
        auth_name += "%s:" % site

    auth_name += "%s@%s" % (getpass.getuser(), hostname)

    password = getattr(args, "login_password", None)

    for _ in range(3):
        try:
            sys.stderr.write("%s's " % username)

            if password is None:
                password = getpass.getpass(stream=sys.stderr)

            token = bs.authenticate(
                username,
                password,
                auth_name,
                url,
                created_with=" ".join(sys.argv),
                fail_if_already_exists=fail_if_already_exists,
                hostname=hostname,
            )
            break

        except errors.Unauthorized:
            log.error("Invalid Username password combination, please try again")
            password = None
            continue

        except errors.BinstarError as err:
            if fail_if_already_exists is True and err.args[1] == 400:
                log.warn("It appears you are already logged in from host %s" % socket.gethostname())
                log.warn(
                    "Logging in again will remove the previous token. "
                    " (This could cause troubles with virtual machines with the same hostname)"
                )
                log.warn("Otherwise you can login again and specify a " 'different hostname with "--hostname"')
                if bool_input("Would you like to continue"):
                    fail_if_already_exists = False
                    continue
                else:
                    raise

    if token is None:
        msg = (
            "Sorry. Please try again " "(go to https://anaconda.org/account/forgot_password " "to reset your password)"
        )
        raise errors.BinstarError(msg)

    return token
Exemple #27
0
def interactive_get_token(args, fail_if_already_exists=True):
    bs = get_binstar(args)
    config = get_config(remote_site=args.site)

    url = config.get('url', 'https://api.anaconda.org')
    parsed_url = urlparse(url)
    token = None
    hostname = getattr(args, 'hostname', platform.node())
    if getattr(args, 'login_username', None):
        username = args.login_username
    else:
        username = input('Username: '******'binstar_client:'
    site = args.site or config.get('default_site')
    if site and site != 'binstar':
        # For testing with binstar alpha site
        auth_name += '%s:' % site

    auth_name += '%s@%s' % (getpass.getuser(), hostname)

    password = getattr(args, 'login_password', None)

    for _ in range(3):
        try:
            sys.stderr.write("%s's " % username)

            if password is None:
                password = getpass.getpass(stream=sys.stderr)

            token = bs.authenticate(username, password, auth_name, url,
                                    created_with=' '.join(sys.argv),
                                    fail_if_already_exists=fail_if_already_exists,
                                    hostname=hostname)
            break

        except errors.Unauthorized:
            log.error('Invalid Username password combination, please try again')
            password = None
            continue

        except errors.BinstarError as err:
            if fail_if_already_exists is True and err.args[1] == 400:
                log.warn('It appears you are already logged in from host %s' % socket.gethostname())
                log.warn('Logging in again will remove the previous token. '
                         ' (This could cause troubles with virtual machines with the same hostname)')
                log.warn('Otherwise you can login again and specify a '
                          'different hostname with "--hostname"')
                if bool_input("Would you like to continue"):
                    fail_if_already_exists = False
                    continue
                else:
                    raise


    if token is None:
        if parsed_url.netloc.startswith('api.anaconda.org'):
            netloc = 'anaconda.org'
        else:
            netloc = parsed_url.netloc
        hostparts = (parsed_url.scheme, netloc)
        msg = ('Sorry. Please try again ' +\
               '(go to %s://%s/account/forgot_password ' % hostparts +\
               'to reset your password)')
        raise errors.BinstarError(msg)

    return token
Exemple #28
0
def main(args):
    config = get_config(site=args.site)

    aserver_api = get_server_api(token=args.token,
                                 site=args.site,
                                 config=config)
    aserver_api.check_server()

    validate_username = True

    if args.user:
        username = args.user
    elif 'upload_user' in config:
        username = config['upload_user']
    else:
        validate_username = False
        user = aserver_api.user()
        username = user['login']

    logger.info('Using "%s" as upload username', username)

    if validate_username:
        try:
            aserver_api.user(username)
        except errors.NotFound:
            message = 'User "{}" does not exist'.format(username)
            logger.error(message)
            raise errors.BinstarError(message)

    uploaded_packages = []
    uploaded_projects = []

    # Flatten file list because of 'windows_glob' function
    files = [f for fglob in args.files for f in fglob]

    if args.all:
        files += get_convert_files(files)

    for filename in files:
        if not exists(filename):
            message = 'File "{}" does not exist'.format(filename)
            logger.error(message)
            raise errors.BinstarError(message)

        package_type = determine_package_type(filename, args)

        if package_type == 'project':
            uploaded_projects.append(upload_project(filename, args, username))
        else:
            if package_type == 'ipynb' and not args.mode == 'force':
                try:
                    nbformat.read(open(filename), nbformat.NO_CONVERT)
                except Exception as error:
                    logger.error("Invalid notebook file '%s': %s", filename,
                                 error)
                    logger.info("Use --force to upload the file anyways")
                    continue

            package_info = upload_package(filename,
                                          package_type=package_type,
                                          aserver_api=aserver_api,
                                          username=username,
                                          args=args)

            if package_info:
                uploaded_packages.append(package_info)

    for package, upload_info in uploaded_packages:
        package_url = upload_info.get(
            'url', 'https://anaconda.org/%s/%s' % (username, package))
        logger.info("{} located at:\n{}\n".format(
            verbose_package_type(package_type), package_url))

    for project_name, url in uploaded_projects:
        logger.info("Project {} uploaded to {}.\n".format(project_name, url))
Exemple #29
0
def interactive_get_token(args, fail_if_already_exists=True):
    bs = get_server_api(args.token, args.site, args.log_level)
    config = get_config(remote_site=args.site)

    token = None
    # This function could be called from a totally different CLI, so we don't
    # know if the attribute hostname exists.
    hostname = getattr(args, 'hostname', platform.node())
    site = args.site or config.get('default_site')
    url = config.get('url', 'https://api.anaconda.org')

    auth_name = 'binstar_client:'
    if site and site != 'binstar':
        # For testing with binstar alpha site
        auth_name += '%s:' % site

    auth_name += '%s@%s' % (getpass.getuser(), hostname)

    auth_type = bs.authentication_type()

    if auth_type == 'kerberos':
        token = try_replace_token(
            bs.krb_authenticate,
            application=auth_name,
            application_url=url,
            created_with=' '.join(sys.argv),
            fail_if_already_exists=fail_if_already_exists,
            hostname=hostname,
        )

        if token is None:
            raise errors.BinstarError(
                'Unable to authenticate via Kerberos. Try refreshing your '
                'authentication using `kinit`')

    else:

        if getattr(args, 'login_username', None):
            username = args.login_username
        else:
            username = input('Username: '******'login_password', None)

        for _ in range(3):
            try:
                sys.stderr.write("%s's " % username)

                if password is None:
                    password = getpass.getpass(stream=sys.stderr)

                token = try_replace_token(
                    bs.authenticate,
                    username=username,
                    password=password,
                    application=auth_name,
                    application_url=url,
                    created_with=' '.join(sys.argv),
                    fail_if_already_exists=fail_if_already_exists,
                    hostname=hostname,
                )
                break

            except errors.Unauthorized:
                log.error('Invalid Username password combination, please try again')
                password = None
                continue


        if token is None:
            parsed_url = urlparse(url)
            if parsed_url.netloc.startswith('api.anaconda.org'):
                netloc = 'anaconda.org'
            else:
                netloc = parsed_url.netloc
            hostparts = (parsed_url.scheme, netloc)
            msg = ('Sorry. Please try again ' + \
                   '(go to %s://%s/account/forgot_password ' % hostparts + \
                   'to reset your password)')
            raise errors.BinstarError(msg)

    return token