def sversion(self, odoo_series: OdooSeries) -> str: if not self.addon: return typer.style("✘ not installed", fg=typer.colors.RED) elif is_core_ce_addon(self.addon_name, odoo_series): return f"{odoo_series}+{OdooEdition.CE}" elif is_core_ee_addon(self.addon_name, odoo_series): return f"{odoo_series}+{OdooEdition.EE}" else: return self.addon.manifest.version or "no version"
def start(task: str = typer.Option("Task", autocompletion=complete_task_name)) -> None: task_sql = search_task_or_fail(task) event_repository.stop() event_repository.start(task_sql.id) task_str = typer.style(task_sql.name, fg=typer.colors.YELLOW) typer.echo(f"Task {task_str} started!")
def print_info_for_string(self, only_interesting: bool = False, show_offset_in_file: bool = False): parts_for_echo = [] if only_interesting and not self.type_: return if show_offset_in_file: parts_for_echo.append(str(self.offset_in_file)) parts_for_echo.append(typer.style(self.value, fg=self.color)) if self.hint: parts_for_echo.append(typer.style(self.hint, fg=typer.colors.GREEN)) typer.echo(f"{' '.join(parts_for_echo)}")
def get_articles(self, ids_list: List[str]) -> List[Generator]: """Synopsis: Process each S2ORC pdf archive and extract entries of interest based on paper_ids fetched from S2ORC metadata Input: List of paper_ids (S2ORC ids) Output: List of generators which contain S2ORC pdf entries""" typer.secho('Extracting pdf entries from S2ORC', bold=True) first = typer.style('Number of s2orc ids to search for ', bold=True) second = typer.style(f"{len(ids_list)}", blink=True, fg=typer.colors.GREEN, bold=True) typer.echo(first + second) interests = [ self._open_s2rc(str(archive), ids_list) for archive in self.archive_paths ] return interests
def cli_save_output(output_info: Union[str, BytesIO], output_file: Path): if isinstance(output_info, str): typer.echo( typer.style(f"Save output as: {output_file.as_posix()}", fg=typer.colors.CYAN)) raise typer.Exit(code=0) else: typer.echo(f"Failed to generate output: {output_file.as_posix()}") raise typer.Exit(code=1)
def confirm_overwrite(procedure_name) -> bool: """Prompt y/n when user is attempting to create a Procedure with the same name as an existing one""" existence_warning = typer.style( glot.localized("overwrite_warn", {"name": procedure_name}), **WARNING_STYLE) return typer.confirm(existence_warning, abort=True)
def copyApp(tag, path): (exitcode, stdout, stderr) = execute( ['docker', 'cp', path, tag+':/root/app']) if stderr: stderr = typer.style(stderr.decode('ascii'), fg=typer.colors.RED) typer.echo('Failed to copy app:') typer.echo(f' tag: {tag}') typer.echo(f' stderr:\n{stderr}') exit(1)
def multiline_input_prompt(message): """Uses typer and ARgorithmToolkit.parser.multiline to create a multiline input prompt. Args: message (str): The text for prompt Returns: ip: data entered by user """ text = typer.style(message + ':', fg=typer.colors.WHITE) helptext = typer.style( "Press ENTER on empty line to leave multiline input", fg=typer.colors.CYAN) typer.echo(text) typer.echo(helptext) ip = multiline() return ip
def cli_push(folder_struct_list, upload_file_name, upload_file_abs_path): """ Replace (Remote)ipynb in google colab with local ipynb :param folder_struct_list: :param upload_file_name: :param upload_file_abs_path: """ AUTH_USER_ID = check_all_config() total = 100 with typer.progressbar(length=total) as progress: drive = drive_auth() progress.update(15) COLAB_NB_FOLD_ID = get_colab_folder_id(drive) progress.update(30) final_folder_id = fold_struct_gen(drive, COLAB_NB_FOLD_ID, folder_struct_list) progress.update(45) delete_folder(drive, upload_file_name, final_folder_id) progress.update(60) new_file_metadata = get_file_meta(upload_file_name, final_folder_id) new_file_id = create_new_file(drive, new_file_metadata, upload_file_abs_path, upload_file_name, final_folder_id) # print(f"new colab file id is {new_file_id}") colab_url = f'https://colab.research.google.com/drive/{new_file_id}?authuser={AUTH_USER_ID}' drive_folder_url = f'https://drive.google.com/drive/u/{AUTH_USER_ID}/folders/{final_folder_id}' progress.update(90) webbrowser.open(url=colab_url) progress.update(100) message = f"\n {upload_file_name} in google drive updated with the local file" message = typer.style(message, fg=typer.colors.GREEN, bold=True) typer.echo(message) message = f"\n drive folder url: {drive_folder_url}" message = typer.style(message, fg=typer.colors.CYAN, bold=True) typer.echo(message) message = f"\n colab file url: {colab_url}" message = typer.style(message, fg=typer.colors.BRIGHT_CYAN, bold=True) typer.echo(message)
def eval_caas_response(resp) -> None: if not resp.ok: typer.echo(f"[{resp.status_code}] {resp.error} \n{resp.output}") return else: resp = resp.output lines = "-" * 22 typer.echo("") typer.echo(lines) if resp.get("_global_result", {}).get("status", '') == 0: typer.echo( f"Global Result: {typer.style('Success', fg='bright_green')}") else: typer.echo(f"Global Result: {typer.style('Failure', fg='red')}") typer.echo(lines) _bypass = None if resp.get("cli_cmds_result"): typer.secho("\n -- Command Results --", fg="cyan") for cmd_resp in resp["cli_cmds_result"]: for _c, _r in cmd_resp.items(): _r_code = _r.get("status") if _r_code == 0: _r_pretty = typer.style("OK", fg="bright_green") elif _r_code == 2: _r_pretty = typer.style("WARNING", fg="bright_red") else: _r_pretty = typer.style(f"ERROR {_r_code}", fg="red") _r_txt = _r.get("status_str") typer.echo(f" [{_bypass or _r_pretty}] {_c}") if _r_txt: typer.echo(f"{lines}\n{_r_txt}\n{lines}") # if _r_code not in [0, 2]: # _bypass = "******" # if _r_txt: # typer.echo(f"\n{lines}{_r_txt}\n{lines}\n") # typer.echo("-" * 65) # typer.echo("!! Remaining Commands bypassed due to Error in previous object !!") # typer.echo("-" * 65) # elif _r_txt and not _bypass: # typer.echo(f"\t{_r_txt}") typer.echo("")
def main( name_of_problem: str = typer.Argument(...), path_to_dataset: Path = typer.Option(None, "--dataset", "-d", help="Path to dataset."), test: bool = typer.Option(False, "--test", "-t", help="Test the soultion."), ): try: problem = solutions[name_of_problem] except KeyError: typer.echo( typer.style( f"The problem '{name_of_problem}' is not defined, you may have a typo.", fg=typer.colors.WHITE, bg=typer.colors.RED, )) raise typer.Abort() if path_to_dataset: with open(path_to_dataset) as f: dataset_lines = f.readlines() return typer.echo(problem.solution(dataset_lines)) output = problem.solution(problem.SAMPLE_DATASET.splitlines(True)) if test: try: problem.test_solution() return typer.echo( typer.style("The solution is correct!", fg=typer.colors.GREEN, bold=True)) except AssertionError: typer.echo( typer.style("The soultion is not correct!", fg=typer.colors.RED, bold=True)) typer.echo("Correct output:") typer.echo(problem.SAMPLE_OUTPUT) typer.echo("Current output:") return typer.echo(output) return typer.echo(output)
def write_superposed_pdbs(self, output_pdb_folder, alignments: dict = None, verbose: bool = False): """ Superposes PDBs according to alignment and writes transformed PDBs to files (View with Pymol) Parameters ---------- output_pdb_folder alignments verbose """ if alignments is None: alignments = self.alignment output_pdb_folder = Path(output_pdb_folder) if not output_pdb_folder.exists(): output_pdb_folder.mkdir() reference_name = self.structures[self.reference_structure_index].name core_indices = np.array([ i for i in range(len(alignments[reference_name])) if -1 not in [alignments[n][i] for n in alignments] ]) if verbose: typer.echo( f"{len(core_indices)} core positions in alignment of length {len(alignments[reference_name])}" ) if len(core_indices) < len(alignments[reference_name]) // 2: if verbose: typer.echo( typer.style( "Core indices are < half of alignment length, superposing using reference structure " "instead", fg=typer.colors.RED, )) typer.echo( typer.style( "Please inspect the distance matrix to split divergent protein groups", fg=typer.colors.RED, )) self.write_superposed_pdbs_reference(output_pdb_folder, alignments) else: self.write_superposed_pdbs_core(output_pdb_folder, alignments)
def archive( path: str = typer.Option(None, "--path", "-f", help="Path to config yml"), output_format: str = typer.Option( "pgdump", "--output-format", "-o", help="csv, geojson, shapefile, pgdump and postgres"), push: bool = typer.Option(False, "--s3", "-s", help="Push to s3"), clean: bool = typer.Option(False, "--clean", "-c", help="Remove temporary files"), latest: bool = typer.Option(False, "--latest", "-l", help="Tag with latest"), name: str = typer.Option( None, "--name", "-n", help="Name of the dataset, if supplied, \"path\" will ignored"), compress: bool = typer.Option(False, "--compress", help="Compress output"), inplace: bool = typer.Option(False, "--inplace", help="Only keeping zipped file"), postgres_url: str = typer.Option(None, "--postgres-url", help="Postgres connection url"), version: str = typer.Option(None, "--version", "-v", help="Custom version input"), ) -> None: # fmt: on """ Archive a dataset from source to destination """ if not name and not path: message = typer.style( "\nPlease specify dataset NAME or PATH to configuration\n", fg=typer.colors.RED) typer.echo(message) else: a = Archive() a( path=path, output_format=output_format, push=push, clean=clean, latest=latest, name=name, compress=compress, inplace=inplace, postgres_url=postgres_url, version=version, )
def wrapper(*args, **kwargs): try: func(*args, **kwargs) except KurbyError as e: typer.echo("Error " + typer.style(e.code, fg=typer.colors.RED, bold=True) + f": {e.message}") if DEBUG: raise e raise typer.Exit(1)
def match_recent_tweets(n: int = 100): bot_name_s = typer.style( f"@{config.twitter.BOT_NAME}", fg=typer.colors.BRIGHT_YELLOW ) typer.echo(f"Collecting recent tweets from {bot_name_s}") # load songs lyrics_dir = data_dir / "lyrics" band_dir = lyrics_dir / config.lyrics.BAND_NAME songs_path = band_dir / "all-songs.yml" with songs_path.open("r") as fh: songs = [ pt.Song(**song) for song in yaml.load(fh.read(), Loader=yaml.FullLoader) ] tweets = twitter.api.user_timeline( screen_name=config.twitter.BOT_NAME, count=n, include_rts=False, tweet_mode="extended", ) matches, unknowns = [], [] for tweet in tweets: tweet_lines = tweet.full_text.splitlines() lyrics = typer.style( " / ".join(tweet_lines), fg=typer.colors.BRIGHT_MAGENTA ) matched_songs = search.find_songs_from_lyrics(tweet_lines, songs) if matched_songs: matches.append(lyrics) else: unknowns.append(lyrics) match_frac = len(matches) / len(tweets) typer.echo( f"""Matching {typer.style(f"{match_frac*100:.2f}")}% of tweets""" ) for tweet in unknowns: typer.echo(f"Unknown lyric: {tweet}")
def print_message(message: str, color: str, bold: bool, should_exit: bool, code: int): """ Print formatted message and exit if requested. """ typer.echo(typer.style(message, fg=color, bold=bold)) if should_exit: sys.exit(code)
def host_status(self, verbose): """Creates and formats message for node status.""" if self.status == "online": vm_status = typer.style(self.status, fg=typer.colors.GREEN, bold=True) else: vm_status = typer.style(self.status, fg=typer.colors.RED, bold=True) message = self.node + ": " + vm_status if verbose: maxmem = round(self.maxmem / 1000000000, 2) # turns this into gigabytes usedmem = percent_used(self.maxmem, self.mem) mem = ", available RAM: " + str( maxmem) + "GiB used RAM: " + usedmem message += mem return message
def see(): """ See list of all projects that are added """ current_config = JsonDataOperations.read() if len(current_config['projects']) == 0: typer.echo('Seems like you have not added any project yet!!!') command = typer.style("copen add", bg=typer.colors.BRIGHT_WHITE, fg=typer.colors.BLACK) typer.echo('Use ' + command + ' to add new project') raise typer.Exit() col = typer.style("Project Name", fg=typer.colors.CYAN, bold=True) typer.echo(col) typer.echo("=======================") for project_item in current_config['projects']: typer.echo(project_item['project_name']) typer.echo("=======================")
def get_git_root(path): try: git_repo = Repo(path, search_parent_directories=True) return git_repo.working_tree_dir except InvalidGitRepositoryError as no_repo_error: message = f"no git repo initialized : please make sure you have initialized a git repo \n" message = typer.style(message, fg=typer.colors.BRIGHT_RED, bold=True) typer.echo(message) raise typer.Exit()
def wlan( group: str = typer.Argument(..., metavar="[GROUP NAME|SWARM ID]", autocompletion=cli.cache.group_completion), name: str = typer.Argument(..., metavar="[WLAN NAME]", autocompletion=lambda incomplete: tuple(["<WLAN NAME>"])), 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)",), ) -> None: yes = yes_ if yes_ else yes group = cli.cache.get_group_identifier(group) confirm_1 = typer.style("Please Confirm:", fg="cyan") confirm_2 = typer.style("Delete", fg="bright_red") confirm_3 = typer.style(f"Group {group.name}, WLAN {name}", fg="cyan") if yes or typer.confirm(f"{confirm_1} {confirm_2} {confirm_3}", abort=True): resp = cli.central.request(cli.central.delete_wlan, group.name, name) cli.display_results(resp, tablefmt="action")
def read_notif(read: str): today = date.today() message = "\n------------------------------------------------\n\n" unread_notification = user.get_notifications( before=datetime(today.year, today.month, today.day)) if read == "A": for notif in unread_notification: notif.mark_as_read() message += typer.style("Marked as Read. \n", fg=typer.colors.BRIGHT_CYAN) message += "\n------------------------------------------------\n\n" typer.echo(f"{message}") else: for notif in unread_notification[:int(read)]: notif.mark_as_read() message += typer.style("Marked as Read. \n", fg=typer.colors.BRIGHT_CYAN) message += "\n------------------------------------------------\n\n" typer.echo(f"{message}")
def print_results(links: dict): """Simple utility function to print to terminal""" num_of_failed_links = 0 for k, v in links.items(): if k == 200: for link in v: typer.echo(typer.style(f"[ {k} ] - {link}", fg="green")) elif k == 500: for link in v: typer.echo(typer.style(f"[ {k} ] - {link}", fg="red")) num_of_failed_links += 1 else: for link in v: typer.echo(typer.style(f"[ {k} ] - {link}", fg="yellow")) num_of_failed_links += 1 typer.echo("========================") typer.echo(f"TOTAL LINKS CHECKED: {len(links[200]) + num_of_failed_links}") typer.echo(f"FAILED: {num_of_failed_links}")
def db_backup( db_name: str = typer.Argument( ..., help="Name of db you want to backup "+ " # NOTE: if you want to make cron for this script ,"+ " you sould comment typer confirm lines" ) ): mycursor.execute( "SHOW DATABASES LIKE %s", (db_name,) ) db_check = mycursor.fetchone() # print(db_check) if db_check: backup = typer.confirm( "Are you sure you want to backup "+db_name+" ?", abort=True ) # print(backup) db_cont = config("DB_HOST") if backup == True: backup_file = './db_backup/'+db_name+date.strftime("%x").replace("/", "_") # print(backup_file) typer.echo("backup file : "+ backup_file) cmd = 'docker exec -it '+db_cont+' "mysqldump -u {0} -p {1} > {2}"'.format(config("DB_USER"),\ config("DB_NAME"),backup_file,) make_file = "touch "+backup_file os.system(make_file) os.system(cmd) ending = typer.style( "Getting backup from "+db_name, fg=typer.colors.BRIGHT_YELLOW , bold=True ) typer.echo(ending) else: raise ValueError( typer.style( "Database "+db_name+" is not existed! check you database name", fg=typer.colors.RED, bold=True ) )
def item_prompt(resources: Iterable[T], jmespath_msg: str = None) -> T: """Prompt's the user for an item to select from the items passed. Item is expected to support the Item protocol.""" resources = cast(ResourceCollection, resources) items = list(resources.all()) if not resources or len(items) == 0: raise UserWarning( f'no items found when calling {resources._py_operation_name}') elif len(items) == 1: # No need to make a selection if there's only one option return list(items)[0] msg = '' for i, item in enumerate(items): if jmespath_msg: # dump and load json to convert datetime and similar to something readable data = json.loads(json.dumps(item.meta.data, default=str)) msg = ', '.join(jmespath.search(jmespath_msg, data=data or '')) name = get_name_tag(item.tags) secho("{}".format(i), bold=True, nl=False, fg=colors.GREEN) if name: secho(") {} Name: {} ({})".format( style(item.id, underline=True, bold=True), style(name, bold=True), msg)) else: secho(") {} ({})".format(style(item.id, bold=True), msg)) answer = int( input( style(f'Select {list(items)[0].meta.resource_model.name}:', underline=True) + ' ')) try: return list(items)[answer] except IndexError: secho( f"Invalid selection, valid inputs are 0 through {len(items) - 1}", file=sys.stderr, fg=colors.RED) return item_prompt(resources)
def serialize_parser_and_lexer(): import typer t = time.time() G.serialize_lexer('CoolLexer', inspect.getmodulename(__file__)) G.serialize_parser('lalr1', 'CoolParser', inspect.getmodulename(__file__)) styled_e = typer.style(f'Serialization Time : {time.time() - t} seconds', fg=typer.colors.GREEN, bold=True) typer.echo(styled_e)
def _do_subtables(data: list, tablefmt: str = "rich"): out = [] for inner_dict in data: # the object: switch/vlan etc dict for key, val in inner_dict.items(): if not isinstance(val, (list, dict, tuple)): if val is None: inner_dict[key] = '' elif isinstance(val, str) and val.lower() in ['up', 'down']: color = 'red' if val.lower() == 'down' else 'green' if tablefmt == 'rich': inner_dict[ key] = f'[b {color}]{val.title()}[/b {color}]' else: inner_dict[key] = typer.style(val.title(), fg=color) else: if tablefmt == 'rich': inner_dict[key] = Text(str(val), style=None) else: inner_dict[key] = str(val) else: val = self.listify(val) if val and tablefmt == "rich" and hasattr( val[0], 'keys'): inner_table = Table( *(k for k in val[0].keys()), show_header=True, # padding=(0, 0), pad_edge=False, collapse_padding=True, show_edge=False, header_style="bold cyan", box=SIMPLE) _ = [ inner_table.add_row(*[ self.do_pretty(kk, str(vv)) for kk, vv in v.items() ]) for v in val ] with console.capture(): console.print(inner_table) inner_dict[key] = console.export_text() elif val and tablefmt == "tabulate" and hasattr( val[0], 'keys'): inner_table = tabulate(val, headers="keys", tablefmt=tablefmt) inner_dict[key] = inner_table else: if all(isinstance(v, str) for v in val): inner_dict[key] = ", ".join(val) out.append(inner_dict) return out
def select_idx_from_list(seq: Sequence[T], noun: str = None) -> int: """Present a list of choices, and return the index of the selected choice.""" if noun is None: noun = str(type(seq[0]).__name__.lower()) typer.echo(f"Select a {noun} from the list below:") choices: List[str] = [] for idx, stop in enumerate(seq): choices.append(f"{idx}") idx_str = typer.style(f"{idx}.", bold=True) typer.echo(f"{idx_str} {stop}") return int(typer.prompt("", type=click.Choice(choices)))
def confirm_overwrite(task_spec_name) -> bool: """Prompt y/n when user is attempting to create a Task Spec with the same name as an existing one""" existence_warning = typer.style( f"🤔 Task Spec '{task_spec_name}' appears to exist already\n" "Would you like to overwrite it?", fg=typer.colors.YELLOW, ) return typer.confirm(existence_warning, abort=True)
def site( sites: List[str] = typer.Argument( ..., help="Site(s) to delete (can provide more than one).", autocompletion=cli.cache.site_completion, ), 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)",), ) -> None: yes = yes_ if yes_ else yes sites = [cli.cache.get_site_identifier(s) for s in sites] _del_msg = [ f" {typer.style(s.name, fg='reset')}" for s in sites ] if len(_del_msg) > 7: _del_msg = [*_del_msg[0:3], " ...", *_del_msg[-3:]] _del_msg = "\n".join(_del_msg) confirm_1 = typer.style("About to", fg="cyan") confirm_2 = typer.style("Delete:", fg="bright_red") confirm_3 = f'{typer.style(f"Confirm", fg="cyan")} {typer.style(f"delete", fg="red")}' confirm_3 = f'{confirm_3} {typer.style(f"{len(sites)} sites?", fg="cyan")}' _msg = f"{confirm_1} {confirm_2}\n{_del_msg}\n{confirm_3}" if yes or typer.confirm(_msg, abort=True): del_list = [s.id for s in sites] resp = cli.central.request(cli.central.delete_site, del_list) cli.display_results(resp, tablefmt="action") if resp: cache_del_res = asyncio.run(cli.cache.update_site_db(data=del_list, remove=True)) if len(cache_del_res) != len(del_list): log.warning( f"Attempt to delete entries from Site Cache returned {len(cache_del_res)} " f"but we tried to delete {len(del_list)}", show=True )
def _display_results( data: Union[List[dict], List[str], None] = None, tablefmt: str = "rich", title: str = None, caption: str = None, pager: bool = True, outfile: Path = None, sort_by: str = None, reverse: bool = False, pad: int = None, cleaner: callable = None, **cleaner_kwargs, ): if data: data = utils.listify(data) if cleaner: data = cleaner(data, **cleaner_kwargs) if sort_by and all(isinstance(d, dict) for d in data): if not all([True if sort_by in d else False for d in data]): typer.echo(f"Invalid dataset for {sort_by} not all entries contain a {sort_by} key") typer.secho("sort by is not implemented for all commands yet", fg="red") else: data = sorted(data, key=lambda d: d[sort_by]) if reverse: data = data[::-1] outdata = utils.output( data, tablefmt, title=title, caption=caption, account=None if config.account in ["central_info", "account"] else config.account, config=config, ) typer.echo_via_pager(outdata) if pager and tty and len(outdata) > tty.rows else typer.echo(outdata) # -- // Output to file \\ -- if outfile and outdata: if Path().cwd() != Path.joinpath(config.outdir / outfile): if Path.joinpath(outfile.parent.resolve() / ".git").is_dir(): typer.secho( "It looks like you are in the root of a git repo dir.\n" "Exporting to out subdir." ) config.outdir.mkdir(exist_ok=True) outfile = config.outdir / outfile print(typer.style(f"\nWriting output to {outfile}... ", fg="cyan"), end="") outfile.write_text(outdata.file) # typer.unstyle(outdata) also works typer.secho("Done", fg="green")