def ask(self): # Get list of calendars calendars = self.api.get_calendar_list()['items'] # Make user select calendar self.calendar = cli.ask_choice("Select calendar to sync:", choices=calendars, func_desc=lambda c: c['summary']) # Get list of colors colors = self.api.get_color_list() event_colors = [] for color_id in colors['event']: color = colors['event'][color_id] color['id'] = color_id event_colors.append(color) def custom_color_print(c): return f"https://www.color-hex.com/color/{c['background'][1:]}" self.lecture_color = cli.ask_choice("Select color for " + stylize("lecture", attr('bold')) + " events (2):", choices=event_colors, func_desc=custom_color_print) if self.lecture_color is None: self.lecture_color = event_colors[2] self.exercise_color = cli.ask_choice( "Select color for " + stylize("exercise", attr('bold')) + " events (1):", choices=event_colors, func_desc=custom_color_print) if self.exercise_color is None: self.exercise_color = event_colors[1] # Make user select while True: self.date_from = cli.ask_string( "Provide academic year starting date (Y-m-d):") if self.date_from: self.date_from = self.date_from.strip() try: self.date_from = datetime.datetime.strptime( self.date_from, '%Y-%m-%d') break except ValueError: pass print("Provided date is not valid, please try again.") self.save()
def download(): cli_ui.info_2("Downloading the newest version of PortCMS") if (not checker.checkGitStatus()): cli_ui.error( "Please download and install git to continue: https://git-scm.com/downloads" ) os._exit(1) isUpdate = False try: os.mkdir("PortCMS") except: what = cli_ui.ask_choice( "PortCMS is already downloaded. What do You want to do?", choices=["Update", "Check database config"]) isUpdate = what == "Update" if (not isUpdate): os.chdir("PortCMS") dbconf() os._exit(0) if (isUpdate): os.chdir("PortCMS") os.system("git pull") else: os.system( "git clone https://github.com/PetrusTryb/portfolio.git PortCMS") os.chdir("PortCMS") cli_ui.info(cli_ui.check, "Download complete")
def do_reset_hard(self, processor): 'Reset failed and done tasks for one processor.' if cli_ui.ask_yes_no( "Are you sure you want to delete all computed data?", default=False): processor = cli_ui.ask_choice("Pick a processor to reset", choices=self._sis.processors) self._sis.reset([processor], reset_hard=True) print("done.")
def edit_account_choice(self): account = self.database.find('user_data', f'user_ID = {self.user_id}') account_choices = [] for i in range(len(account)): account_choices.append(account[i][1:3]) choices = account_choices account_to_be_edited = cli_ui.ask_choice( "Which account would you like to edit", choices=choices) return account_to_be_edited
def restore(self): if not self.rubrik: creds = self._read_credentials(ignore_stored=True) self._connect(creds) # Find the backups/folders found under the given path backups = [d for d in os.listdir(self.path) if os.path.isdir(os.path.join(self.path, d))] # TODO: verify that the folders are really backup folders of this tool choice = cli_ui.ask_choice("Which backup to restore?", choices=backups) logging.info('Restoring `{}`'.format(choice)) # Create a list of config types backed up in the chosen folder config_types = [d for d in os.listdir(os.path.join(self.path, choice)) if os.path.isdir(os.path.join(self.path, choice, d))] # Create a list of dependencies for each config type so we can make sure # we restore them in a dependencies first order deps = {} for c in config_types: klass = config_class(c) instance = klass(self.path, self.rubrik, logging.getLogger()) deps[c] = instance.dependencies try: # Topologically sort the dependencies sorted_config_types = toposort_flatten(deps) # Execute restore in the sorted order jobs = [] for c in sorted_config_types: klass = config_class(c) instance = klass(self.path, self.rubrik, logging.getLogger()) path = os.path.join(self.path, choice, config_name(instance)) items = [] for f in os.listdir(path): with open(os.path.join(path, f), 'r') as jf: items.append(json.load(jf)) jobs += instance.restore(items) # Write the restore log self._write_restore_log(choice, jobs) except toposort.CircularDependencyError as e: logging.critical(e)
def delete(self): account = self.database.find('user_data', f'user_ID = {self.user_id}') account_choices = [] for i in range(len(account)): account_choices.append(account[i][1:3]) choices = account_choices account_to_be_deleted = cli_ui.ask_choice( "Which account would you like to delete", choices=choices) website = account_to_be_deleted[0] username = account_to_be_deleted[1] self.database.delete( 'user_data', f'website = "{website}" AND username = "******"')
def test_ask_choice() -> None: class Fruit: def __init__(self, name: str, price: int): self.name = name self.price = price def func_desc(fruit: Fruit) -> str: return fruit.name fruits = [Fruit("apple", 42), Fruit("banana", 10), Fruit("orange", 12)] with mock.patch("builtins.input") as m: m.side_effect = ["nan", "5", "2"] actual = cli_ui.ask_choice("Select a fruit", choices=fruits, func_desc=operator.attrgetter("name")) assert actual.name == "banana" assert actual.price == 10 assert m.call_count == 3
if entry[0] not in changes.keys(): changes[entry[0]] = [entry[1]] else: changes[entry[0]].append(entry[1]) return changes adds_sorted = {} deletes_sorted = {} cli_ui.info_1("Welcome to OCLC Holdings Manager") # Read in the settings settings_files = glob.glob('settings*.json') settings_file = cli_ui.ask_choice("Which settings file should I use?", choices=settings_files, sort=True) settings = OhmSettings(settings_file) # load sqlite3 database database = OhmDatabase(settings.database) # initialize OCLC API oclc_conn = OhmOclc(settings.oclc_credentials) menu_items = ("Parse MARC extract", "Compare changes", "Send to OCLC", "Analyze Results", "Test OCLC WSKey", "Exit") while True: menu_choice = cli_ui.ask_choice("OHM Main Menu", choices=menu_items,
def edit(): today = date.today() response = user_info.edit_account_choice() choices = ['Password', 'Username', 'Username and Password'] a = cli_ui.ask_choice("What would you like to edit?", choices=choices) if a == 'Password': new_password = cli_ui.ask_string("Enter new Password") user_info.edit(f'password = "******", Date_Modified = "{today}"', response[0], response[1]) helper.clear_screen() print("Records have been updated.") return True elif a == 'Username': new_username = cli_ui.ask_string("Enter new Username") user_info.edit(f'username = "******", Date_Modified = "{today}"', response[0], response[1) helper.clear_screen() print("Records have been updated.") return True elif a == 'Username and Password': new_password = cli_ui.ask_string("Enter new Password") new_username = cli_ui.ask_string("Enter new Username") user_info.edit( f'username = "******", password = "******", Date_Modified = "{today}"', response[0], response[1]) helper.clear_screen() print("Records have been updated.") return True def delete(): user_info.delete() helper.clear_screen() print("Account records have been deleted.") return True choices = ['Login', 'Sign Up', 'Exit'] flag = False while not flag: c = cli_ui.ask_choice("Would you like to", choices=choices) if c == "Login": flag = login() elif c == "Sign Up": flag = sign_up() elif c == "Exit": sys.exit(0) logged_in_choices = ['View Stored Passwords', 'Log Out', 'Add New Passwords', 'Edit Passwords', 'Delete Passwords', 'Password Generator'] achoices = ['Filter by Website', 'Filter by Username', 'View All'] while flag: c = cli_ui.ask_choice("Would you like to", choices=logged_in_choices) if c == 'View Stored Passwords': a = cli_ui.ask_choice("Would you like to", choices=achoices) if a == 'Filter by Website': info = filter_website() helper.clear_screen() print(info) elif a == 'Filter by Username': info = filter_username() helper.clear_screen() print(info) elif a == 'View All': info = user_info.get_all_password() helper.clear_screen() print(info) elif c == 'Log Out': helper.clear_screen() print("Logged Out.") sys.exit(0) elif c == 'Add New Passwords': helper.clear_screen() flag = add_passwords() elif c == 'Edit Passwords': helper.clear_screen() flag = edit() elif c == 'Delete Passwords': helper.clear_screen() flag = delete() elif c == 'Password Generator': helper.clear_screen() length = int(input("How many characters do you want in your password? ")) type1 = cli_ui.ask_yes_no("Do you want Upper Case Characters in your password?") type2 = cli_ui.ask_yes_no("Do you want Lower Case Characters in your password?") type3 = cli_ui.ask_yes_no("Do you want Special Characters in your password?") type4 = cli_ui.ask_yes_no("Do you want Numbers in your password?") password = helper.password_generator_main(type1, type2, type3, type4, length) if password: choice = cli_ui.ask_yes_no( "Would you like to add this password", default=False) if choice == True: website = cli_ui.ask_string("Please enter the website\'s name") username = cli_ui.ask_string("Please enter your username") user_info.add_password(website, username, password) helper.clear_screen() print("The password has been added.") elif choice == False: helper.clear_screen() flag = True
def test_ask_choice_ctrl_c() -> None: with pytest.raises(KeyboardInterrupt): with mock.patch("builtins.input") as m: m.side_effect = KeyboardInterrupt cli_ui.ask_choice("Select a animal", choices=["cat", "dog", "cow"])
def test_ask_choice_empty_input() -> None: with mock.patch("builtins.input") as m: m.side_effect = [""] res = cli_ui.ask_choice("Select a animal", choices=["cat", "dog", "cow"]) assert res is None
def do_reset(self, processor): 'Reset failed tasks for one processor.' processor = cli_ui.ask_choice("Pick a processor to reset", choices=self._sis.processors) self._sis.reset([processor]) print("done.")
def do_show(self, processor): 'Show results for one processor.' processor = cli_ui.ask_choice("Pick a processor", choices=self._sis.processors) self._sis.print_outputs(processor, up_to=10)