def createadmin(): admin_exists = db.users.count_documents({'admin': True}) if admin_exists: typer.echo( 'Admin already registered! If you want another admin, ask the admin to give you permissions trough the API' ) return email = typer.prompt('email') password = typer.prompt('password') db.users.insert_one({ 'email': email, 'password': pass_hasher.hash(password), 'admin': True }) typer.echo('Seed admin registered!')
def process_date(dt: Union[str, date, datetime], which_date: str) -> Union[str, int]: """ Process human readable datetime strings, to date objects then to str in %Y-%m-%d fmt. 2 months ago -> datetime.date(2020, 7, 22) -> '2020-07-22' """ try: new_dt = requests.post( url="http://167.99.201.160/parse", data=json.dumps({"human_readable": dt}), headers={ "accept": "application/json", }, ).json()["data"] except KeyError: typer.secho( """There must be a problem with your date or the language is not supported yet.""", bold=True, fg=typer.colors.BRIGHT_RED, ) typer.secho( """Try entering in YYYY-MM-DD format.""", bold=True, fg=typer.colors.BRIGHT_RED, ) enter_new = typer.confirm( f"Do you want to enter a new {which_date} date?", default=True) if enter_new: new_dt = typer.prompt("Enter here") try: new_dt = requests.post( url="http://167.99.201.160/parse", data=json.dumps({"human_readable": new_dt}), headers={ "accept": "application/json", }, ).json()["data"] except KeyError: typer.secho( """There must be a problem with your date or the language is not supported yet 😕,you might want to send a feedback with 'seoman feedback' then we can support your language.""", bold=True, fg=typer.colors.BRIGHT_RED, ) sys.exit() if enter_new is False: typer.secho( "Aborting...", bold=True, fg=typer.colors.BRIGHT_RED, ) sys.exit() return new_dt
def create_user(name: str = typer.Argument( ..., help="Name of user you want to add"), phone: int = typer.Argument( None, help="The phone number of the user [required]")): if phone: if phone >= 9000000000 and phone <= 9999999999: num = "0" + str(phone) mycursor.execute("SELECT * FROM users where phone = %s", (num, )) check_user = mycursor.fetchone() if check_user is None: sql = 'INSERT INTO users (Username, phone) VALUES (%s, %s)' val = (name, num) mycursor.execute(sql, val) mydb.commit() ending = typer.style("User --((" + name + " " + str(phone) + "))-- Added", fg=typer.colors.GREEN, bold=True) typer.echo(ending) else: raise ValueError( typer.style("Phone number existed", fg=typer.colors.RED, bold=True)) else: raise ValueError( typer.style("Invalid phone number", fg=typer.colors.RED, bold=True)) else: num = typer.prompt("Enter your phone number [09xxxxxxxxx]?") if int(num): if re.search("^09.........", num): mycursor.execute("SELECT * FROM users where phone = %s", (num, )) check_user = mycursor.fetchone() if check_user is None: sql = 'INSERT INTO users (Username, phone) VALUES (%s, %s)' val = (name, num) mycursor.execute(sql, val) mydb.commit() ending = typer.style("User --((" + name + " " + str(num) + "))-- Added", fg=typer.colors.GREEN, bold=True) typer.echo(ending) else: raise ValueError( typer.style("Phone number existed", fg=typer.colors.RED, bold=True)) else: raise ValueError( typer.style("Invalid phone number", fg=typer.colors.RED, bold=True))
def build_reciever_integration_key(key): if not key: load_dotenv() key = os.getenv("RECIEVER_INTEGRATION_KEY") if not key: key = typer.prompt( "What's the reciever's integration key? (Blank to match sender)", hide_input=True, ) return key
def create_default_config(): typer.echo( "It looks like this is your first run of the stream saver. The following questions will set up your config" ) typer.echo( "This script requires you to create a twitch developer application. The instructions for doing so are located in the readme" ) typer.echo("Please complete those steps before continuing") confirm = typer.prompt("When you are ready press Y") if confirm.upper() != "Y": typer.secho("Exiting", fg=typer.colors.RED) raise typer.Exit(code=1) config = configparser.ConfigParser() config["STREAM_SAVER"] = {} # Get client ID config["STREAM_SAVER"]["client_id"] = typer.prompt( "What is the client ID from the twitch developer site?") # Get client secret config["STREAM_SAVER"]["client_secret"] = typer.prompt( "What is the client secret from the twitch developer site?") # Get username config["STREAM_SAVER"]["username"] = typer.prompt( "What is your twitch username?") # Get download filepath tmp_download_dir = os.path.join(str(Path.home()), "Downloads", "twitch-downloads") config["STREAM_SAVER"]["download_dir"] = typer.prompt( "Where do you want downloads to go?", default=tmp_download_dir) # Set default download directory and create it if it does not exist if not os.path.exists(config["STREAM_SAVER"]["download_dir"]): os.makedirs(config["STREAM_SAVER"]["download_dir"]) # Write out config file with open(config_path, "w") as configfile: config.write(configfile)
def run_server( host: str = Argument(..., help="Host address to run the server on"), port: int = Argument(..., help="Port where the server should listen to"), token: bool = Option( False, "--token", "-t", help="Prompt for a token for the client server communication", ), log_level: str = Option( "INFO", "--log-level", "-l", help="Minimum level of the logs (DEBUG, INFO, WARNING, ERROR, ...)", ), log_file: Optional[Path] = Option(None, "--log-file", "-f", help="Path to a log file"), init_file: Optional[Path] = Option( None, "--init-file", "-i", help=("Path to a file containing the 'init_task', 'exec_task'" + "and 'exit_task' for the server initialization"), ), ) -> None: """ Start a bgpy server. Run a bgpy server on the given host, which starts listening to the provided port. Note: Before calling the 'initialize()' method of the 'Client' class and passing 'init_task()', exec_task()' and 'exit_task()' to the server, the server will not respond to requests. """ if token: TOKEN = prompt("Token", hide_input=True) token_setenv(TOKEN) if str(log_file) == "None": log_file = None if str(init_file) == "None": init_file = None server = Server( host=host, port=int(port), log_level=log_level, log_file=log_file, init_file=init_file, ) try: server.run() except OSError as e: echo(e) Abort()
def list_all_and_pick_one_restaurant_id(): restaurants = decode_all_restaurants(request_all_restaurants()) for index, restaurant in enumerate(restaurants): typer.echo(f'{index}) {restaurant["name"]} {restaurant["campus"]}') # TODO: Allow users to choose a number range e.g 1-3 or 1,2,3 chosen_restaurant_index = int(typer.prompt("Choose a restaurant [number]")) restaurant_id = restaurants[chosen_restaurant_index]["identifier"] return restaurant_id
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 input_prompt(message, default=None, type=str, show_default=True): """Uses typer to create a single input field in CLI. Args: message (str): The input field text type (type, optional): The type of input default (type, optional): The default value if user does not enter any value show_default (bool, optional): By default, True. If True shows the default value to user Returns: ip : The data entered by user """ text = typer.style(message, fg=typer.colors.WHITE) if default: ip = typer.prompt(text, default=default, type=type, show_default=show_default) else: ip = typer.prompt(text, type=type) return ip
def create( name: str, type: ProjectTypes = typer.Option(None), # private: bool = typer.O version: bool = typer.Option(None, "--version", callback=version_callback), ) -> None: """Bootstrap a project and push to Github""" with typer.progressbar(range(100), label="Processing") as progress: if not name: name = typer.prompt("What is the name of your project?") typer.secho(f"Bootstrapping project: {name}", fg=typer.colors.MAGENTA) Bootstrap(name, progress, type).create()
def find( path: Path = typer.Argument(None), fields: Optional[List[str]] = typer.Option(None, "--f"), write_path: Path = typer.Option(None, "--w"), ): if path.is_file(): if len(fields) == 0: # Raise a message. typer.secho("You have not passed any fields.", fg=typer.colors.BRIGHT_YELLOW) # Get the column names. column_names = helpers.get_column_names(file=path) # Ask the user for selecting fields from the options. selection = typer.prompt( f"Please select fields from the following fields: {column_names}." ) # Match the selected fields with the column names, fields = helpers.match_selected_fields_with_column_names( column_names=column_names, selection=selection) if write_path is not None: if write_path.exists(): typer.secho( f"Writing output to the file {write_path}.", fg=typer.colors.BRIGHT_BLUE, ) else: typer.secho( f"I could not find a path to the file: {write_path}. Therefore, I am creating one for you.", fg=typer.colors.BRIGHT_RED, ) # Write to the given/created file path. helpers.read_or_write( file=path, fields=list(fields), write_to_file=True, write_to_path=write_path, ) else: typer.secho( f"You haven't given me a write path. So I'm just going to print it out for you.", fg=typer.colors.BRIGHT_BLUE, ) # Read the file with the given fields. helpers.read_or_write(file=path, fields=list(fields)) else: typer.Abort("Invalid input.")
def main(): """ Создание супер юзера """ typer.echo("Create superuser") name = typer.prompt("Username") email = typer.prompt("Email") first_name = typer.prompt("First name") password = typer.prompt("Password") super_user = user_s.get_obj(username=name, email=email) if not super_user: user_in = UserCreateInRegistration( username=name, email=email, password=password, first_name=first_name, ) user_s.create_superuser(schema=user_in) mess = typer.style("Success", fg=typer.colors.GREEN) else: mess = typer.style("Error, user existing", fg=typer.colors.RED) typer.echo(mess)
def link( template_git_url: str, project_dir: Path = Path("."), checkout: Optional[str] = None, no_input: bool = True, config_file: Optional[Path] = None, default_config: bool = False, extra_context: Optional[Dict[str, Any]] = None, directory: Optional[str] = None, ) -> bool: """Links an existing project created from a template, to the template it was created from.""" cruft_file = utils.cruft.get_cruft_file(project_dir, exists=False) template_git_url = utils.cookiecutter.resolve_template_url(template_git_url) with AltTemporaryDirectory() as cookiecutter_template_dir_str: cookiecutter_template_dir = Path(cookiecutter_template_dir_str) with utils.cookiecutter.get_cookiecutter_repo( template_git_url, cookiecutter_template_dir, checkout ) as repo: last_commit = repo.head.object.hexsha if directory: cookiecutter_template_dir = cookiecutter_template_dir / directory context = utils.cookiecutter.generate_cookiecutter_context( template_git_url, cookiecutter_template_dir, config_file, default_config, extra_context, no_input, ) if no_input: use_commit = last_commit else: typer.echo( f"Linking against the commit: {last_commit}" f" which corresponds with the git reference: {checkout}" ) typer.echo("Press enter to link against this commit or provide an alternative commit.") use_commit = typer.prompt("Link to template at commit", default=last_commit) cruft_file.write_text( utils.cruft.json_dumps( { "template": template_git_url, "commit": use_commit, "context": context, "directory": directory, } ) ) return True
def get_details(self) -> dict: typer.secho( f"\nThis will generate a {self.filename.name} file in your current working " "directory. \nFill out your name and email to get started.\n", fg=typer.colors.BLUE, ) fields = {} for field in ["name", "email"]: value = typer.prompt(field) if value: fields[field] = value.strip() return fields
def main(): """ Создание супер юзера """ typer.echo("Create superuser") name = typer.prompt("Username") email = typer.prompt("Email") first_name = typer.prompt("First name") password = typer.prompt("Password") super_user = user.get_by_username_email(db_session, username=name, email=email) if not super_user: user_in = UserCreate(username=name, email=email, password=password, first_name=first_name, is_superuser=True, is_active=True) user.create_superuser(db_session, schema=user_in) mess = typer.style("Success", fg=typer.colors.GREEN) else: mess = typer.style("Error, user existing", fg=typer.colors.RED) typer.echo(mess)
def edit(note_id: int = typer.Argument(..., help=EDIT_NOTE_ID_HELP)): """ Edit a note you've taken. """ note = Notes.get_by_id(note_id) if note is not None: typer.secho(note.pretty_str()) update = typer.prompt("New content") note.content = update note.update() typer.secho(f"Note {note_id} updated.") else: typer.secho(f"No note of ID {note_id} found.") raise typer.Abort()
def main(): project = typer.prompt("Project name:", default="LACE") key = int(typer.prompt("Issue key:")) ticket = f"{project}-{key}" desc = typer.prompt("Short description:") desc_format = desc.replace(" ", "_").lower() branch_name = f"{ticket}-{desc_format}" base_branch = typer.prompt("Base branch:", default="master") title = f"{ticket} | {desc}" typer.echo(f"Tiket: {title}") subprocess.run(["git", "fetch", "origin" f"{base_branch}:{base_branch}"]) subprocess.run(["git", "checkout", "-b", branch_name, base_branch]) subprocess.run(["git", "push", "origin", branch_name]) subprocess.run([ "gh", "pr", "create", "-d", "--title", title, "--body", "" "--base", base_branch ])
def configure(secret_key: str = None, access_key: str = None, host: str = 'https://api.ilkbyte.com', config_file: str = global_config_file): if secret_key is None and access_key is None: typer.echo('You can get api credentials on https://www.ilkbyte.com/panel/account/settings') if secret_key is None: secret_key = typer.prompt('secret_key', hide_input=True) if access_key is None: access_key = typer.prompt('access_key', hide_input=True) cli_section = 'cli' config = ConfigParser() config.add_section(cli_section) config.set(cli_section, 'host', host) config.set(cli_section, 'secret_key', secret_key) config.set(cli_section, 'access_key', access_key) if not config_file: config_file = global_config_file confirm = typer.confirm(f"Config will be saved to {config_file}. Do you confirm it?", abort=True) if confirm: config.write(open(config_file, 'w+'))
def webpage(target=None): """ select from options """ if not target: target = typer.style('Enter path to target webpage', fg=typer.colors.YELLOW, bold=True) target = typer.prompt(target) # connect to a URL req = Request(target, headers={'User-Agent': 'Mozilla/5.0'}) # read html code web_byte = urlopen(req).read() web_page = web_byte.decode('utf-8') # use re.findall to get all the links links = re.findall('"(http[s]?://.*?)"', web_page) list_of_urls = [] for link in links: if '&' in link: link.replace( '&', '&') # https://www.sitemaps.org/protocol.html#escaping typer.echo(link) list_of_urls.append(link) question = typer.style('Create sitemap (y/N)', fg=typer.colors.YELLOW, bold=True) question = typer.prompt(question) if question == 'y': site_map(list_of_urls) else: raise typer.Exit()
def _select_job( _job_list: typing.List[jobs.Job], idx: typing.Optional[int] = None, id: typing.Optional[str] = None, group: typing.Optional[str] = None, ) -> jobs.Job: selected_job = None if id is not None: possible_jobs = [x for x in _job_list if id in x.id] if len(possible_jobs) > 1 and group is not None: possible_jobs = [x for x in possible_jobs if group in x.group] if len(possible_jobs) == 1: selected_job = possible_jobs[0] elif len(possible_jobs) > 0: # TODO: ADD SELECTION HERE pass elif idx is not None: selected_job = _job_list[idx] if idx < len(_job_list) else None else: columns, _ = shutil.get_terminal_size(fallback=(80, 24)) width = int((columns - 15) / 4) print( f"{Fore.LIGHTBLACK_EX}{'idx':3} {'name':{width}} {'group':{width*2}} {'id':{width}} runnable" ) for idx, job in enumerate(_job_list): if job.is_runnable: runnable_emoji = f"{Fore.GREEN}✓{Fore.RESET}" else: runnable_emoji = f"{Fore.RED}!{Fore.RESET}" print( f"{Fore.YELLOW}{idx:3}{Fore.RESET} {job.name:{width}.{width}} {job.group:{width*2}.{width*2}}", f"{job.id:{width}.{width}} {runnable_emoji}", ) while True: _idx = typer.prompt("Select a job index (idx)") if 0 <= int(_idx) < len(_job_list): idx = int(_idx) selected_job = _job_list[idx] break if selected_job is None: logging.error("job could not be found") typer.Exit(1) return selected_job
def collect_field_definitions() -> ParsedFieldDefinitions: definitions: ParsedFieldDefinitions = [] while True: field_name: Union[str, bool] = typer.prompt( "Field name (Empty to continue)", default=False, show_default=False) if not field_name: break print_available_field_definitions() while True: choice = typer.prompt("Pick one", type=int) try: class_name = list(FIELD_GENERATOR_REGISTRY.keys())[choice] definitions.append((field_name, class_name, [])) break except IndexError: typer.echo(f"Error: {choice} is not a valid choice.") continue return definitions
def local_file(): """ select from options """ list_of_urls = [] target = typer.style('Enter path to target file', fg=typer.colors.YELLOW, bold=True) target = typer.prompt(target) open_target = open(target) for line in open_target: if '&' in line: line.replace( '&', '&') # https://www.sitemaps.org/protocol.html#escaping links = re.findall( 'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*(),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', line) # links = re.findall('"(http[s]?://.*?)"', line) for link in links: if link[-1] == ')': typer.echo(link[:-1]) list_of_urls.append(link[:-1]) else: typer.echo(link) list_of_urls.append(link) open_target.close() question = typer.style('Create sitemap (y/N)', fg=typer.colors.YELLOW, bold=True) question = typer.prompt(question) if question == 'y': site_map(list_of_urls) else: raise typer.Exit()
def getPahfit(): typer.secho('\nProvide the requested information to perform PAHFits\n', fg=typer.colors.GREEN) input_dir = typer.prompt( 'Enter the name of the directory to load the Spizter spectra from') output_dir = typer.prompt( 'Enter the name of the directory to which the outputs will be saved') max_iter = int( typer.prompt( 'Enter the maximum number of iterations to be performed per PAHFit. This number should be an integer' )) packfile = ( typer.prompt('Enter the name of the packfile to be used for fitting')) error = float( typer.prompt( 'Enter the relative error to be used for early termination of PAHFit' )) pahfitHelper.pahfit(input_dir, output_dir, max_iter, error, packfile, False) return output_dir, output_dir
def ask_utilization_metrics( util_indices: Dict[str, List[str]], pre_selected_metrics: Optional[List[int]] = None, ) -> List[Metric]: info_prompt = "Percentage Utilisation indices available:\n" i = 0 counter_dict = {} for section in util_indices.keys(): info_prompt += section + "\n" for util_metric in util_indices[section]: i = i + 1 counter_dict[i] = Metric( utilisation=(section, util_metric), is_frequency=False ) info_prompt += "\t(" + str(i) + ") " + util_metric + "\n" while True: if not pre_selected_metrics: typer.echo(info_prompt) user_input = typer.prompt( "Enter a comma-separated list of percentage " + "indices to optimize, input 0 to select frequency" ) try: if not pre_selected_metrics: parsed_list = [ int(i) for i in parse_comma_separated_list(r"[+]?\d+", user_input) ] else: parsed_list = pre_selected_metrics pre_selected_metrics = None if parsed_list and ( parsed_list == [] or max([i for i in parsed_list if i > 0]) < len(counter_dict) ): out: List[Metric] = [ counter_dict[i] for i in {i for i in parsed_list if i > 0} ] return ( (out + [Metric(None, True)]) if (0 in parsed_list) else out ) except Exception as e: print(e) print( "Invalid input, please enter" + " a comma separated list of integer numbers" )
def user_check( username: str, root: Optional[Path] = typer.Option(None), ): """ Check username and password combo """ password = typer.prompt(f"Enter password for {username}", hide_input=True) password = password.strip() token = get_user_store(root).authenticate(username, password) if token: typer.echo("Success: Username and password combination was valid") else: typer.echo("FAIL: Username and password combination was NOT valid") typer.Exit(1)
def connect(local: bool = typer.Option( False, "--local", '-l', help="Connects to server running on localhost", show_default=False)): """Connect to your endpoint. More info at https://argorithm.github.io/toolkit/cli#connect """ if local: endpoint = "http://localhost" else: endpoint = typer.prompt("Enter server endpoint", default=app_settings.get_endpoint()) app_settings.set_endpoint(endpoint)
def options(): """ auto executes with no command """ header = typer.style('Simple Scraper & Site Map Builder:', fg=typer.colors.BLACK, bg=typer.colors.YELLOW, bold=True) typer.echo() typer.echo(header) typer.echo() option1 = typer.style( '1. Reads an HTML document from a website, parses it and extracts all links to ' 'other pages/sites. Each link is printed out line by line to standard out.' 'Prints only the URL, not any of the surrounding HTML tags or attributes. Prompts for an ' 'output directory to save a sitemap.', fg=typer.colors.WHITE) typer.echo(option1) option2 = typer.style( '2. Reads an HTML document saved to disk, parses it and extracts all links to ' 'other pages/sites. Each link is printed out line by line to standard out. ' 'Prints only the URL, not any of the surrounding HTML tags or attributes. Prompts for an ' 'output directory to save a sitemap.', fg=typer.colors.WHITE) typer.echo(option2) option3 = typer.style( '3. Takes in a URL file saved to disk containing all the sites to generate' 'sitemaps for, prompts for an output directory to save sitemaps for each site ' 'in the inputs, and for the maximum number of URLs to include in a sitemap for extra-large ' 'sites.', fg=typer.colors.WHITE) typer.echo(option3) typer.echo() choice_text = typer.style('>>> url(1), local file(2), batch_sitemap(3)', fg=typer.colors.YELLOW, bold=True) choice = typer.prompt(choice_text) typer.echo(choice) if choice == '1': webpage() elif choice == '2': local_file() elif choice == '3': batch_process()
def main() -> None: current_version = get_current_version() typer.secho(f"Current version: {current_version}", bold=True) bump_type: BumpType = typer.prompt( typer.style("Release type ?", fg=typer.colors.BLUE, bold=True), type=Choice(list(BumpType.__members__)), default=BumpType.patch, show_choices=True, ) new_version = get_new_version(current_version, bump_type) release_notes = get_release_notes() summarize(current_version, new_version, bump_type, release_notes) save_release_notes(release_notes) update_pyproject(current_version, new_version) update_changelog(current_version, new_version) create_version_file(new_version) typer.confirm("Additionnal release commit files staged ?", abort=True, default=True)
def process_date(dt: str, which_date: str) -> Union[str, int]: """ Process human readable datetime strings, to date objects then to str in %Y-%m-%d fmt. 2 months ago -> datetime.date(2020, 7, 22) -> '2020-07-22' """ retry = 0 max_retry = 3 parse = dt if dt: while retry < max_retry: try: new_dt = dateparser.parse(parse) if new_dt: return new_dt.strftime("%Y-%m-%d") except Exception: typer.secho( """There must be a problem with your date or the language is not supported yet.""", bold=True, fg=typer.colors.BRIGHT_RED, ) typer.secho( """Try entering in YYYY-MM-DD format.""", bold=True, fg=typer.colors.BRIGHT_RED, ) enter_new = typer.confirm( f"Do you want to enter a new {which_date} date?", default=True ) if enter_new is False: typer.secho( "Aborting...", bold=True, fg=typer.colors.BRIGHT_RED, ) sys.exit() else: parse = typer.prompt("Enter here") finally: retry += 1 typer.secho( """There must be a problem with your date or the language is not supported yet 😕,you might want to send a feedback with 'seoman feedback' then we can support your language.""", bold=True, fg=typer.colors.BRIGHT_RED, ) sys.exit()
def init(): try: # Prompt for config bill_rate = typer.prompt("What's your bill rate?") config = Config(bill_rate=bill_rate) # Make Rep directory dir = Path(".rep") dir.mkdir() # Create and initialize the database with open_db() as db: db.table("config").insert(config.dict()) except FileExistsError: typer.echo("Database already exists.") raise typer.Abort()