def get_description(name=None, defaults=None): """Prompt user for description fields and return results.""" new_description = dict() # Variable name is required (obviously) new_description['Variable'] = defaults['Variable'] # Variable type is required (obviously) original_type = defaults.get('Type', None) type_hint = "" if original_type is None else f" [was '{original_type}']" new_description['Type'] = prompt_options_list( prompt=f"Variable type{type_hint}: ", default=original_type, options=[item['Type'] for item in SECRET_TYPES]) # Prompt (also serves as description) is required prompt = ("Descriptive string to prompt user when " "setting value: ") cli = Input(prompt, default=defaults.get('Prompt'), word_color=colors.foreground["yellow"]) result = cli.launch() new_description['Prompt'] = result # Alternative option set is (no pun intended) optional if new_description['Type'] in ['string']: prompt = "Acceptable options from which to chose: " cli = Input(prompt, default=defaults.get('Options'), word_color=colors.foreground["yellow"]) result = cli.launch() # TODO(dittrich): BUG or ISSUE in waiting. # Items in an Options list can't end in '.*' without # causing confusion with ',*' wildcard feature. # Maybe switch to using '|' for alternaives instead? if '.*' in result: if result == '.*': msg = "[-] '.*' is not valid: did you mean '*'?" else: msg = ("[-] options list items can't have '.*' " "wildcards: did you mean to end with ',*'?") raise RuntimeError(msg) new_description['Options'] = result # Environment variable export alternative optional prompt = "Environment variable to export: " cli = Input(prompt, default=defaults.get('Export', ' '), word_color=colors.foreground["yellow"]) result = cli.launch() if result not in [' ', '', None]: new_description['Export'] = result # URL for further information on options, etc. prompt = "URL for help documentation: " cli = Input(prompt, default=defaults.get('Help', ' '), word_color=colors.foreground["yellow"]) result = cli.launch() if result not in [' ', '', None]: new_description['Help'] = result print('') return new_description
def __init__(self, fileName): self.ing_reader = ING_Reader(fileName) operator = ParticipantsOperator('categories.csv') participants = operator.get_participants() for transaction in self.ing_reader.getTransactions(): if transaction.category == 'unknown': if transaction.party in participants: transaction.set_category(participants[transaction.party]) else: print(transaction) #print(transaction.get_meta()) choices = list(operator.get_categories()) choices.append('NEW*') if os.name == 'nt': category = None while category not in choices: if category is not None: print ("Incorrect Category! Use NEW* to add a new category!") category = input("Set category [{}]:".format(sorted(choices))) if category == 'NEW*': category = input("Set new category: ") break else: cli = Bullet(prompt = "Choose category: ", choices = sorted(choices)) # Create a Bullet or Check object category = cli.launch() # Launch a prompt if category == 'NEW*': new_cli = Input(prompt = "Add new category: " ) # Create a Bullet or Check object category = new_cli.launch() # Launch a prompt transaction.set_category(category) operator.add_participant(transaction.party, category) operator.save() self.ing_reader.save()
def do_task(self): cli = Input(prompt="What task? 📝 >", strip=False) task = cli.launch() cli = Input(prompt="How long? ⏰ >", strip=False) # Set timer duration = int(cli.launch()) try: print("Press CTRL+C to cancel timer and log time.") time.sleep(duration) self.alert_finished(task, duration) except KeyboardInterrupt: print("\nTimer cancelled and time logged!") # TODO: duration passed should time executed before cancelled self.alert_finished(task, duration)
def take_action(self, parsed_args): se = self.app.secrets se.requires_environment() se.read_secrets_and_descriptions() group = parsed_args.group groups = se.get_groups() # Default to using a group with the same name as the environment, # for projects that require a group of "global" variables. if group is None: group = str(self.app.secrets) if group not in groups: raise RuntimeError((f"[!] group '{group}' does not exist in " f"environment '{str(se)}'" ) if parsed_args.group is not None else "[!] please specify a group with '--group'") descriptions = se.read_descriptions(group=group) variables = [item['Variable'] for item in descriptions] args = parsed_args.arg for arg in args: if arg not in variables: raise RuntimeError( f"[!] variable '{arg}' does not exist in group '{group}'") if not parsed_args.force: if not stdin.isatty(): raise RuntimeError( "[-] must use '--force' flag to delete a secret") else: prompt = f"Type the name '{arg}' to confirm: " cli = Input(prompt, default="", word_color=colors.foreground["yellow"]) confirm = cli.launch() if confirm != arg: self.logger.info('[-] cancelled deleting secret') return descriptions = [ item for item in descriptions if item['Variable'] != arg ] se.delete_secret(arg) if len(descriptions) == 0: paths = [se.get_descriptions_path(group=group)] if parsed_args.mirror_locally: paths.append( se.get_descriptions_path( root=os.getcwd(), group=group, )) for path in paths: safe_delete_file(path) self.logger.info("[+] deleted empty group '%s' (%s)", group, path) else: se.write_descriptions( data=descriptions, group=group, mirror_to=os.getcwd() if parsed_args.mirror_locally else None) se.write_secrets()
def main(): default_aws_dir = pathlib.Path().home() / '.aws' default_aws_config = default_aws_dir / 'config' default_aws_creds = default_aws_dir / 'credentials' current_mfa_prompt = Input(prompt='Please input your current mfa code: ') current_mfa = current_mfa_prompt.launch() profile_config = get_profile(default_aws_config) aws_session = get_session(mfa_serial_str=profile_config['mfa_serial'], mfa_code=current_mfa) write_setup(aws_cred_path=default_aws_creds, temp_creds=aws_session, provisioning_profile=profile_config)
def get_builder_aws_ebs() -> packer_builder: ''' build the aws builder section ''' section_meta('starting', getframeinfo(currentframe()).function) variable_dictionary = { 'source_ami': "{{ user `kali_aws_ami` }}", 'region': "{{ user `aws_region` }}", 'ssh_username': "******", 'instance_type': "t2.medium", 'ami_name': "Kali Linux (Standard)", "ami_users": [""], "force_deregister": "true", "force_delete_snapshot": "true" } auth_prompt = Bullet(prompt='Choose from the items below: ', choices=['AWS Profile', 'AWS Access Key']) auth_type = auth_prompt.launch() if auth_type == 'AWS Profile': profile_prompt = Input( prompt='Please input the profile you would like to use: ') current_profile = profile_prompt.launch() variable_dictionary.update({'profile': "{}".format(current_profile)}) elif auth_type == 'AWS Access Key': variable_dictionary.update({ 'access_key': "{{ user `aws_access_key` }}", 'secret_key': "{{ user `aws_secret_key` }}" }) else: print('unknown auth type: {}'.format(auth_type)) aws_ebs_builder = packer_builder.AmazonEbs().from_dict( 'AmazonEBS', d=variable_dictionary) # TODO: fixin base package to accept string aws_ebs_builder_dict = aws_ebs_builder.to_dict() aws_ebs_builder_dict['ami_users'] = "{{user `ami_users`}}" section_meta('exiting', getframeinfo(currentframe()).function) return aws_ebs_builder_dict
def launch(self): for section in self.configuration["config_sections"]: utils.cprint("We are now configuring {} section".format(section), color=colors.foreground["default"]) self.results[section] = self.rlaunch(section, 1) utils.cprint("You finish all the configurations, here is your full configurations", color=colors.foreground["default"]) utils.cprint(json.dumps(self.results, indent=2), color=colors.foreground["default"]) while True: ui = Input("Where are you going to save the configuration? ", word_color=colors.foreground["yellow"], default="configurations/default.json") path = ui.launch() if path: path_dir = os.path.dirname(path) if os.path.exists(path_dir): with open(path, 'w') as fout: fout.write(json.dumps(self.results, indent=2)) break else: utils.cprint("The dir `{}` does not exist".format(path_dir)) else: utils.cprint("Invalid input") utils.cprint("Done!")
def gif_path_option(image_filepath): path = Path(image_filepath) default_choice = YesNo( # Prompt for the user to see prompt="Do you want to use the default folder {0} ? ".format( path.parent), ) default = default_choice.launch() if default: return str(path.parent) else: while True: folder_choices = Input( # Prompt for the user to see prompt="What is the folder you want to use for the ASCII gif? ", strip=True) menu = folder_choices.launch() if os.path.exists(menu): return menu else: msg = f'Error: The folder \'{menu}\' doesnt seem to exists' print(color.error(msg))
if __name__ == "__main__": LOGGER = yt_utils.config_logger(log_file="yt-channels.log") with open(os.path.join(yt_utils.BASE_SHARE, "channels.json"), "r") as cf: channels = {c["name"]: c["id"] for c in json.load(fp=cf)} ch = Bullet( "Select a Channel:", bullet="→ ", align=4, margin=1, choices=list(channels.keys()), ) clear() channel = ch.launch() cp = Input(f"Enter a folder name ({channel}): ", default=channel) c_folder = cp.launch() details, plp = playlist_prompt(channels[channel]) clear() title = plp.launch() while title in ["[Next Page]", "[Previous Page]"]: page = details.next_page if title == "[Next Page]" else details.prev_page details, plp = playlist_prompt(channels[channel], page) clear() title = plp.launch() playlist = [pl for pl in details.items if pl.title == title][0] fp = Input(f"Enter a folder name ({playlist.title}): ", default=playlist.title) f_folder = fp.launch() addp = YesNo(prompt="Add this playlist to be monitored? (y/N)", default="N", prompt_prefix="")
alt_model_name = None if model is download_choice: cli = Bullet(prompt="Model to download:", choices=list(downloadable_models.keys()), **ocean_style_dolphin) model2download = cli.launch() alt_model_name_cli = Input( prompt="\n There's already a \'{}\' in your disk.\ \n Please, type a different name: \n\n ".format(model2download), strip=True, indent=alignment['indent']) if model2download in available_models: alt_model_name = alt_model_name_cli.launch() else: cli = YesNo( prompt="\n The model to download is going to be named \'{}\'. \ \n Do you want to change this name? [y/n] ".format( model2download), prompt_prefix="", indent=alignment['indent']) if cli.launch(): alt_model_name_cli = Input(prompt="\n Type a new name: \n ", strip=True, indent=alignment['indent']) alt_model_name = alt_model_name_cli.launch() else: model2resume = model
def input(self, index): cli = Input(prompt=self.items[index]['elements'], word_color=colors.background['cyan'], indent=3) answers = cli.launch() return answers