def init(): config_dir = os.getcwd() config_filename = f".{app.info.name}.yml" config_path: Path = Path(config_dir) / config_filename typer.echo( f"👋 Welcome in {app.info.name}, we are going to edit your {config_filename}" ) understand_wikilinks = typer.confirm( "Should it understand wiki-links (example `[[Label]]`):", default=True) reference_by = typer.prompt( "Should the title or the filename be considered as the unique key to reference a note ?", type=Choice(["title", "filename"], case_sensitive=False), show_choices=True, default="filename", ) link_system = typer.prompt( "What is your link system links or wiki-links ?", type=Choice(["wikilink", "link"], case_sensitive=False), show_choices=True, default="link", ) init_config = LinkyNoteConfig( parse_config=ParseConfig(parse_wikilinks=understand_wikilinks), modify_config=ModifyConfig(reference_by=reference_by, link_system=link_system), ) Config.write(config_path, init_config)
def bootstrap(service_ctx, application): # type: (ServiceContext, str,bool,str) -> None cc = CodeCreator("", service_ctx.dry_run) service_def = Service(app=application, role="master", definition={}) service_def.set_service_type("service-buddy-master") directory = service_ctx.destination_directory if directory == "./code": #override default for this usecase directory = "./" config = {} vcs_provider = click.prompt('Please select your source code repository', type=Choice(vcs.vcs_providers)) config['vcs-provider'] = vcs_provider vcs_options = vcs.options for key, value in vcs_options.iteritems(): config['vcs_{}'.format(key)] = click.prompt("VCS: {} ({})".format( value, key)) ci_provider = click.prompt('Please select your build system - ', type=Choice(ci.build_systems)) config['build-system-provider'] = ci_provider ci_options = ci.build_system_map[ci_provider].options() for key, value in ci_options.iteritems(): config['build-system-{}'.format(key)] = click.prompt( "Build System: {} ({})".format(value, key)) cc.create_project(service_definition=service_def, app_dir=directory, extra_config=config)
def prompt_global_params(params): """Prompt global parameters.""" _params = params["global"] if "year" not in params or not _params["year"]: _params["year"] = datetime.datetime.now().year if "license" not in params: _prompt_param( _params, "license", "License", param_type=Choice(LICENSES), show_choices=True, ) _prompt_param(_params, "author_name", "Author name", default=get_username()) _prompt_param(_params, "author_email", "Author email", default=get_usermail()) _prompt_param(_params, "organization", "Organization", default=get_username())
def choose_managed_user(account: MyPlexAccount): users = [u.title for u in account.users() if u.friend] if not users: return None click.echo(success("Managed user(s) found:")) users = sorted(users) for user in users: click.echo(f"- {user}") if not click.confirm(PROMPT_MANAGED_USER): return None # choice = prompt_choice(users) user = click.prompt( title("Please select:"), type=Choice(users), show_default=True, ) # Sanity check, even the user can't input invalid user user_account = account.user(user) if user_account: return user return None
def stage_option(func): """ Add option to decorated command func for specifying image build Stage :param func: Click CLI command to decorate :return: decorated CLI command """ return option( '--stage', '-s', type=Choice([ Stage.bare, Stage.base, Stage.build, Stage.install, Stage.fork, Stage.crio, Stage.ose_master, Stage.ose_enterprise_39, Stage.ose_enterprise_38, Stage.ose_enterprise_37, Stage.ose_enterprise_36, ]), # default=Stage.install, show_default=True, metavar='NAME', help='VM image stage.', )(func)
def raw_preset_option(help_action, callback): """ Get an option for OpenShift version presets. :param help_action: the helptext for the preset option :param callback: the callback for the preset option :return: the preset option """ return option( '--for', '-f', 'preset', type=Choice([ Preset.origin_master, Preset.ose_master, Preset.ose_32, Preset.ose_321, Preset.ose_33, ]), metavar='PRESET', expose_value=False, help=help_action + ' using a pre-set configuration for a specific version of OpenShift.', callback=callback, )
def repository_argument(func): """ Add the repository selection argument to the decorated command func. :param func: Click CLI command to decorate :return: decorated CLI command """ return argument('repository', nargs=1, type=Choice([ Repository.origin, Repository.enterprise, Repository.web_console, Repository.web_console_server, Repository.source_to_image, Repository.metrics, Repository.logging, Repository.online, Repository.online_hibernation, Repository.release, Repository.aoscdjobs, Repository.openshift_ansible, Repository.jenkins, Repository.wildfly, Repository.jenkins_plugin, Repository.jenkins_sync_plugin, Repository.jenkins_client_plugin, Repository.jenkins_login_plugin, Repository.image_registry, Repository.cluster_operator, Repository.kubernetes_metrics_server, ]))(func)
def prompt_for_new_args(name=None, default_destination="cwd", edit_after=None) -> Iterator[Any]: """Prompt for all arguments needed to perform `not do`""" title = ask(glot["new_title_prompt"]) name = slugify(title) if name is None else name prompts = ( (glot["new_description_prompt"], { "default": "" }), (glot["new_name_prompt"], { "default": name }), ( glot["new_destination_prompt"], { "default": default_destination, "type": Choice(["home", "cwd"]), "show_choices": True, }, ), (glot["new_open_editor_prompt"], { "default": edit_after, "type": bool }), ) return (title, *multiprompt(*prompts))
def create_print_wrapper(f): """Creates a print wrapper for commands This adds the necessary options for formatting results as well as wrapping the command to handle those formatting options. :param f: the function to wrap :type f: function :returns: the wrapped function :rtype: function """ def new_func(*args, **kwargs): response_format = kwargs.pop('format') response = f(*args, **kwargs) echo(format_output(response, response_format)) return response new_func = update_wrapper(new_func, f) insert_click_param( new_func, Option( ['--format'], type=Choice(['json_pp', 'json', 'yaml', 'column']), default='column', help= 'Specify how responses should be formatted and echoed to the terminal.' )) return new_func
def choose_default_calendar(vdirs): names = [name for name, _, _ in sorted(vdirs or ())] print("Which calendar do you want as a default calendar?") print("(The default calendar is specified, when no calendar is specified.)") print(f"Configured calendars: {', '.join(names)}") default_calendar = prompt( "Please type one of the above options", default=names[0], type=Choice(names), ) return default_calendar
class Command(CommandBase): """Display Pureport task information """ @option('-s', '--state', type=Choice(STATE_CHOICES), help='The task state.') @option('-pn', '--page_number', type=int, help='The page number for pagination.') @option('-ps', '--page_size', type=int, help='The page size for pagination.') def list(self, state=None, page_number=None, page_size=None): """Display list of all tasks \f :param state: Filter results based on state :type state: str :param page_number: page number to display :type page_number: int :param page_size: number of results per page :type page_size: int :returns: a list of Task objects :rtype: list """ params = { 'state': state, 'pageNumber': page_number, 'pageSize': page_size } kwargs = {'query': dict(((k, v) for k, v in params.items() if v))} return self.__call__('get', '/tasks', **kwargs) @argument('task_id') def get(self, task_id): """Get a task by it's id. \f :param task_id: the ide of the task to retrieve :type task_id: string :returns: a Task object :rtype: dict """ return self.__call__('get', '/tasks/{}'.format(task_id))
def repository_argument(func): """ Add the repository selection argument to the decorated command func. :param func: Click CLI command to decorate :return: decorated CLI command """ return argument('repository', nargs=1, type=Choice([ Repository.origin, Repository.enterprise, Repository.web_console, Repository.source_to_image, Repository.metrics, Repository.logging ]))(func)
def package_options(func): """ Add all of the package options to the decorated command func. :param func: Click CLI command to decorate :return: decorated CLI command """ return option( '--stage', '-s', 'upgrade_stage', type=Choice(['current', 'next', 'fork', 'base', 'crio']), help= 'Update the current stage, upgrade to next default stage, or choose a stage', )(func)
class LevelType(ParamType): _choice = Choice(tuple(item.name.lower() for item in Status), case_sensitive=False) name = _choice.name def get_metavar(self, param: Parameter) -> str: return self._choice.get_metavar(param) def get_missing_message(self, param: Parameter) -> str: return self._choice.get_missing_message(param) def convert(self, value: Any, param: Optional[Parameter], ctx: Optional[Context]) -> Status: if isinstance(value, Status): return value key = self._choice.convert(value, param, ctx).lower() return next(item for item in Status if item.name.lower() == key)
def provider_option(func): """ Add option to decorated command func for specifying cloud provider (e.g. AWS, GCP, etc.) :param func: Click CLI command to decorate :return: decorated CLI command """ return option( '--provider', '-p', type=Choice([ Provider.aws, ]), default=Provider.aws, show_default=True, metavar='NAME', help='Cloud provider.', )(func)
def operating_system_option(func): """ Add option to decorated command func for specifying OperatingSystem :param func: Click CLI command to decorate :return: decorated CLI command """ return option( '--os', '-o', 'operating_system', type=Choice([ OperatingSystem.fedora, OperatingSystem.centos, OperatingSystem.rhel, ]), show_default=True, metavar='NAME', help='VM operating system.', )(func)
def print_menu(options: List[Tuple], title: str, enable_no_selection=True) -> Optional: """ options should be in the form [(name, value)] example: [("School #1", "ABC")] """ clear() print(title) if enable_no_selection: print("0: Return without selecting an option") for index, (option, value) in enumerate(options): print(str(index + 1) + ":", option) start_index = 0 if enable_no_selection else 1 choices = Choice(list(map(str, range(start_index, len(options) + 1)))) choice = prompt("Select an item", type=choices) if choice == '0': print("Selecting None") return None print(options) return options[int(choice) - 1][1]
def configure_cli(self): @self.cli.command(name="run_service") @argument("name") @option("--devices") @option("--payload") def start(name, devices, payload): devices_list = devices.split(",") if devices else [] devices_list = [ db.fetch("device", name=name).id for name in devices_list ] payload_dict = loads(payload) if payload else {} payload_dict.update(devices=devices_list, trigger="CLI", creator=getuser()) service = db.fetch("service", name=name) results = app.run(service.id, **payload_dict) db.session.commit() echo(app.str_dict(results)) @self.cli.command(name="delete_log") @option( "--keep-last-days", default=15, help="Number of days to keep", ) @option( "--log", "-l", required=True, type=Choice(("changelog", "result")), help="Type of logs", ) def delete_log(keep_last_days, log): deletion_time = datetime.now() - timedelta(days=keep_last_days) app.result_log_deletion( date_time=deletion_time.strftime("%d/%m/%Y %H:%M:%S"), deletion_types=[log], ) app.log("info", f"deleted all logs in '{log}' up until {deletion_time}")
def _add_plugins(self, ctx): if ctx.obj.initiated: active = ctx.obj.meta.features append_unique( self.params, click.core.Option( (f"--scope", ), type=Choice(active), show_choices=True, multiple=True, help="Execute stages only from given plugins", )) else: for name, plugin in ctx.obj.plugins.plugins.items(): append_unique( self.params, click.core.Option( (f"--with-{name}/--without-{name}", ), default=True, is_flag=True, help=plugin.description, ))
def prompt_server(servers: List[MyPlexResource]): old_age = datetime.now() - timedelta(weeks=1) def fmt_server(s): if s.lastSeenAt < old_age: decorator = disabled else: decorator = comment product = decorator(f"{s.product}/{s.productVersion}") platform = decorator(f"{s.device}: {s.platform}/{s.platformVersion}") click.echo( f"- {highlight(s.name)}: [Last seen: {decorator(str(s.lastSeenAt))}, Server: {product} on {platform}]" ) c: ResourceConnection for c in s.connections: click.echo(f" {c.uri}") owned_servers = [s for s in servers if s.owned] unowned_servers = [s for s in servers if not s.owned] sorter = partial(sorted, key=lambda s: s.lastSeenAt) server_names = [] if owned_servers: click.echo(success(f"{len(owned_servers)} owned servers found:")) for s in sorter(owned_servers): fmt_server(s) server_names.append(s.name) if unowned_servers: click.echo(success(f"{len(owned_servers)} unowned servers found:")) for s in sorter(unowned_servers): fmt_server(s) server_names.append(s.name) return click.prompt( title("Select default server:"), type=Choice(server_names), show_default=True, )
def repository_argument(func): """ Add the repository selection argument to the decorated command func. :param func: Click CLI command to decorate :return: decorated CLI command """ return argument('repository', nargs=1, type=Choice([ Repository.origin, Repository.enterprise, Repository.web_console, Repository.source_to_image, Repository.metrics, Repository.logging, Repository.online, Repository.release, Repository.aoscdjobs, Repository.openshift_ansible, Repository.jenkins, ]))(func)
def generate_page_dialog_params( page_no: int, ) -> Tuple[DialogParameter, DialogParameter, DialogParameter, DialogParameter]: # noinspection PyUnresolvedReferences return ( DialogParameter(title=f"pages.page{page_no}.page_title", comment="The title of the page"), DialogParameter(title=f"pages.page{page_no}.page_file", comment="File containing page text"), DialogParameter( title=f"pages.page{page_no}.page_file_format", comment= "Text format of the page file. None or default - the script will try to guess it at runtime.", type=Choice([_[0] for _ in AllowedFileFormat.__members__.items() ]), # making the linter happy, see JetBrains PY-36205 required=False, ), DialogParameter( title=f"pages.page{page_no}.page_space", comment="Key of the space with the page", required=False, ), )
class ExecutorFactoryType(ParamType): _choice = Choice( tuple(_CONCURRENT_EXECUTOR_FACTORY_MAP.keys()), case_sensitive=False, ) name = _choice.name def get_metavar(self, param): return self._choice.get_metavar(param) def get_missing_message(self, param): return self._choice.get_missing_message(param) def convert( self, value: Any, param: Optional[Parameter], ctx: Optional[Context], ) -> ExecutorFactory: if isinstance(value, ExecutorFactory): return value key = self._choice.convert(value, param, ctx) return _CONCURRENT_EXECUTOR_FACTORY_MAP[key.lower()]
from . import version from .logging import configure_logging from .qt import Patray def main(config): configure_logging(config.log_level) logger.info("patray: version {}, config {}", version, config) app = QApplication(sys.argv) app.setQuitOnLastWindowClosed(False) _ = Patray(config) sys.exit(app.exec_()) style = Choice(["combo", "radio"]) options = [ option("--profile-enabled", default=True, type=bool), option("--profile-style", default="combo", type=style), option("--port-enabled", default=True, type=bool), option("--port-style", default="radio", type=style), option("--port-maximum-volume", default=100, type=int), option("--port-hide-by-mask", multiple=True), option("--log-level", default="INFO"), option("--icon-path", default=None, required=False, type=Path(exists=True, dir_okay=False, readable=True, resolve_path=True)),
platform='universal')).replace(' ', '_') def rand_string(length, chars=ascii_letters) -> str: return ''.join(random.choice(chars) for _ in range(length)) @group('iccas') def main(): plt.style.use('seaborn') @main.command() @option_group( 'Data processing options', option('--variable', type=Choice(['cases', 'deaths']), default='cases'), option('--window', type=int, default=7, help='Size (in days) of the time window'), option('-n/-N', '--normalize/--no-normalize', default=True), option('--interpolation', type=Choice(['linear', 'pchip']), default='pchip'), ) @option_group( 'Figure and chart options', option('--population / --no-population', 'show_population', default=True, help='if --normalize, do/don\'t plot the age distribution of the '
raise click.BadParameter("Could not guess a database location") @group() @option( "--repository", "-r", default=lambda: find_root(MARKER_DIRECTORIES), type=Path(exists=True, file_okay=False), help="Root of the repository (regardless of the directory analyzed)", ) @option( "--database-engine", "--database", type=Choice([DBType.SQLITE, DBType.MEMORY]), default=DBType.SQLITE, help="database engine to use", ) @option( "--database-name", "--dbname", callback=default_database, type=Path(dir_okay=False) ) @click.pass_context def cli( ctx: click.Context, repository: Optional[str], database_engine: DBType, database_name: Optional[str], ): ctx.obj = Context( repository=repository,
@setup.command() @option('--username', prompt=True, callback=validate_username, help='Username used to log in.') @option('--email', prompt='E-mail', callback=validate_email, help='E-mail address of the user.') @password_option(default='generated', callback=validate_password, help='Password for the user.') @option('--role', type=Choice([role.name for role in UserRole]), default=UserRole.reporter.name, prompt=True, callback=lambda ctx, param, role: role, help='Permission group of the user.') @option('--active/--inactive', default=True, prompt=True, help='Enable or disable the user.') def user(username, email, password, role, active): """Create a new application user.""" from tracker import db from tracker.user import hash_password from tracker.user import random_string
input_counts, output_counts): fields = [clone] for (i, oc) in enumerate(ocs): fields.append('{:.2f}'.format(log10pval_hash[(i, ic, oc)])) print('\t'.join(fields), file=op) @cli.command(name='merge-columns') @option('-i', '--input', required=True, help='input path (directory of tab-delim files)') @option('-o', '--output', required=True, help='output path') @option('-m', '--method', type=Choice(['iter', 'outer']), default='iter', help='merge/join method') @option('-p', '--position', type=int, default=1, help='the field position to merge (0-indexed)') @option('-d', '--index-cols', default=1, help='number of columns to use as index/row-key') def merge_columns(input, output, method, position, index_cols): """merge tab-delim files method: iter -- concurrently iterate over lines of all files; assumes
@option( "--db", nargs=1, default=lambda: os.environ.get('PIPENV_SAFETY_DB', False), help="Path to a local PyUp Safety vulnerabilities database." " Default: ENV PIPENV_SAFETY_DB or None.", ) @option( "--ignore", "-i", multiple=True, help="Ignore specified vulnerability during PyUp Safety checks.", ) @option( "--output", type=Choice(["default", "json", "full-report", "bare"]), default="default", help="Translates to --json, --full-report or --bare from PyUp Safety check", ) @option( "--key", help="Safety API key from PyUp.io for scanning dependencies against a live" " vulnerabilities database. Leave blank for scanning against a" " database that only updates once a month.", ) @option("--quiet", is_flag=True, help="Quiet standard output, except vulnerability report.") @common_options @system_option @argument("args", nargs=-1)
@group() def cli(): pass @cli.command(help="interactive exploration of issues") def explore(): echo("Interactive mode not yet implemented") @cli.command(help="parse static analysis output and save to disk") @option( "--database", type=Choice(["memory", "sqlite"]), default="memory", help="database engine to use", ) @option("--database-name", "--dbname", type=str) @option("--run-kind", type=str) @option("--repository", type=str) @option("--branch", type=str) @option("--commit-hash", type=str) @option("--job-id", type=str) @option("--differential-id", type=int) @option( "--previous-issue-handles", type=Path(exists=True), help=("file containing list of issue handles to compare INPUT_FILE to " "(preferred over --previous-input)"),