def sdl( file: str, output: str = typer.Option(None, help="save output into a file."), ) -> None: """Generate SDL aka GraphQL schema from ADFH file. Args: file: Path to ADFH file. output: If --output is used, it will save it in file. """ console = Console() data = read_adfh_file(file=file) if type(data) == str: console.print(data, style="bold red") else: ihsan_type = IhsanType(**data) # type: ignore sdl_output = to_sdl(schema=ihsan_type) if output: typer.confirm( f"The output will be saved in {output}, are you sure?", abort=True) with open(output, "w") as output_file: output_file.write(sdl_output) else: console.print(sdl_output, style="bold green") console.print( "Use -> https://app.graphqleditor.com/ to test the schema :)", style="bold blue", )
def main(extension: str, directory: Optional[str] = typer.Argument( None, help="Dossier dans lequel chercher."), delete: bool = typer.Option(False, help="Supprime les fichiers trouvés.")): """ Affiche les fichiers trouvés avec l'extension donnée. """ if directory: directory = Path(directory) else: directory = Path.cwd() if not directory.exists(): typer.secho(f"Le dossier '{directory}' n'existe pas.", fg=typer.colors.RED) raise typer.Exit() files = directory.rglob(f"*.{extension}") if delete: typer.confirm( "Voulez-vous vraiment supprimer tous les fichiers trouvés ?", abort=True) for file in files: file.unlink() typer.secho(f"Suppression du fichier {file}.", fg=typer.colors.RED) else: typer.secho(f"Fichier trouvés l'extension {extension} :", bg=typer.colors.BLUE, fg=typer.colors.BRIGHT_WHITE) for file in files: typer.echo(file)
def json( file: str, output: str = typer.Option(None, help="save output into a file."), ) -> None: """Generate json from ADFH file. Args: file: Path to ADFH file. output: If --output is used, it will save it in file. """ console = Console() data = read_adfh_file(file=file) if type(data) == str: console.print(data, style="bold red") else: ihsan_type = IhsanType(**data) # type: ignore if output: typer.confirm( f"The output will be saved in {output}, are you sure?", abort=True) with open(output, "w") as output_file: output_file.write(ihsan_type.json()) else: console.print(ihsan_type.json(), style="bold green")
def main( project_name: str, routers: str = typer.Option( default='', help='Router names to create, write every router name with spaces'), models: str = typer.Option( default='', help='Model names to create, write every router name with spaces')): typer.confirm( f'Project name: {project_name} \n routers: {routers} \n models: {models}', default=True, abort=True) # Create the base directory os.mkdir(project_name) # Create high level main file create_base_main(project_name) # Create the app package os.mkdir(f'{project_name}/app') open(f'{project_name}/app/__init__.py', 'w').close() # If there are model classes to create then create these classes as well if models != '': create_models(project_name, models.split()) # If there are routers to create then create these as well if routers != '': create_routers(project_name, routers.split()) # Create the base fastapi main file. FastAPI object will be created here create_main(project_name, routers.split()) create_docker_file(project_name)
def createuser(): username = typer.prompt("Username") password = typer.prompt("Password") email = typer.prompt("Email") is_superuser = typer.confirm(f"is {username} super user?") is_staff = typer.confirm(f"is {username} staff user?") is_active = typer.confirm(f"is {username} active user?") run_async( run( data={ "username": username, "password": password, "email": email, "full_name": " ", "is_superuser": is_superuser, "is_staff": is_staff, "is_active": is_active, "phone_number": "0923275406", } ) )
def out( when: str = Option(None, help="Set a specific time to clock out"), id: str = Option(None, help="The id of the clok instance to clok out of."), m: str = Option(None, help="Journal Message to add to record"), ): """Clock out from a job""" if when: when = parse_date_and_time(when) if id is not None and when is not None: clok = Clok.clok_out_by_id(id, when, verbose=True) else: clok = Clok.get_last_record() if (datetime.now() - clok.time_in).total_seconds() / (60 * 60) > 12: typer.confirm( "The last clocked in time is more than 12 hours ago, are you\n" "are you sure you want to clok out now?") if when is not None: clok = Clok.clock_out_when(when, verbose=True) else: clok = Clok.clock_out(verbose=True) if m is not None: clok.add_journal(m)
def provision(lang_code: str, ): text = "" for line in fileinput.input("-"): text += line if not text: typer.echo(rtext("No any input data")) return streams_data = ChannelStream.parse_raw(text) _login() device = api.get_or_create_device(lang_code) if not streams_data: typer.echo(rtext("No input data")) return if device.outputs: typer.confirm("Are you sure you want to continue?", abort=True) for stream in streams_data: device.create_output( name=stream.channel_name, server_url=stream.server_url, shared_key=stream.stream_key, ) typer.echo(gtext(f"Added {stream}"))
def init( username=typer.Option(None, prompt=True), api_key=typer.Option(None, prompt=True), archive_path=typer.Option( default_archive_dir, prompt=True, help="(absolute) path to directory to store archive json files", ), earliest_year=typer.Option( default=2010, help="the earliest year to start fetching scrobbles from"), ): """ Initialize the archiver with a lastfm username, api key, and a path to put archive json files. Also optionally specify the earliest year to look back (default 2010) """ typer.echo("Initializing the archiver...") if SETTINGS_KEY in current_config: typer.confirm( f"Are you sure you want to overwrite existing configuration at {str(config_path)}?", abort=True) new_config = configparser.ConfigParser() new_config[SETTINGS_KEY] = { "username": username, "api_key": api_key, "archive_path": archive_path, "earliest_year": earliest_year, } with open(config_path, mode="w") as f: new_config.write(f) typer.echo( typer.style(f"Config file written to {str(config_path)}", fg=typer.colors.GREEN))
def init_endpoint(): """Setup funcx dirs and default endpoint config files TODO : Every mechanism that will update the config file, must be using a locking mechanism, ideally something like fcntl https://docs.python.org/3/library/fcntl.html to ensure that multiple endpoint invocations do not mangle the funcx config files or the lockfile module. """ _ = FuncXClient() if os.path.exists(State.FUNCX_CONFIG_FILE): typer.confirm( "Are you sure you want to initialize this directory? " f"This will erase everything in {State.FUNCX_DIR}", abort=True ) logger.info("Wiping all current configs in {}".format(State.FUNCX_DIR)) backup_dir = State.FUNCX_DIR + ".bak" try: logger.debug(f"Removing old backups in {backup_dir}") shutil.rmtree(backup_dir) except OSError: pass os.renames(State.FUNCX_DIR, backup_dir) if os.path.exists(State.FUNCX_CONFIG_FILE): logger.debug("Config file exists at {}".format(State.FUNCX_CONFIG_FILE)) return try: os.makedirs(State.FUNCX_DIR, exist_ok=True) except Exception as e: print("[FuncX] Caught exception during registration {}".format(e)) shutil.copyfile(State.FUNCX_DEFAULT_CONFIG_TEMPLATE, State.FUNCX_CONFIG_FILE) init_endpoint_dir("default")
def add( # ctx: typer.Context, url_data: List[str] = typer.Argument(..., help="URL and tags"), title: str = typer.Option(None, "--title"), desc: str = typer.Option("", "-d", "--desc"), edit: bool = typer.Option(False, "-e", "--edit", help="open in editor"), verbose: bool = typer.Option(False, "-v", "--verbose"), nofetch: bool = typer.Option(False, "-f", "--nofetch", help="do not try to fetch metadata from web"), ): """ Adds booksmarks to database and FTS index. Provide URL (required) and tags (optional) as parameters. Example: twbm add https://www.google.com tag1, tag2 --title "<title>" """ if verbose: typer.echo(f"Using DB: {config.twbm_db_url}", err=True) url = url_data[0].strip().strip(",") tags = clean_tags(url_data[1:]) if len(unknown_tags := check_tags(tags)) > 0: typer.confirm(f"Create {unknown_tags=} ?", abort=True)
def register(db_path: Path = typer.Option( default="db.sqlite3", file_okay=True, writable=True, readable=True, resolve_path=True, )): """Register a new member in the cohort.""" reader = SimpleMFRC522() session = init_db(db_path) typer.secho("🆕 Registering new members", fg=typer.colors.MAGENTA) try: while True: card_id, user_in_db = scan_card(reader, session) if user_in_db: typer.secho( f"💳 Card {anonymize(card_id)} already registered to\n" f"First Name: {user_in_db.first_name}\n" f"Last Name: {user_in_db.last_name}\n" f"⌚ Registration time: {user_in_db.registration_dt}", fg=typer.colors.RED, ) if typer.confirm("❓ Want to edit the above information?"): first_name, last_name = ask_details() user_in_db.first_name = first_name user_in_db.last_name = last_name user_in_db.registration_dt = datetime.now() session.commit() else: register_new_member(session, card_id) if not typer.confirm("❓ Do you want to register another member?"): break time.sleep(1) finally: GPIO.cleanup()
def delete_template(template_name: str): typer.confirm("Are you sure you want to delete this template?", abort=True) template_list = qs_client.list_templates(AwsAccountId=aws_account_id) matches = [ temp for temp in template_list["TemplateSummaryList"] if temp["Name"] == template_name ] if len(matches) > 1: print(f"\nThere are multiple templates with name {template_name}") print("This function can handle one at most.") return elif len(matches) == 0: print(f"\nThere are no templates with name {template_name}") return template_id = matches[0]["TemplateId"] print(f"\nDeleting template with ID: {template_id}\n") response = qs_client.delete_template( AwsAccountId=aws_account_id, TemplateId=template_id, ) pprint.pp(response)
def main(dataset: Dataset, output_path: Path = typer.Argument('data', help='Output path for dataset'), sample_size: int = typer.Option( 1000, help='Number of samples for each label to generate')): print('Generating %s dataset' % dataset.value) if dataset == Dataset.CYCLIQ: graphs = cycliq(sample_size, is_multi=False) elif dataset == Dataset.CYCLIQ_MULTI: graphs = cycliq(sample_size, is_multi=True) elif dataset == Dataset.TRISQ: graphs = trisq(sample_size) elif dataset == Dataset.HOUSE_CLIQ: graphs = house_cliq(sample_size) elif dataset == Dataset.GRID_CLIQ: graphs = grid_cliq(sample_size) elif dataset == Dataset.HOUSE_GRID: graphs = house_grid(sample_size) if not output_path.exists(): typer.confirm( "Output path %s does not exist, do you want to create it?" % output_path, abort=True) output_path.mkdir() output_path = output_path / dataset.value output_path.mkdir(exist_ok=True) write_gexf(output_path, graphs) write_adjacency(output_path, dataset, graphs)
def delete(name: str): _login() typer.confirm(f"Are you sure to delete `{bctext(name)}`?", abort=True) for n in name.split(" "): status = api.devices.delete_device(n) if status: typer.echo(f"Device {bctext(n)} deleted")
def abort_if_replacement_unwanted(virtual_package_name): typer.confirm( f'A virtual package with the name "{virtual_package_name}" is already installed. ' f"Do you want to replace it?", default=False, err=True, abort=True, )
def rename( what: RenameArgs = typer.Argument(..., ), group_ap: str = typer.Argument( ..., metavar=f"AP{iden.dev}", autocompletion=cli.cache.dev_kwarg_completion), new_name: str = typer.Argument(...), yes: bool = typer.Option(False, "-Y", help="Bypass confirmation prompts - Assume Yes"), yes_: bool = typer.Option(False, "-y", hidden=True), debug: bool = typer.Option( False, "--debug", envvar="ARUBACLI_DEBUG", help="Enable Additional Debug Logging", ), default: bool = typer.Option( False, "-d", is_flag=True, help="Use default central account", show_default=False, ), account: str = typer.Option( "central_info", envvar="ARUBACLI_ACCOUNT", help="The Aruba Central Account to use (must be defined in the config)", autocompletion=cli.cache.account_completion), ) -> None: yes = yes_ if yes_ else yes if what == "group": group_ap = cli.cache.get_group_identifier(group_ap) print( f"Please Confirm: rename group [red]{group_ap.name}[/red] -> [bright_green]{new_name}[/bright_green]" ) if yes or typer.confirm("proceed?", abort=True): resp = cli.central.request(cli.central.update_group_name, group_ap.name, new_name) # XXX Doesn't actually appear to be valid for any group type if not resp and "group already has AOS_10X version set" in resp.output.get( "description", ""): resp.output["description"] = f"{group_ap.name} is an AOS_10X group, " \ "rename only supported on AOS_8X groups. Use clone." cli.display_results(resp, tablefmt="action") elif what == "ap": group_ap = cli.cache.get_dev_identifier(group_ap, dev_type="ap") print( f"Please Confirm: rename ap [red]{group_ap.name}[/red] -> [bright_green]{new_name}[/bright_green]" ) print(" [italic]Will result in 2 API calls[/italic]\n") if yes or typer.confirm("Proceed?", abort=True): resp = cli.central.request(cli.central.update_ap_settings, group_ap.serial, new_name) cli.display_results(resp, tablefmt="action")
def run_setup(): config = {} typer.echo( "Welcome to the setup guide, this will help build your config!\n") typer.echo( "This config will use the existing config you have, and everything " "is saved to ~/.timewriggle/config.toml \n\n") typer.echo("First, we will need some toggl information") toggl = CONFIG["toggl"] if "toggl" in CONFIG else {} toggl["api_token"] = typer.prompt( "What is your toggl API token? " "(Toggle -> Reports -> Profile Settings -> API Token)", type=str, default=toggl.get("api_token")) toggl["workspace"] = typer.prompt("What workspace do you want tracked?", type=str, default=toggl.get("workspace")) config["toggl"] = toggl typer.echo("Now we need some of your google api information") google_api = CONFIG["google_api"] if "google_api" in CONFIG else {} google_api["spreadsheet_id"] = typer.prompt( "What is the Google sheet id to write to? " "(eg: https://docs.google.com/spreadsheets/d/<sheet_id>/edit)", type=str, default=google_api.get("spreadsheet_id")) google_api["credentials_file"] = typer.prompt( "Where is the credentials file?", type=str, default=google_api.get("credentials_file", "creds/credentials.json"), ) google_api["token_file"] = typer.prompt( "Where should the token file be persisted?", type=str, default=google_api.get("token_file", "creds/token.py"), ) google_api["project_sheet"] = typer.prompt( "Where are the project sheets? (the default should work 99% of the time)", type=str, default=google_api.get("project_sheet", "Projects!A4:B"), ) google_api["time_sheet"] = typer.prompt( "Where are the time sheets? (the default should work 99% of the time)", type=str, default=google_api.get("time_sheet", "timesheet!A2:D"), ) google_api["date_format"] = typer.prompt( "What is the date format? Note: this is really important for parsing", type=str, default=google_api.get("date_format", "%Y-%m-%d"), ) config["google_api"] = google_api typer.echo("\nThese are your current settings:") typer.echo(toml.dumps(config)) typer.confirm("Are you happy with these settings?", abort=True) with open(CONFIG_PATH, "w") as file: toml.dump(config, file)
def delete_data_source(data_source_id: str): typer.confirm("Are you sure you want to delete this data source?", abort=True) print(f"\nDeleting data source with ID: {data_source_id}\n") response = qs_client.delete_data_source( AwsAccountId=aws_account_id, DataSourceId=data_source_id, ) pprint.pp(response)
async def run(self, *, poll: bool = True) -> None: self._running = True _set_current_servo(self.servo) await self.servo.startup() self.logger.info( f"Servo started with {len(self.servo.connectors)} active connectors [{self.optimizer.id} @ {self.optimizer.url or self.optimizer.base_url}]" ) async def giveup() -> None: loop = asyncio.get_event_loop() self.logger.critical("retries exhausted, giving up") asyncio.create_task(self.shutdown(loop)) try: @backoff.on_exception( backoff.expo, httpx.HTTPError, max_time=lambda: self.config.settings.backoff.max_time(), max_tries=lambda: self.config.settings.backoff.max_tries(), on_giveup=giveup, ) async def connect() -> None: self.logger.info("Saying HELLO.", end=" ") await self._post_event( servo.api.Events.hello, dict( agent=servo.api.user_agent(), telemetry=self.servo.telemetry.values, ), ) self._connected = True self.logger.info( f"Connecting to Opsani Optimizer @ {self.optimizer.url}..." ) if self.interactive: typer.confirm("Connect to the optimizer?", abort=True) await connect() except typer.Abort: # Rescue abort and notify user servo.logger.warning("Operation aborted. Use Control-C to exit") except asyncio.CancelledError as error: self.logger.trace("task cancelled, aborting servo runner") raise error except: self.logger.exception("exception encountered during connect") if poll: self.run_main_loop() else: self.logger.warning( f"Servo runner initialized with polling disabled -- command loop is not running" )
def delete_endpoint( name: str = typer.Argument(..., autocompletion=complete_endpoint_name), autoconfirm: bool = typer.Option( False, "-y", help="Do not ask for confirmation to delete."), ): """Deletes an endpoint and its config.""" if not autoconfirm: typer.confirm( f"Are you sure you want to delete the endpoint <{name}>?", abort=True) manager.delete_endpoint(name)
def create( path: str = "./", port: Optional[str] = None, tag: Optional[str] = None, ): """ Auto-builds Docker image for chitra ModelServer Args: path: file-location of main.py port: port to expose tag: tag of docker image """ if not port: port = "8080" if not tag: tag = "chitra-server" path = Path(path) files = glob(str(path / "*")) file_check(files) style_path = typer.style(str(path), fg=typer.colors.GREEN) typer.echo(f"Everything under {style_path} will be added to Docker image!") show_files = typer.confirm("Do you wish to see the files to be added?") if show_files: typer.echo(files) dockerfile = get_dockerfile() dockerfile = dockerfile.replace("PORT", port) if typer.confirm("Show Dockerfile"): typer.echo(dockerfile) text_to_file(dockerfile, "Dockerfile") typer.echo(f"Building Docker {tag} 🐳") cmd = f"docker build --tag {tag} ." cmd = shlex.split(cmd) process = subprocess.run(cmd, stdout=subprocess.PIPE, universal_newlines=True) if process.returncode == 0: typer.secho( "Docker image has been created for your app! Check the image using ", nl=False, fg=typer.colors.GREEN, ) typer.secho("docker images", fg=typer.colors.BRIGHT_BLUE) else: typer.secho("Docker build failed!", fg=typer.colors.RED)
async def get_access_token(http_client: httpx.AsyncClient, app_name: str) -> dict: """ use service account to generate access token / generate service account if missing """ service_account_path = (pathlib.Path(typer.get_app_dir(app_name)) / COCOHUB_SERVICE_ACCOUNT) if service_account_path.exists(): with service_account_path.open("r") as f: service_account: CoCoHubServiceAccount = CoCoHubServiceAccount.validate( json.load(f)) else: if typer.confirm( "No service account. do you want to generate one now?"): service_account = generate_service_account(service_account_path) else: raise Exception( "No service account. try again after authenticating at CoCoHub" ) try: http_response = await http_client.post( COCOHUB_TOKEN_URL, auth=(service_account.client_id, service_account.client_secret), headers={"content-length": "0"}, ) http_response.raise_for_status() access_token = http_response.json() return access_token except httpx.exceptions.HTTPError as err: if err.response.status_code == 401: if typer.confirm( "\n Service account expired. do you want to generate a new one now?" ): service_account_path = ( pathlib.Path(typer.get_app_dir(app_name)) / COCOHUB_SERVICE_ACCOUNT) os.remove(service_account_path) service_account = generate_service_account( service_account_path) http_response = await http_client.post( COCOHUB_TOKEN_URL, auth=(service_account.client_id, service_account.client_secret), headers={"content-length": "0"}, ) http_response.raise_for_status() access_token = http_response.json() return access_token else: raise Exception( "No service account. try again after authenticating at CoCoHub" )
def restore(database: str = typer.Argument(..., help='Database name'), do_restore: bool = typer.Option( False, help='Restore database from backup')): if do_restore: typer.confirm( 'Are you sure about recovery? The current data will be changed!', abort=True) typer.echo(f'Process restore {database}') driver = DATABASE_DRIVER[settings.db_type](database) Restore(driver, do_restore=do_restore) typer.echo('That\'s all, folks!')
def delete(id_=Argument(None, help="The id of the time_clock record to delete")): """Delete a record by record ID.""" if id_ is not None: c = Clok.get_by_id(id_) if c is not None: print(clock_row_header()) typer.confirm( f"Are you sure that you want to delete this record? ({id_})?") try: Clok.delete_by_id(id_) except NoResultFound: print(f"Record ({id_}) does not exist")
def clear( root: Optional[Path] = typer.Option(None), force: bool = typer.Option(False, "--force", "-f"), ): """ Clear local KB """ root = Config.get_root(root) if root.exists(): if not force: typer.confirm(f"Clearing {root}. Are you sure?", abort=True) kb = KB(root=root) kb.clear() services.finish("Clear", True)
async def main_loop(self) -> None: # FIXME: We have seen exceptions from using `with self.servo.current()` crossing contexts _set_current_servo(self.servo) while self._running: try: if self.interactive: if not typer.confirm("Poll for next command?"): typer.echo("Sleeping for 1m") await asyncio.sleep(60) continue status = await self.exec_command() if status.status == servo.api.OptimizerStatuses.unexpected_event: self.logger.warning( f"server reported unexpected event: {status.reason}" ) except (httpx.TimeoutException, httpx.HTTPStatusError) as error: self.logger.warning( f"command execution failed HTTP client error: {error}" ) except pydantic.ValidationError as error: self.logger.warning( f"command execution failed with model validation error: {error}" ) self.logger.opt(exception=error).debug( "Pydantic model failed validation" ) except Exception as error: self.logger.exception(f"failed with unrecoverable error: {error}") raise error
def run_query(*args, **kw): try: result = method(*args, **kw) except RefreshError: regen = typer.confirm( "Your credentials has expired, do you want to regenerate them?", default=True, ) if regen is True: auth.get_authenticated() typer.secho( "Authenticated successfully!", fg=typer.colors.BRIGHT_GREEN, bold=True, ), result = method(*args, **kw) else: msg = typer.secho( "Aborting...", bold=True, fg=typer.colors.BRIGHT_RED, ) exit() return result
def setup(): # Copy repo so we can practice pulling. repo_name = os.getcwd() pull_repo_name = repo_name + PULL_SUFFIX if os.path.exists(pull_repo_name): delete = typer.confirm( f"The directory {pull_repo_name} already exists. Do you want to delete it?" ) if not delete: cli.info("Not deleting.") raise typer.Abort() cli.info(f"Deleting {pull_repo_name}.") utils.rmtree_readonly(pull_repo_name) shutil.copytree(repo_name, pull_repo_name) # Setup original repo so we can practice pushing. with open(".gsc_id", "w") as f: f.write("push_and_pull") res = subprocess.run(["git", "add", ".gsc_id"], stdout=PIPE, stderr=PIPE) if res.returncode != 0: raise setup_exercise.SetupError("Failed to add gsc_id. Contact us for help.") res = subprocess.run(["git", "commit", "-m", COMMIT_MSG], stdout=PIPE, stderr=PIPE) if res.returncode != 0: raise setup_exercise.SetupError( "Failed to setup Git Scientist. Contact us for help." )
def resume( src_table: str, src_region: str, src_profile: str, dst_table: str, dst_region: str, dst_profile: str, ) -> bool: src_table_msg = typer.style(src_table, fg=typer.colors.BLUE, bold=True) dst_table_msg = typer.style(dst_table, fg=typer.colors.BLUE, bold=True) dst_region_msg = typer.style(dst_region, fg=typer.colors.BLUE, bold=True) dst_profile_msg = typer.style(dst_profile, fg=typer.colors.BLUE, bold=True) src_region_msg = typer.style(src_region, fg=typer.colors.BLUE, bold=True) src_profile_msg = typer.style(src_profile, fg=typer.colors.BLUE, bold=True) typer.secho("#" * 40, fg=typer.colors.BLUE) typer.echo(f"source table: {src_table_msg}") typer.echo(f"source region: {src_region_msg}") typer.echo(f"source profile: {src_profile_msg}") typer.echo("-" * 40) typer.echo(f"dest table: {dst_table_msg}") typer.echo(f"dest region: {dst_region_msg}") typer.echo(f"dest profile: {dst_profile_msg}") typer.secho("#" * 40, fg=typer.colors.BLUE) return typer.confirm("Configurations are correct?")
def ask_details(): while True: first_name = typer.prompt("❓ What is your first name?") last_name = typer.prompt("❓ What is your last name?") if typer.confirm("❓ Is the information above correct?"): break return first_name, last_name