def et(ctx: click.core.Context, verbose: bool): """ Primary top-level group command. Calling directly with no parameters will display help. """ ctx.obj = {} ctx.obj['verbose'] = verbose
def main(ctx: click.core.Context, db: str): """tasks3 is a commandline tool to create and manage tasks and todo lists""" ctx.ensure_object(dict) ctx.obj["DB"] = db return 0
def _wait_for_remote_mount( max_attempts: int, ctx: click.core.Context, remote_encrypted: Path, path_on_cloud_drive: str, ) -> None: """ Wait for the rclone mount or error if it does not start within some time close to 25 seconds. """ relative_path_on_cloud_drive = Path(path_on_cloud_drive).relative_to('/') remote_mount = remote_encrypted / relative_path_on_cloud_drive attempts = 0 sleep_seconds = 5 while not remote_mount.exists(): attempts += 1 if attempts > max_attempts: message = ( f'Remote mount not found after {max_attempts} attempts, ' 'exiting.') ctx.fail(message) message = f'Remote mount {remote_mount} does not exist yet, waiting.' LOGGER.info(message) time.sleep(sleep_seconds)
def cli(ctx: click.core.Context, url: str, request_id: str) -> None: """Python library for convenient access to the iov42 platform..""" ctx.ensure_object(dict) # TODO: lazy creation of identity for the 'create identity' command. For now # we provide a dummy identity which will replaced at a later stage. ctx.obj["url"] = url ctx.obj["request_id"] = request_id
def download_artifact( ctx: click.core.Context, dcos_version: str, download_path: str, ) -> None: """ Download a DC/OS Open Source artifact. For DC/OS Enterprise release artifacts, contact your sales representative. """ path = Path(download_path) label = 'Downloading to ' + str(path) base_url = 'https://downloads.dcos.io/dcos/' url = base_url + dcos_version + '/dcos_generate_config.sh' head_resp = requests.head(url) if not head_resp.ok: message = 'Cannot download artifact from {url}.'.format(url=url) ctx.fail(message=message) if path.is_dir(): path = path / 'dcos_generate_config.sh' if not path.exists(): path.parent.mkdir(parents=True, exist_ok=True) # See # https://stackoverflow.com/questions/16694907/how-to-download-large-file-in-python-with-requests-py stream = requests.get(url, stream=True) assert stream.ok content_length = int(stream.headers['Content-Length']) total_written = 0 chunk_size = 1024 # See http://click.pocoo.org/6/arguments/#file-args for parameter # information with click.open_file( filename=str(path), mode='wb', atomic=True, lazy=True, ) as file_descriptor: content_iter = stream.iter_content(chunk_size=chunk_size) with click.progressbar( # type: ignore content_iter, length=content_length / chunk_size, label=label, ) as progress_bar: for chunk in progress_bar: # Filter out keep-alive new chunks. if chunk: total_written += len(chunk) file_descriptor.write(chunk) # type: ignore message = ('Downloaded {total_written} bytes. ' 'Expected {content_length} bytes.').format( total_written=total_written, content_length=content_length, ) assert total_written == content_length, message
def main(ctx: click.core.Context, broker_url: str, queue_name: str, connection_timeout: int): """Simple CLI for messaging""" ctx.ensure_object(dict) ctx.obj["BROKER_URL"] = broker_url ctx.obj["QUEUE_NAME"] = queue_name ctx.obj["CONNECTION_TIMEOUT"] = connection_timeout
def stream_pipeline(context: click.core.Context): logging.info("Kafka -> Spark -> MongoDB") project_root = context.obj['PROJECT_ROOT'] configurator = get_configurator(project_root)._configuration_data context = AppSparkContext(configurator) st = StreamingPipeline(configurator, context) st.start_streaming('my_topic') context.stop_spark_context()
def main(ctx: click.core.Context, **kwargs: Any) -> None: """primer - prime projects for blackening... 🏴""" LOG.debug(f"Starting {sys.argv[0]}") # TODO: Change to asyncio.run when Black >= 3.7 only loop = asyncio.get_event_loop() try: ctx.exit(loop.run_until_complete(async_main(**kwargs))) finally: loop.close()
def cli( ctx: click.core.Context, token: str, verbose: int, log_to_console: bool, log_to_file: bool, log_file_name: str, debug: bool, result_dir: str, ): """The foss_cli cmdline. Multiple -v increase verbosity-level. """ if log_to_console: console_handler = logging.StreamHandler() console_handler.setFormatter(formatter) logger.addHandler(console_handler) if not os.path.isdir(result_dir): os.mkdir(result_dir) if log_to_file: logfile_handler = RotatingFileHandler( os.path.join(result_dir, log_file_name), maxBytes=MAX_SIZE_OF_LOGFILE, backupCount=MAX_NUMBER_OF_LOGFILES, ) logfile_handler.setFormatter(formatter) logger.addHandler(logfile_handler) logger.setLevel(FOSS_LOGGING_MAP.get(verbose, logging.DEBUG)) assert os.path.isdir(result_dir) ctx.obj["VERBOSE"] = verbose ctx.obj["TOKEN"] = token ctx.obj["DEBUG"] = debug ctx.obj["RESULT_DIR"] = result_dir if ctx.obj["VERBOSE"] >= 2: logger.debug(f"foss_cli called with: {pprint.pformat(sys.argv)}") foss_needs_initialization = needs_later_initialization_of_foss_instance( ctx) if foss_needs_initialization: logger.debug( "Initializing Fossology client according to the CLI context") foss = init_foss(ctx) # leaves the foss instance within the ctx dict else: logger.debug("Initialization of Fossology client is not needed") if debug: logger.debug("Started in debug mode") if foss_needs_initialization: logger.debug( f"Using API: {pprint.pformat(foss.api)} version {pprint.pformat(foss.version)}" ) logger.debug( f"Running as user {pprint.pformat(foss.user.name)} on {pprint.pformat(foss.host)}" ) else: logger.debug("Fossology client was not initialized")
def print_version( ctx: click.core.Context, param: Union[click.core.Option, click.core.Parameter], value: Any, ) -> Any: """Print version click callback.""" if not value or ctx.resilient_parsing: return click.echo(__package__ + " version: " + __version__) ctx.exit()
def cli(ctx: click.core.Context, config: str, endpoint: str, username: str, password: str, skip_verify: bool) -> None: """Nessie cli tool. Interact with Nessie branches and tables via the command line """ if config: os.environ["NESSIE_CLIENTDIR"] = config config = build_config({"endpoint": endpoint, "username": username, "password": password, "verify": not skip_verify}) nessie = NessieClient(config) ctx.obj = dict() ctx.obj["nessie"] = nessie
def init(ctx: click.core.Context, site_path: str) -> None: """Create an new mackerel site""" output_path = Path(site_path) sample_site_path = Path( os.path.dirname(os.path.realpath(mackerel.__file__))) / 'site' try: shutil.copytree(src=sample_site_path, dst=output_path) except FileExistsError as e: ctx.fail(f'Initialize failed, file {e.filename} already exists') click.echo(f'Initialized empty mackerel site in {output_path}')
def init(ctx: click.core.Context, site_path: str) -> None: """Create an new mackerel site""" output_path = Path(site_path) sample_site_path = Path(os.path.dirname( os.path.realpath(mackerel.__file__))) / 'site' try: shutil.copytree(src=sample_site_path, dst=output_path) except FileExistsError as e: ctx.fail(f'Initialize failed, file {e.filename} already exists') click.echo(f'Initialized empty mackerel site in {output_path}')
def main(ctx: click.core.Context, **kwargs) -> None: ret_val = 0 LOG.info(f"Starting {sys.argv[0]}") loop = asyncio.get_event_loop() try: ret_val = loop.run_until_complete(async_main(**kwargs)) finally: loop.close() ctx.exit(ret_val)
def main(ctx: click.core.Context, host: str, user: str, password: typing.Optional[str], schema: str) -> None: """Main entrypoint for fuzzy-tribble. Type --help after any subcommand for additional help.""" ctx.obj = {} creds = tribble.database.Creds(host, user, password, schema) engine = tribble.database.connect_db(creds) contract.Session.configure(bind=engine) ctx.obj['creds'] = creds ctx.obj['engine'] = engine
def access_token_check( ctx: click.core.Context, _: click.core.Option, access_token: Optional[str], required: bool, ) -> Union[str, NoReturn]: """Check if access token is present.""" if not access_token and required: display_message(ERROR_MESSAGES["missing_access_token"], msg_type="error") ctx.exit(1) else: return access_token
def cli(ctx: click.core.Context) -> None: """ A Python package for generating static websites using AWS CloudFormation. \f :type ctx: click.core.Context :param ctx: Click context object :rtype: None :return: None """ if ctx.invoked_subcommand is None: click.echo(ctx.get_help()) ctx.exit(1)
def get_command(self, ctx: click.core.Context, cmd_name: str) -> Optional[click.core.Command]: rv = click.core.Group.get_command(self, ctx, cmd_name) if rv is not None: return rv matches = difflib.get_close_matches(cmd_name, self.list_commands(ctx), n=2) if not matches: return None elif len(matches) == 1: return click.core.Group.get_command(self, ctx, str(matches[0])) else: ctx.fail('Too many matches: {0}'.format(matches)) return None
def print_version(ctx: click.core.Context, param: Union[click.core.Option, click.core.Parameter], value: Union[bool, int, str]): """Print version callback method Args: ctx: click context param: click param value: click value """ if param == 'test': return if not value or ctx.resilient_parsing: return click.echo('Putio Aria2c Downloader version {}'.format(__version__)) ctx.exit()
def find_or_create_session(context: click.core.Context, session: Optional[str], build_name: Optional[str], flavor=[]) -> Optional[str]: """Determine the test session ID to be used. 1. If the user explicitly provides the session id via the `--session` option 2. If the user gives no options, the current session ID is read from the session file tied to $PWD, or one is created from the current build name. See https://github.com/launchableinc/cli/pull/342 3. The `--build` option is legacy compatible behaviour, in which case a session gets created and tied to the build. Args: session: The --session option value build_name: The --build option value """ from .record.session import session as session_command if session: return session saved_build_name = read_build() if not saved_build_name: raise click.UsageError( click.style( "Have you run `launchable record build`?\nIf not, please do. If it was run elsewhere/earlier, please use the --session option", fg="yellow")) else: if build_name and saved_build_name != build_name: raise click.UsageError( click.style( "Given build name ({}) is different from when you ran `launchable record build --name {}`.\nMake sure to run `launchable record build --name {}` before." .format(build_name, saved_build_name, build_name), fg="yellow")) session_id = read_session(saved_build_name) if session_id: return session_id else: context.invoke(session_command, build_name=saved_build_name, save_session_file=True, print_session=False, flavor=flavor) return read_session(saved_build_name)
def wrapper(ctx: click.core.Context, **kwargs: Any) -> Any: # store all options in the context object for name, value in kwargs.items(): ctx.obj[name] = value # launch the app code from here run(ctx) return func()
def main(ctx: click.core.Context, config_file: str): path = Path(config_file) data = {} if path.exists() and path.is_file(): with open(config_file, 'rb') as fd: data = yaml.safe_load(fd) ctx.obj = {'config': data, 'config_file': path, 'config_dir': path.parent}
def main(ctx: click.core.Context, username: str, password: str, stdin_password: bool) -> None: if not (password or stdin_password): raise click.UsageError( "Must supply one of `password` or `stdin_password`") if stdin_password: password = input() ctx.obj = AirtableCredentials(username=username, password=password)
def destroy_list( ctx: click.core.Context, cluster_ids: List[str], ) -> None: """ Destroy clusters. To destroy all clusters, run ``dcos-vagrant destroy $(dcos-vagrant list)``. """ for cluster_id in cluster_ids: if cluster_id not in existing_cluster_ids(): warning = 'Cluster "{cluster_id}" does not exist'.format( cluster_id=cluster_id, ) click.echo(warning, err=True) continue ctx.invoke( destroy, cluster_id=cluster_id, )
def cli(ctx: click.core.Context, json: bool, verbose: bool, endpoint: str) -> None: """Nessie cli tool. Interact with Nessie branches and tables via the command line """ try: config = build_config({"endpoint": endpoint} if endpoint else None) nessie = NessieClient(config) ctx.obj = ContextObject(nessie, verbose, json) except confuse.exceptions.ConfigTypeError as e: raise click.ClickException(str(e))
def drclip(ctx: click.core.Context, config: TextIOWrapper, registry: str): """Runs commands against docker registries""" ctx.obj = CmdContext(RegistryV2API(registry, DockerCredentials(config))) err = None try: ctx.obj.api.head() # Simple version check / connectivity check except CredentialsNotFound: err = f'Error: Credentials for {registry} could not be located (you may need to run docker login ... )' except CredentialsException as e: err = e if err: click.echo(err, err=True) sys.exit(1)
def convert(ctx: click.core.Context, tar_file: str, script_path: str, file: str, merge: bool, debug: bool): """ 指定されたtarファイルを展開し、変換ルールに従って変換します。 """ if debug: log.set_level(log.Level.DEBUG) if not script_path is None: s = script_path else: conf = __get_params(ctx) if (conf.convert_rule is not None) and (not os.path.exists(conf.convert_rule)): click.echo("convert_rule \"%s\" が存在しません。" % conf.convert_rule) ctx.exit(2) else: s = conf.convert_rule p = conv.ConvertParams() p.script_path = s p.log_path = tar_file p.file = file ret = None try: ret, out_dir = conv.Converter(p).exec() if merge and not (out_dir is None): ret = mrg.Merge().exec(os.path.join(out_dir, conf.merge_dir)) except IOError as e: click.echo(e.args) except Exception as e: click.echo(e.args) # finished if ret: click.echo("正常に終了しました。") else: click.echo("失敗しました。")
def upload_file( ctx: click.core.Context, upload_file: str, folder_name: str, description: str, access_level: str, reuse_newest_upload: bool, summary: bool, ): """The foss_cli upload_file command.""" logger.debug(f"Try to upload file {upload_file}") foss = ctx.obj["FOSS"] # check/set the requested access level the_access_level = check_get_access_level(access_level) # check/set the requested folder folder_to_use = check_get_folder(ctx, folder_name) if reuse_newest_upload: the_upload = get_newest_upload_of_file(ctx, upload_file, folder_name) else: the_upload = None if the_upload is None: the_upload = foss.upload_file( folder_to_use, file=upload_file, description=description if description else "upload via foss-cli", access_level=the_access_level, ) ctx.obj["UPLOAD"] = the_upload if summary: summary = foss.upload_summary(the_upload) if ctx.obj["DEBUG"]: logger.debug( f"Summary of upload {summary.uploadName} ({summary.id})" f"Main license: {summary.mainLicense}" f"Unique licenses: {summary.uniqueLicenses}" f"Total licenses: {summary.totalLicenses}" f"Unique concluded licenses: {summary.uniqueConcludedLicenses}" f"Total concluded licenses: {summary.totalConcludedLicenses}" f"Files to be cleared: {summary.filesToBeCleared}" f"Files cleared: {summary.filesCleared}" f"Clearing status: {summary.clearingStatus}" f"Copyright count: {summary.copyrightCount}" f"Additional info: {summary.additional_info}")
def main( ctx: click.core.Context, username: str, password: str, token: str, locale: str, stdin_password: bool, ) -> None: if not (password or stdin_password): raise click.UsageError("Must supply one of `password` or `stdin_password`") if stdin_password: password = input() ctx.obj = CrunchyrollApi(username, password, token)
def destroy_list( ctx: click.core.Context, cluster_ids: List[str], transport: Transport, ) -> None: """ Destroy clusters. To destroy all clusters, run ``minidcos docker destroy $(minidcos docker list)``. """ for cluster_id in cluster_ids: if cluster_id not in existing_cluster_ids(): warning = 'Cluster "{cluster_id}" does not exist'.format( cluster_id=cluster_id, ) click.echo(warning, err=True) continue ctx.invoke( destroy, cluster_id=cluster_id, transport=transport, )
def cli( ctx: click.core.Context, host: str, username: str, password: str, device_type: str, ) -> None: """Interact with the device API.""" api_generator: Callable[[str, str, str], Union[GogoGate2Api, ISmartGateApi]] if device_type == DeviceType.GOGOGATE2.value: api_generator = GogoGate2Api else: api_generator = ISmartGateApi if password == "-": # nosec password = default_password() ctx.obj = {API: api_generator(host, username, password)}
def cli( ctx: click.core.Context, debug: bool, verbose: bool, url: str, username: str, password: str, print_headers: bool, ) -> None: log_level = Context.LOG_WARNING if debug: log_level = Context.LOG_DEBUG elif verbose: log_level = Context.LOG_INFO ctx.obj = Context(url, username, password, log_level, print_headers)
def cli(ctx: click.core.Context) -> None: """ Mackerel is a minimal static site generator written in typed Python 3.6+. """ ctx.obj = {}