def choose_license(licenses, author, year):
click.echo("Found the following matching licenses:")
click.echo(
green(
"\n".join(
[
'{index}: {name}'.format(index=index + 1, name=lic.name)
for index, lic in enumerate(licenses)
]
)
)
)
choice = click.prompt(
"Please choose which one you'd like to add",
default=1,
type=click.IntRange(1, len(licenses))
)
return licenses[choice - 1]
python类IntRange()的实例源码
def option(*param_decls, **attrs):
""" Add a Click option. """
def decorator(f):
if isinstance(attrs.get("type"), click.IntRange):
r = attrs["type"]
attrs["help"] += " [range: {0}-{1}]".format(r.min, r.max)
if attrs.get("default") not in (None, False, 0):
attrs["help"] += " [default: {0}]".format(attrs["default"])
return click.option(*param_decls, **attrs)(f)
return decorator
def channels_option(**attrs):
attrs.setdefault("help", "Color channel count (1=gray, 2=gray+alpha, 3=HSV/RGB, 4=RGB+alpha)")
return int_option("--channels", type=click.IntRange(1, 4), default=3, **attrs)
def octaves_option(**attrs):
attrs.setdefault("help", "Octave count: Number of multi-res layers")
return int_option("--octaves", type=click.IntRange(1, 10), default=1, **attrs)
def warp_octaves_option(**attrs):
attrs.setdefault("help", "Octave Warp: Octave count for --warp")
return int_option("--warp-octaves", type=click.IntRange(1, 10), default=3, **attrs)
def reverb_option(**attrs):
attrs.setdefault("help", "Post-reduce tiled octave count")
return int_option("--reverb", type=click.IntRange(1, 10), default=None, **attrs)
def point_freq_option(default=3.0, **attrs):
attrs.setdefault("help", "Voronoi/DLA: Approximate lengthwise point cloud frequency (freq * freq = count)")
return int_option("--point-freq", type=click.IntRange(1, 10), default=default, **attrs)
def point_generations_option(**attrs):
attrs.setdefault("help", "Voronoi/DLA: Penrose-ish generations. When using, keep --point-freq below ~3 to avoid OOM")
return int_option("--point-generations", type=click.IntRange(1, 3), default=1, **attrs)
def convert_primitive(ast):
import click
mapping = {
'Int': int,
'Str': str,
'Float': float,
'Color': str,
'Bool': bool
}
# TODO: it would be a good idea to refactor this someday, but until then
# just handle the few predicates we know about.
predicate = ast['predicate']
if predicate:
if predicate['name'] == 'Choices' and ast['name'] == 'Str':
return click.Choice(predicate['choices'])
elif predicate['name'] == 'Range' and ast['name'] == 'Int':
start = predicate['start']
end = predicate['end']
# click.IntRange is always inclusive
if start is not None and not predicate['inclusive-start']:
start += 1
if end is not None and not predicate['inclusive-end']:
end -= 1
return click.IntRange(start, end)
elif predicate['name'] == 'Range' and ast['name'] == 'Float':
# click.FloatRange will be in click 7.0, so for now the
# range handling will just fallback to qiime2.
return mapping['Float']
else:
raise NotImplementedError()
else:
return mapping[ast['name']]
def __init__(self, min=None, max=None):
self.intrange = click.IntRange(min, max)
def trait_to_option(name, trait):
if is_trait(trait):
if isinstance(trait, Int):
return click.Option(param_decls=('--' + name,),
default=trait.default_value,
type=click.IntRange(trait.min, trait.max))
elif isinstance(trait, Float):
return click.Option(param_decls=('--' + name,),
default=trait.default_value,
type=float)
elif isinstance(trait, Complex):
return click.Option(param_decls=('--' + name,),
default=trait.default_value,
type=complex)
elif isinstance(trait, Bool):
return click.Option(param_decls=('--' + name,),
default=trait.default_value,
is_flag=True)
elif isinstance(trait, Unicode):
return click.Option(param_decls=('--' + name,),
default=trait.default_value,
type=str)
elif isinstance(trait, Enum):
# FIXME: trait.values should be strings
return click.Option(param_decls=('--' + name,),
default=str(trait.default_value),
type=click.Choice(list(map(str, trait.values))))
elif isinstance(trait, Tuple):
return click.Option(param_decls=('--' + name,),
default=trait.default_value,
type=tuple(
trait_to_type(t) for t in trait._traits))
else:
raise InvalidValue('Trait conversion is not supported for: '
'{}'.format(trait))
else:
raise InvalidType('Trait should be instance of {}'.format(TraitType))
def __init__(self, option):
if option.choices:
type_ = click.Choice(option.choices)
elif option.min is not None or option.max is not None:
type_ = click.IntRange(min=option.min, max=option.max)
else:
type_ = TYPES[option.type_name]
super().__init__(
param_decls=option.cli, help=option.help,
default=None, type=type_)
self.metadata = option.metadata
def test_int_range_type(self):
class Option(IntegerOption):
metadata = 'name'
min = 10
max = 20
cli = ['--name']
click_option = ClickObjectOption(Option)
self.assertIsInstance(click_option.type, click.IntRange)
self.assertEqual(click_option.type.min, 10)
self.assertEqual(click_option.type.max, 20)
def choose_role_to_assume(config, principal_roles):
chosen_principal_arn = None
chosen_role_arn = None
principal_roles_emptied = not bool(principal_roles)
if principal_roles_emptied:
return chosen_principal_arn, chosen_role_arn
role_collection = []
principal_roles = collections.OrderedDict(sorted(principal_roles.items(), key=lambda t: t[0]))
for account_name in principal_roles.keys():
roles = principal_roles[account_name]
for role_arn in roles.keys():
role_collection.append([roles[role_arn]['principal_arn'], role_arn])
logging.debug(u'Role arn from config: {}'.format(config.role_arn))
chosen_principal_role = [role for role in role_collection if config.role_arn == role[1]]
logging.debug(u'Calculated role collection: {}'.format(role_collection))
if len(chosen_principal_role) == 1:
logging.debug(u'Chosen principal role based on previously used role_arn stored in config: {}'
.format(chosen_principal_role))
chosen_principal_arn = chosen_principal_role[0][0]
chosen_role_arn = chosen_principal_role[0][1]
return chosen_principal_arn, chosen_role_arn
if len(role_collection) == 1:
logging.debug(u'There is only one role to choose')
chosen_principal_arn = role_collection[0][0]
chosen_role_arn = role_collection[0][1]
elif len(role_collection) > 1:
logging.debug(u'Manual choice')
click.echo(u'Please choose the role you would like to assume:')
i = 0
for account_name in principal_roles.keys():
roles = principal_roles[account_name]
click.echo('{}:'.format(account_name))
for role_arn in roles.keys():
role_entry = roles[role_arn]
click.echo(' [ {} -> {} ]: {}'.format(role_entry['name'].ljust(30, ' ' if i % 2 == 0 else '.'), i, role_arn))
i += 1
selected_index = click.prompt(text='Selection', type=click.IntRange(0, len(role_collection)))
chosen_principal_arn = role_collection[selected_index][0]
chosen_role_arn = role_collection[selected_index][1]
return chosen_principal_arn, chosen_role_arn