def detach_volume(): """Create a snapshot of a volume identified by it's mount path""" parser = _get_parser() group = parser.add_mutually_exclusive_group(required=True) group.add_argument("-m", "--mount-path", help="Mount point of the volume to be detached" ).completer = FilesCompleter() group.add_argument( "-i", "--volume-id", help="Volume id to detach").completer = ChoicesCompleter( info().volume_ids()) group.add_argument("-d", "--device", help="Device to detach").completer = ChoicesCompleter( info().volume_ids()) parser.add_argument("-x", "--delete", help="Delete volume after detaching", action="store_true") argcomplete.autocomplete(parser) args = parser.parse_args() if is_ec2(): ebs.detach_volume( mount_path=args.mount_path, volume_id=args.volume_id, device=args.device, delete_volume=args.delete, ) else: parser.error("Only makes sense on an EC2 instance")
def attach_eni(): """Optionally create and attach an elastic network interface""" parser = _get_parser() group = parser.add_mutually_exclusive_group() group.add_argument( "-s", "--subnet", help="Subnet for the elastic " + "network inferface if one is " + "created. Needs to " + "be on the same availability " + "zone as the instance.", ).completer = ChoicesCompleter(interface.list_compatible_subnet_ids()) group.add_argument( "-i", "--eni-id", help="Id of the eni to attach, if " + "attaching an existing eni.", ).completer = ChoicesCompleter(interface.list_attachable_eni_ids()) argcomplete.autocomplete(parser) args = parser.parse_args() if args.subnet: iface = interface.create_eni(args.subnet) elif args.eni_id: iface = interface.get_eni(args.eni_id) else: iface = interface.create_eni(info().subnet_id()) interface.attach_eni(iface.id) print(iface.id)
def _add_default_params(parser): parser.add_argument("template", nargs="?").completer = ChoicesCompleter( list_templates()) parser.add_argument("-y", "--yes", action='store_true', help='Answer yes or use default to all questions')
def cli_upsert_cloudfront_records(): """ Upsert Route53 records for all aliases of a CloudFront distribution """ parser = get_parser() stack_select = parser.add_mutually_exclusive_group(required=True) stack_select.add_argument("-i", "--distribution_id", help="Id for the " + "distribution to " + "upsert").completer = \ ChoicesCompleter(distributions()) stack_select.add_argument("-c", "--distribution_comment", help="Comment for the" + " distribution " + "to upsert").completer = \ ChoicesCompleter(distribution_comments()) parser.add_argument("-w", "--wait", help="Wait for request to sync", action="store_true") argcomplete.autocomplete(parser) args = parser.parse_args() upsert_cloudfront_records(args)
def main(): trial_class = 'c2w.test.protocol.udp_client_test.c2wUdpChatClientTestCase' parser = argparse.ArgumentParser(description='Trial udp client test', formatter_class=SmartFormatter) with open(os.path.join(stockrsm_path, "data", "c2w", "test", "udp_client_tests_list.txt")) as tests_list: tests = list(l.rstrip('\n') for l in tests_list.readlines()) if not tests: print("Sorry, no test available for the moment") exit() # stupid hack for [""] + tests for getting the alignment of values. To be modified. parser.add_argument("--scenario", help='''R|Scenario name. Allowed values are ''' + '\n'.join([""] + tests,)).completer=ChoicesCompleter(tuple(tests)) argcomplete.autocomplete(parser) options = parser.parse_args() cmdLine = ['trial', trial_class + ".test_" + options.scenario] os.environ['STOCKRSMPATH'] = stockrsm_path del sys.argv[-1] del sys.argv[-1] sys.argv.append(trial_class + ".test_" + options.scenario) sys.path.insert(0, os.path.abspath(os.getcwd())) from twisted.scripts.trial import run run()
def stack_params_and_outputs(): """Show stack parameters and outputs as a single json documents""" parser = _get_parser() parser.add_argument( "-p", "--parameter", help="Name of paremeter if only" + " one parameter required", ) parser.add_argument( "-s", "--stack-name", help="The name of the stack to show", default=info().stack_name(), ).completer = ChoicesCompleter(best_effort_stacks()) argcomplete.autocomplete(parser) args = parser.parse_args() resp, _ = instance_info.stack_params_and_outputs_and_stack( stack_name=args.stack_name) if args.parameter: if args.parameter in resp: print(resp[args.parameter]) else: parser.error("Parameter " + args.parameter + " not found") else: print(json.dumps(resp, indent=2))
def select_account(accounts_list): parser = argparse.ArgumentParser() parser.add_argument('account').completer = ChoicesCompleter( accounts_list.keys()) argcomplete.autocomplete(parser) args = parser.parse_args() return args.account
def cli_mfa_code(): """ Generates a TOTP code using an MFA token. """ parser = get_parser() parser.add_argument("token_name", help="Name of the token to use.").completer = \ ChoicesCompleter(list_mfa_tokens()) argcomplete.autocomplete(parser) args = parser.parse_args() print(mfa_generate_code(args.token_name))
def cli_mfa_to_qrcode(): """ Generates a QR code to import a token to other devices. """ parser = get_parser() parser.add_argument("token_name", help="Name of the token to use.").completer = \ ChoicesCompleter(list_mfa_tokens()) argcomplete.autocomplete(parser) args = parser.parse_args() mfa_to_qrcode(args.token_name)
def main(): parser = argparse.ArgumentParser(description='Read and process recipemd recipes') parser.add_argument( 'file', type=argparse.FileType('r', encoding='UTF-8'), help='A recipemd file' ).completer = FilesCompleter(allowednames='*.md') display_parser = parser.add_mutually_exclusive_group() display_parser.add_argument('-t', '--title', action='store_true', help='Display recipe title') display_parser.add_argument('-i', '--ingredients', action='store_true', help='Display recipe ingredients') parser.add_argument( '-f', '--flatten', action='store_true', help='Flatten ingredients and instructions of linked recipes into main recipe' ) parser.add_argument( '-r', '--round', type=lambda s: None if s.lower() == 'no' else int(s), metavar='n', default=2, help='Round amount to n digits after decimal point. Default is "2", use "no" to disable rounding.' ).completer = ChoicesCompleter(('no', *range(0, decimal.getcontext().prec + 1))) scale_parser = parser.add_mutually_exclusive_group() scale_parser.add_argument('-m', '--multiply', type=str, help='Multiply recipe by N', metavar='N') scale_parser.add_argument( '-y', '--yield', type=str, help='Scale the recipe for yield Y, e.g. "5 servings"', metavar='Y', dest='required_yield' ).completer = _yield_completer # completions argcomplete.autocomplete(parser) # parse args args = parser.parse_args() # read and parse recipe src = args.file.read() rp = RecipeParser() r = rp.parse(src) # scale recipe r = _process_scaling(r, args) # flatten recipe if args.flatten: base_url = URL(f'file://{os.path.abspath(args.file.name)}') r = _get_flattened_ingredients_recipe(r, base_url=base_url, parser=rp) # create output depending on arguments if args.title: print(r.title) elif args.ingredients: for ingr in r.leaf_ingredients: print(_ingredient_to_string(ingr, rounding=args.round)) else: rs = RecipeSerializer() print(rs.serialize(r, rounding=args.round))
def cli_read_profile_expiry(): """ Read expiry field from credentials file, which is there if the login happened with aws-azure-login or another tool that implements the same logic (none currently known).""" parser = argparse.ArgumentParser( description=cli_read_profile_expiry.__doc__) parser.add_argument("profile", help="The profile to read expiry info from").completer = \ ChoicesCompleter(read_expiring_profiles()) argcomplete.autocomplete(parser) args = parser.parse_args() print(read_profile_expiry(args.profile))
def cli_mfa_delete_token(): """ Deletes an MFA token file from the .ndt subdirectory in the user's home directory """ parser = get_parser() parser.add_argument("token_name", help="Name of the token to delete.").completer = \ ChoicesCompleter(list_mfa_tokens()) argcomplete.autocomplete(parser) args = parser.parse_args() mfa_delete_token(args.token_name)
def get_completer(self, parser, *args, **kwargs): # noqa: D102 if '--bazel-args' not in args: return None try: from argcomplete.completers import ChoicesCompleter except ImportError: return None return ChoicesCompleter(get_bazel_args_completer_choices())
def get_completer(self, parser, *args, **kwargs): # noqa: D102 if '--cargo-args' not in args: return None try: from argcomplete.completers import ChoicesCompleter except ImportError: return None return ChoicesCompleter([])
def show_stack_params_and_outputs(): """ Show stack parameters and outputs as a single json documents """ parser = get_parser() parser.add_argument("-r", "--region", help="Region for the stack to show", default=region()).completer = ChoicesCompleter(regions()) parser.add_argument("-p", "--parameter", help="Name of paremeter if only" + " one parameter required") parser.add_argument("stack_name", help="The stack name to show").completer = \ ChoicesCompleter(stacks()) argcomplete.autocomplete(parser) args = parser.parse_args() resp = stack_params_and_outputs(args.region, args.stack_name) if args.parameter: if args.parameter in resp: print(resp[args.parameter]) else: parser.error("Parameter " + args.parameter + " not found") else: print(json.dumps(resp, indent=2))
def add_arguments(self, *, parser): # noqa: D102 argument = parser.add_argument( 'name', help='The unique name identifying the repository') try: from argcomplete.completers import ChoicesCompleter except ImportError: pass else: repos = get_repositories() argument.completer = \ ChoicesCompleter(repos.keys())
def add_deployer_server(): """Add a server into a maven configuration file. Password is taken from the environment variable 'DEPLOYER_PASSWORD' """ parser = get_parser() parser.add_argument("file", help="The file to modify").completer = \ FilesCompleter() parser.add_argument("username", help="The username to access the server.").completer = \ ChoicesCompleter(()) parser.add_argument("--id", help="Optional id for the server. Default is" + " deploy. One server with this id is " + "added and another with '-release' " + "appended", default="deploy").completer = \ ChoicesCompleter(()) argcomplete.autocomplete(parser) args = parser.parse_args() if not os.path.isfile(args.file): parser.error(args.file + " not found") add_server(args.file, args.id, args.username) add_server(args.file, args.id + "-release", args.username)
def profile_expiry_to_env(): """ Prints profile expiry from credentials file (~/.aws/credentials) as eval-able environment variables """ parser = argparse.ArgumentParser(description=profile_expiry_to_env.__doc__) if "_ARGCOMPLETE" in os.environ: parser.add_argument("profile", help="The profile to read expiry info from").completer = \ ChoicesCompleter(read_expiring_profiles()) argcomplete.autocomplete(parser) else: parser.add_argument("profile", help="The profile to read expiry info from") args = parser.parse_args() print_profile_expiry(args.profile)
def add_arguments(self, *, parser): # noqa: D102 argument = parser.add_argument( 'name', nargs='?', help='Only list the information for a specific repository') try: from argcomplete.completers import ChoicesCompleter except ImportError: pass else: repos = get_repositories() argument.completer = \ ChoicesCompleter(repos.keys())
def cli_list_components(): """ Prints the components in a branch, by default the current branch """ parser = get_parser() parser.add_argument("-j", "--json", action="store_true", help="Print in json format.") parser.add_argument("-b", "--branch", help="The branch to get components from. Default is to process current branch").completer = \ ChoicesCompleter(Git().get_branches()) argcomplete.autocomplete(parser) args = parser.parse_args() ret = list_components(**vars(args)) if args.json: print(json.dumps(ret, indent=2)) else: print("\n".join(ret))
def volume_info(): """Get information about an EBS volume via a mountpoint, device or volume-id""" parser = _get_parser() group = parser.add_mutually_exclusive_group(required=True) group.add_argument("-m", "--mount-path", help="Mount point of the volume to be detached" ).completer = FilesCompleter() group.add_argument( "-i", "--volume-id", help="Volume id to detach").completer = ChoicesCompleter( info().volume_ids()) group.add_argument("-d", "--device", help="Device to detach").completer = ChoicesCompleter( info().volume_ids()) parser.add_argument( "-j", "--jmespath", help= "A jemspath expression to get a specific piece of info from volume", ) argcomplete.autocomplete(parser) args = parser.parse_args() if is_ec2(): vol_info = ebs.volume_info(mount_path=args.mount_path, volume_id=args.volume_id, device=args.device) if vol_info: if args.jmespath: vol_info = search(args.jmespath, vol_info) if isinstance(vol_info, dict): print(json.dumps(vol_info, indent=2, default=dthandler)) else: print(str(vol_info)) else: print("No volume info found") exit(1) else: parser.error("Only makes sense on an EC2 instance")
def detach_eni(): """Detach an eni from this instance""" parser = _get_parser() parser.add_argument("-i", "--eni-id", help="Eni id to detach").completer = ChoicesCompleter( info().network_interface_ids()) parser.add_argument("-d", "--delete", help="Delete eni after detach", action="store_true") argcomplete.autocomplete(parser) args = parser.parse_args() interface.detach_eni(args.eni_id, delete=args.delete)
def cli_share_to_another_region(): """ Shares an image to another region for potentially another account """ parser = get_parser() parser.add_argument("ami_id", help="The ami to share") parser.add_argument("to_region", help="The region to share to").completer =\ ChoicesCompleter(regions()) parser.add_argument("ami_name", help="The name for the ami") parser.add_argument("account_id", nargs="+", help="The account ids to sh" + "are ami to") argcomplete.autocomplete(parser) args = parser.parse_args() share_to_another_region(args.ami_id, args.to_region, args.ami_name, args.account_id)
def get_completer(self, parser, *args, **kwargs): # noqa: D102 # only contribute a complete for CMake arguments if '--catkin-cmake-args' not in args: return None # check that the argcomplete version has the necessary completer try: from argcomplete.completers import ChoicesCompleter except ImportError: return None # since only one extension can contribute a completer # include the CMake choices in addition to the catkin ones return ChoicesCompleter(get_cmake_args_completer_choices() + get_catkin_cmake_args_completer_choices())
def create_eni(): """create an elastic network interface""" parser = _get_parser() parser.add_argument( "-s", "--subnet", help="Subnet for the elastic " + "network inferface if one is " + "created. Needs to " + "be on the same availability " + "zone as the instance.", ).completer = ChoicesCompleter(interface.list_compatible_subnet_ids()) argcomplete.autocomplete(parser) args = parser.parse_args() if not args.subnet: args.subnet = info().subnet_id() iface = interface.create_eni(args.subnet) print(iface.id)
def __init__(self, jobs): super(ArgParser, self).__init__(description='Fuel artifact downloader') self.add_argument( '-j', '--job', dest='job', required=True, help='Jenkins job').completer = ChoicesCompleter(jobs) self.add_argument('-b', '--build', type=int, help='Jenkins build') self.add_argument('-i', '--iso', action='store_true', help='Download iso-file') self.add_argument('-a', '--author', help='Author of a build') self.add_argument('-o', '--output', help='Output dir for the artifacts') argcomplete.autocomplete(self)
def list_file_to_json(): """ Convert a file with an entry on each line to a json document with a single element (name as argument) containg file rows as list. """ parser = get_parser() parser.add_argument("arrayname", help="The name in the json object given" + "to the array").completer = \ ChoicesCompleter(()) parser.add_argument("file", help="The file to parse").completer = \ FilesCompleter() argcomplete.autocomplete(parser) args = parser.parse_args() if not os.path.isfile(args.file): parser.error(args.file + " not found") content = [line.rstrip('\n') for line in open(args.file)] json.dump({args.arrayname: content}, sys.stdout)
def add_arguments(self, *, parser): # noqa: D102 self.mixins_by_verb = get_mixins() argument = parser.add_argument( 'verb', nargs='?', help='Only show the mixins for a specific verb') try: from argcomplete.completers import ChoicesCompleter except ImportError: pass else: argument.completer = \ ChoicesCompleter(self.mixins_by_verb.keys()) argument = parser.add_argument( 'mixin_name', nargs='?', help='Only show a specific mixin for a specific verb') argument.completer = _get_mixin_name_completer('verb', self.mixins_by_verb)
def cli_enable_profile(): """Enable a configured profile. Simple IAM user, AzureAD, ADFS and ndt assume-role profiles are supported""" parser = argparse.ArgumentParser(description=cli_enable_profile.__doc__) type_select = parser.add_mutually_exclusive_group(required=False) type_select.add_argument("-i", "--iam", action="store_true", help="IAM user type profile") type_select.add_argument("-a", "--azure", action="store_true", help="Azure login type profile") type_select.add_argument("-f", "--adfs", action="store_true", help="ADFS login type profile") type_select.add_argument("-n", "--ndt", action="store_true", help="NDT assume role type profile") if "_ARGCOMPLETE" in os.environ: parser.add_argument("profile", help="The profile to enable").completer = \ ChoicesCompleter(read_profiles()) argcomplete.autocomplete(parser) else: parser.add_argument("profile", help="The profile to enable") args = parser.parse_args() if args.iam: profile_type = "iam" elif args.azure: profile_type = "azure" elif args.adfs: profile_type = "adfs" elif args.ndt: profile_type = "ndt" else: profile = get_profile(args.profile) if "azure_tenant_id" in profile: profile_type = "azure" elif "ndt_role_arn" in profile: profile_type = "ndt" elif "adfs_login_url" in profile: profile_type = "adfs" else: profile_type = "iam" enable_profile(profile_type, args.profile)
def profile_to_env(): """ Prints profile parameters from credentials file (~/.aws/credentials) as eval-able environment variables """ parser = argparse.ArgumentParser(description=profile_to_env.__doc__) parser.add_argument("-t", "--target-role", action="store_true", help="Output also azure_default_role_arn") parser.add_argument( "-r", "--role-arn", help= "Output also the role given here as the target role for the profile") if "_ARGCOMPLETE" in os.environ: parser.add_argument("profile", help="The profile to read profile info from").completer = \ ChoicesCompleter(read_profiles()) argcomplete.autocomplete(parser) else: parser.add_argument("profile", help="The profile to read profile info from") args = parser.parse_args() safe_profile = re.sub("[^A-Z0-9]", "_", args.profile.upper()) params = [] role_param = "AWS_TARGET_ROLE_ARN_" + safe_profile if args.target_role: profile_entry = "profile " + args.profile home = expanduser("~") config = join(home, ".aws", "config") if exists(config): parser = ConfigParser() with open(config) as configfile: parser.readfp(configfile) if profile_entry in parser.sections() and parser.has_option( profile_entry, "azure_default_role_arn"): params.append(role_param) print(role_param + "=\"" + parser.get(profile_entry, "azure_default_role_arn") + "\"") if profile_entry in parser.sections() and parser.has_option( profile_entry, "adfs_role_arn"): params.append(role_param) print(role_param + "=\"" + parser.get(profile_entry, "adfs_role_arn") + "\"") if args.role_arn: params.append(role_param) print(role_param + "=\"" + args.role_arn + "\"") print_profile(args.profile, params)