def get_review_info(review=None): known_metadata = (review.metadata.get("review") or {}) if review else {} date_started = get_date( "When did you start reading this book?", default=known_metadata.get("date_started"), ) date_read = get_date("When did you finish reading it?", default=known_metadata.get("date_read")) rating = inquirer.list_input( message="What’s your rating?", choices=[("⭐⭐⭐⭐⭐", 5), ("⭐⭐⭐⭐", 4), ("⭐⭐⭐", 3), ("⭐⭐", 2), ("⭐", 1)], default=known_metadata.get("rating"), carousel=True, ) if rating > 3: did_not_finish = False else: did_not_finish = not inquirer.list_input( message="Did you finish the book?", choices=[("yes", True), ("no", False)], carousel=True, ) return { "date_started": date_started, "date_read": date_read, "rating": rating, "did_not_finish": did_not_finish, }
def change_book(auth): review = get_review_from_user(auth=auth) while True: action = inquirer.list_input( message="What do you want to do with this book?", choices=[ ("Rate and review", "rating"), ("Mark as currently reading", "to_currently_reading"), ("Mark as to be read", "to_tbr"), ("Remove from library", "remove"), ("Edit manually", "manually"), ("Change cover image", "cover"), ("Choose different book", "book"), ("Quit", "quit"), ], carousel=True, ) if action == "quit": return if action == "book": return change_book(auth=auth) push_to_goodreads = False if review.metadata["book"].get("goodreads") and action != "cover": push_to_goodreads = inquirer.list_input( message="Do you want to push this change to Goodreads?", choices=[("Yes", True), ("No", False)], default=True, carousel=True, ) globals()[f"_change_{action}"](review=review, push_to_goodreads=push_to_goodreads, auth=auth) if action == "remove": return change_book(auth=auth)
def interactive_loop_add_point_of_interest(self): CHOICE_CANCEL = "CANCEL" choice = "" while choice != "Back": point_of_interest = inquirer.text( message="Enter the name of the point of interest to add") # Query for the point of interest gm_results = self.gm.places(query=point_of_interest, type="point_of_interest") # Let user choose which point of interest to add choice = inquirer.list_input( "Please choose which point of interest to add", choices=[(result["name"], result["place_id"]) for result in gm_results["results"]] + [("Cancel", CHOICE_CANCEL)]) if choice == CHOICE_CANCEL: break # Build Google Maps URL url = "https://www.google.com/maps/search/?{}" params = { "api": "1", "query": point_of_interest, "query_place_id": choice, } self.logger.debug(u" > Google Maps URL: {}".format( url.format(urllib.urlencode(params)))) # Navigate with Firefox and try to add self.marionette.add_feature_2(url.format(urllib.urlencode(params)), self.list_add) # Wait for user input choice = inquirer.list_input( "Please choose an action", choices=["Add another point of interest", "Back"])
def interactive_loop_add_city(self): CHOICE_CANCEL = "CANCEL" choice = "" while choice != "Back": city = inquirer.text(message="Enter the name of the city to add") # Query for city gm_results = self.gm.places_autocomplete(input_text=city, types="(cities)") # Let user choose which city to add choice = inquirer.list_input( "Please choose which city to add", choices=[(result["description"], result["place_id"]) for result in gm_results] + [("Cancel", CHOICE_CANCEL)]) if choice == CHOICE_CANCEL: break # Build Google Maps URL url = "https://www.google.com/maps/search/?{}" params = { "api": "1", "query": city, "query_place_id": choice, } self.logger.debug(u" > Google Maps URL: {}".format( url.format(urllib.urlencode(params)))) # Navigate with Firefox and try to add self.marionette.add_feature_2(url.format(urllib.urlencode(params)), self.list_add) # Wait for user input choice = inquirer.list_input("Please choose an action", choices=["Add another city", "Back"])
def create_book(auth, search_term=None): choice = inquirer.list_input( "Do you want to get the book data from Goodreads, or input it manually?", choices=["goodreads", "manually"], default="goodreads", carousel=True, ) entry_type = inquirer.list_input( message="What type of book is this?", choices=[ ("One I’ve read", "reviews"), ("One I’m currently reading", "currently-reading"), ("One I want to read", "to-read"), ], carousel=True, ) metadata = { "book": get_book_from_input() if choice == "manually" else goodreads.get_book_from_goodreads(auth=auth, search_term=search_term) } if entry_type == "reviews": review_info = get_review_info() metadata["review"] = { key: review_info[key] for key in ("date_read", "rating", "date_started") } if review_info["did_not_finish"]: metadata["review"]["did_not_finish"] = True review = Review(metadata=metadata, text="", entry_type=entry_type) if review.metadata["book"]["cover_image_url"]: review.download_cover() else: review.find_cover() review.save() review.edit() push_to_goodreads = inquirer.list_input( message="Do you want to push this change to Goodreads?", choices=[("Yes", True), ("No", False)], default=True, carousel=True, ) if push_to_goodreads: review = Review(path=review.path) # need to reload goodreads.push_to_goodreads(review, auth=auth) subprocess.check_call([ "git", "add", review.path, Path("src/covers") / (review.metadata["book"].get("cover_image") or ""), ])
def cli(*lol, **trololol): "Interact with the data fueling books.rixx.de" if len(sys.argv) > 1: return inquirer.list_input( message="What do you want to do?", choices=( ("Add a new book", create_book), ("Edit an existing book", change_book), ("Tag books", change_tags), ("Build the site", build_site), ("Review a random book", random_review), ), carousel=True, )()
def confirm_upload(test_file_list): """Confirm if the user would like to proceed with uploading test data. For folder uploads, the arg value will be presented to the user in a list. The intention is that they will be able to review the list of files the program found and confirm if they would like to proceed. For single file uploads, the arg value will be presented to the user for confirmation that the path they previously submitted was correct. Args: test_file_list (list): A list of test files that were identified as upload candidates Returns: A string value of 'Yes' or 'No' """ if len(test_file_list) > 1: print('\nFound ' + str(len(test_file_list)) + ' test(s) to upload.\n') print('Test(s):') pprint(test_file_list) print('\n') message_content = 'Are you sure you would like to upload these files?' else: message_content = 'Are you sure you would like to upload: ' + \ os.path.split(test_file_list[0])[1] + '?' confirmed = inquirer.list_input(message_content, choices=['Yes', 'No']) return confirmed
def interactive_loop(self): # Choices "Main Menu" # Add city # Add airport # Add point of interest # Exit CHOICE_CITY = "CITY" CHOICE_AIRPORT = "AIRPORT" CHOICE_POINT_OF_INTEREST = "POINT_OF_INTEREST" CHOICE_EXIT = "EXIT" CHOICES = [ ("Add city", CHOICE_CITY), ("Add airport", CHOICE_AIRPORT), ("Add point of interest", CHOICE_POINT_OF_INTEREST), ("Exit", CHOICE_EXIT), ] choice = "" while choice != CHOICE_EXIT: choice = inquirer.list_input("Please choose an action", choices=CHOICES) if choice == CHOICE_CITY: self.interactive_loop_add_city() elif choice == CHOICE_AIRPORT: self.interactive_loop_add_airport() elif choice == CHOICE_POINT_OF_INTEREST: self.interactive_loop_add_point_of_interest()
def get_book_from_goodreads(auth, search_term=None): search_term = inquirer.text( "Give me your best Goodreads search terms – or a URL, if you have one!", default=None, ) if "goodreads.com" in search_term: return get_book_data(url=search_term.strip() + ".xml", auth=auth) response = requests.get( f"{GOODREADS_URL}search/index.xml", {"key": auth["goodreads_developer_key"], "q": search_term}, ) to_root = ET.fromstring(response.content.decode()) results = to_root.find("search").find("results") options = [] for index, work in enumerate(results): title = work.find("best_book").find("title").text author = work.find("best_book").find("author").find("name").text options.append( ( (f"{index + 1}. {title} by {author}"), work.find("best_book").find("id").text, ) ) click.echo( click.style(f"Found {len(options)} possible books:", fg="green", bold=True) ) book = inquirer.list_input(message="Which one did you mean?", choices=options) return get_book_data(url=f"{GOODREADS_URL}book/show/{book}.xml", auth=auth)
def extended_vignere_cipher_get_key() -> bytearray: # Set up cipher key key_source = inquirer.list_input("Choose key source", choices=["Manual Input", "File"]) if key_source == "Manual Input": key_string = inquirer.text(message="key") return key_string.encode('UTF-8') elif key_source == "File": question = [ inquirer.Path( "file_path", message="path to key file", path_type=inquirer.Path.FILE, ), ] key_file_path = inquirer.prompt(question) return hf.read_file_as_bytearray(key_file_path['file_path']) else: raise NotImplementedError
def get_date(prompt, default): choices = ["today", "yesterday", "another day"] if default: choices.append(default) date = inquirer.list_input(message=prompt, choices=choices, carousel=True, default=default) today = dt.datetime.now() if date == "today": return today.date() if date == "yesterday": yesterday = today - dt.timedelta(days=1) return yesterday.date() if date == default: return default date = None while True: date = inquirer.text(message="Which other day?") if re.match(r"^\d{4}-\d{2}-\d{2}$", date.strip()): return dt.datetime.strptime(date, "%Y-%m-%d").date() elif re.match(r"^\d{1,2} [A-Z][a-z]+ \d{4}$", date.strip()): return dt.datetime.strptime(date, "%d %B %Y").date() else: click.echo(click.style(f"Unrecognised date: {date}", fg="red"))
def _change_cover(review, push_to_goodreads, auth): old_cover_url = review.metadata["book"]["cover_image_url"] source = inquirer.list_input( message="Where do you want to retrieve the cover image from?", choices=[ ("Goodreads", "goodreads"), ("Goodreads web scraping", "goodreads_scrape"), ("Google APIs", "google"), ("OpenLibrary", "openlibrary"), ("Custom URL", "manually"), ], carousel=True, ) if source == "manually": url = inquirer.text(message="Cover image URL") review.download_cover(url, force_new=True) else: review.find_cover(source, force_new=True) if review.metadata["book"]["cover_image_url"] != old_cover_url: click.echo( click.style("Successfully downloaded new cover image!", fg="green")) review.save() subprocess.check_call([ "xdg-open", Path("src/covers") / review.metadata["book"]["cover_image"] ]) else: click.echo(click.style("Couldn't find a new cover, sorry!", fg="red"))
def omap2(seed, mOps): global outPath maps = [] try: maps = listdir('.\\maps\\' + seed) except FileNotFoundError: print(errstr) omap() if maps == []: return if 'desktop.ini' in maps: maps.remove('desktop.ini') maps.sort(reverse=True) mtarg = list_input( 'Select which version you want to view', choices=maps+['Redraw Map']+mOps) if mtarg == 'Exit' or mtarg == 'Main Menu': return mtarg elif mtarg == 'Redraw Map (simple mode only)': outPath = stcWrap('.\\raws\\' + seed) if not outPath: draw() else: naxt('.\\raws\\' + seed) elif not accWrap('.\\maps\\' + seed + '\\' + mtarg): omap() else: now('.\\raws\\' + seed)
def simple_key_read_prompt() -> str: # Set up cipher key key_source = inquirer.list_input("Choose key source", choices=["Manual Input", "File"]) if key_source == "Manual Input": key_string = inquirer.text(message="key") return key_string elif key_source == "File": question = [ inquirer.Path( "file_path", message="path to key file", path_type=inquirer.Path.FILE, ), ] key_file_path = inquirer.prompt(question) return hf.read_file_as_string_single_stripped( key_file_path['file_path']) else: raise NotImplementedError
def ciphertext_read_prompt() -> str: # Ask for ciphertext source ciphertext_source = inquirer.list_input("Choose ciphertext source", choices=["Manual Input", "File"]) if ciphertext_source == "Manual Input": ciphertext_string = inquirer.text(message="ciphertext") return ciphertext_string elif ciphertext_source == "File": question = [ inquirer.Path( "file_path", message="path to ciphertext file", path_type=inquirer.Path.FILE, ), ] ciphertext_file_path = inquirer.prompt(question) return hf.read_file_as_string_single_stripped( ciphertext_file_path['file_path']) else: raise NotImplementedError
def hillCipher_cipher_get_key() -> str: # Set up cipher key key_source = inquirer.list_input("Choose key source", choices=["Manual Input", "File"]) if key_source == "Manual Input": key_size = int(inquirer.text(message="key size (N x N)")) key_string = inquirer.text(message="key") key_list = [int(x) for x in key_string.split()] if len(key_list) != key_size**2: raise Exception("key length not valid") key = [] for i in range(0, key_size): key_row = [] for j in range(0, key_size): key_row.append(key_list[key_size * i + j]) key.append(key_row) return key elif key_source == "File": question = [ inquirer.Path( "file_path", message="path to key file", path_type=inquirer.Path.FILE, ), ] key_file_path = inquirer.prompt(question) key_string_list = hf.read_file_as_string_list_stripped( key_file_path['file_path']) key_size = int(key_string_list[0]) key_list = [int(x) for x in key_string_list[1].split()] if len(key_list) != key_size**2: raise Exception("key length not valid") key = [] for i in range(0, key_size): key_row = [] for j in range(0, key_size): key_row.append(key_list[key_size * i + j]) key.append(key_row) return key else: raise NotImplementedError
def delete(name): if name is None: name = inquirer.list_input('Which model would you like to delete?', choices=get_builds()) if inquirer.confirm( "This will permanently delete your model. Do you want to continue?", default=False): delete_build(name)
def _integration_type(self, integration: str) -> str: if integration in Integration._registry.keys(): return integration return inquirer.list_input( f"Select Service for Integration '{integration}'", choices=list(Integration._registry.keys()) + [self.INQUIRER_SKIP_OPTION], )
def includeWorkflowStages(): ''' Just asking the user whether he wants to include workflow stages included in the export. Not possible to include stages using the delivery token. ''' choice = inquirer.list_input("{}Do you want to include the entry workflow stages in the export? (It is not possible to include them using the Delivery Token (Content Delivery API)).{}".format(config.BOLD, config.END), choices=['Include Workflow Stages', 'Exclude Workflow Stages']) if 'Include' in choice: return True return False
def select_region(account_id): client = _assumed_role(account_id, 'selectRegion', 'ec2') regions = [ region['RegionName'] for region in client.describe_regions()['Regions'] ] choice = inquirer.list_input("Select an AWS Region", choices=regions, default='eu-central-1') return choice
def omap(mOps): getPathLists() targ = list_input( 'Select which seed you want to view', choices=mapPaths+mOps) if targ == 'Exit' or targ == 'Main Menu': return targ else: omap2(targ)
def get_tests_to_upload(test_prefix='test_'): """Get information from the user regarding the files they are uploading via the API. Uses the inquirer command line user interface to query the user. The inquirer cli will validate all data submitted. A user may choose to upload a single file or upload an entire folder. Note - that when uploading a folder, all of the root folders' subdirectories will be searched for test files to upload. The default prefix for a test files is "test_". Args: test_prefix (str): The naming convention used for files containing test cases that should be uploaded to TestLink. Returns: A dict containing the data that will be uploaded. Either the the test_file key or test_folder will be returned depending on what type of upload the user has selected. Example: {'libs_dir': '/home/johndoe/test_project', 'test_file': 'home/johndoe/test_project/test_item.py'} """ if inquirer.list_input('How many test files do you need to upload?', choices=['Single', 'Multiple']) == 'Single': questions = [ inquirer.Path('test_file', message="Which test file are you uploading?", path_type=inquirer.Path.FILE), inquirer.Path( 'libs_dir', message="Whats the path to your projects library files?", path_type=inquirer.Path.DIRECTORY) ] else: questions = [ inquirer.Path('test_folder', message="Which test folder are you uploading?", path_type=inquirer.Path.DIRECTORY), inquirer.Path( 'libs_dir', message="Whats the path to your projects library files?", path_type=inquirer.Path.DIRECTORY) ] answers = inquirer.prompt(questions) files_to_upload = [] if 'test_folder' in answers: for root, dirs, files in os.walk(answers['test_folder']): for file in files: if re.search(test_prefix + '.*.py$', file) is not None: files_to_upload.append(root + '/' + file) else: files_to_upload.append(answers['test_file']) upload_data = {'tests': files_to_upload, 'libs_dir': answers['libs_dir']} upload_data['confirmed'] = confirm_upload(upload_data['tests']) return upload_data
def select_todo(): todos = [todo.title for todo in page.children] todo = prompt.list_input( 'Select Todo', choices=todos, ) index = todos.index(todo) return index, todo
def _choose_from(options): while True: choice = random.choice(options) prompt = f"{choice.metadata['book']['title']} by {choice.metadata['book']['author']}" approved = inquirer.list_input( message=prompt, choices=(("OK", True), ("Give me another one", False)), carousel=True, ) if approved: return choice
def menu2(): getPathLists() whatdo = list_input( 'MAIN', choices=['Draw a map', 'Open a map', 'Exit']) if whatdo == 'Exit': return elif whatdo == 'Draw a map': draw() elif whatdo == 'Open a map': omap()
def get_label(existing_labels: Set[str]) -> str: label = inquirer.list_input( 'Please choose a label to apply to this message', choices=[IGNORE_LABEL] + sorted(existing_labels) + [CREATE_LABEL], render=INQUIRER_RENDER) if label == CREATE_LABEL: label = create_label(existing_labels) if not label: return get_label(existing_labels) # Add new label to the set of existing labels existing_labels.add(label) return label
def menu(): getPathLists() whatdo = list_input( 'What would you like to do?', choices=['Draw a map', 'Open a map', 'Exit']) if whatdo == 'Exit': return elif whatdo == 'Draw a map': draw() elif whatdo == 'Open a map': omap()
def select_account(): orga_client = boto3.client('organizations') accounts = [] paginator = orga_client.get_paginator('list_accounts') page_iterator = paginator.paginate() for page in page_iterator: for account in page['Accounts']: accounts.append(account) choice = inquirer.list_input( "Select an AWS Account", choices=list( map(lambda acc: (acc['Name'], acc['Id'], acc['Status']), accounts))) return choice
def main(): os.system('clear') display_splash_screen() # Get Test Case Data info = get_tests_to_upload() while info['confirmed'] == 'No': if inquirer.list_input('Would you like to exit the application?', choices=['Yes', 'No']) == 'Yes': exit_application() restart_application() info = get_tests_to_upload() update_sys_path(info['libs_dir']) upload_test_cases(info['tests']) # Upload Data # Verify the user is finished if inquirer.list_input('Do you have more tests to upload?', choices=['Yes', 'No']) == 'Yes': main() else: exit_application()
def get_review_from_user(auth=None): review = None while not review: original_search = inquirer.text(message="What's the book called?") search = original_search.strip().lower().replace(" ", "-") files = list(glob.glob(f"src/**/*{search}*.md")) + list( glob.glob(f"src/reviews/**/*{search}*.md")) if len(files) == 0: click.echo(click.style("No book like that was found.", fg="red")) progress = inquirer.list_input( "Do you want to add it as new book instead, or continue searching?", choices=[("New book", "new"), ("Continue", "continue")], ) if progress == "new": return create_book(auth=auth, search_term=original_search) continue reviews = [Review(path=path) for path in files] options = [( f"{review.metadata['book']['title']} by {review.metadata['book']['author']} ({review.entry_type})", review, ) for review in reviews] options += [ ("Try a different search", "again"), ("Add a new book instead", "new"), ] choice = inquirer.list_input( f"Found {len(reviews)} books. Which one's yours?", choices=options, carousel=True, ) if choice == "new": return create_book(auth=auth, search_term=original_search) if choice == "again": continue return choice return get_review_from_user(auth=auth)
import os import sys sys.path.append(os.path.realpath('.')) import inquirer # flake8: noqa text = inquirer.text(message="Enter your username") print(text) password = inquirer.password(message='Please enter your password'), print(password) checkbox = inquirer.checkbox(message='Please define your type of project?', choices=['common', 'backend', 'frontend']) print(checkbox) choice = inquirer.list_input("Public or private?", choices=['public', 'private']) print(choice) correct = inquirer.confirm("This will delete all your current labels and " "create a new ones. Continue?", default=False) print(correct)