def test_union_no_dataclass(): @dataclass class Args: action: Union[int, str] with raises(Exception) as exc_info: parse(Args, []) assert "Union" in exc_info.value.args[0]
def test_subcommands(): install_help = "installing command" package_help = "package help" @argsclass(description=install_help) class Install: package: str = arg(positional=True, help=package_help) help_help = "helping command" @argsclass(description=help_help) class Help: command: str = arg(positional=True) verbose: bool pip_help = "Pip install packages!" @argsclass(description=pip_help) class Pip: action: Union[Install, Help] verbose: bool # passing your own parser ignores `description` assert pip_help in make_parser(Pip).format_help() parser = make_parser(Pip, ParserTest()) subparsers = next(action for action in parser._actions if isinstance(action, _SubParsersAction)) args = [("install", "package", install_help), ("help", "command", help_help)] for sub_command, arg_name, help_str in args: assert sub_command in parser.format_help() # noinspection PyUnresolvedReferences sub_help = subparsers.choices[sub_command].format_help() assert arg_name in sub_help assert help_str in sub_help result = parse(Pip, ["--verbose", "install", "foo"]) assert isinstance(result, Pip) assert isinstance(result.action, Install) assert result.action.package == "foo" assert result.verbose result = parse(Pip, ["help", "foo", "--verbose"]) assert isinstance(result, Pip) assert isinstance(result.action, Help) assert result.action.command == "foo" assert result.action.verbose assert not result.verbose # When a required argument is missing, argparse should print an error and trigger a # system exit with raises(SystemExit): parse(Pip, [])
def main(): def validate_args(args: Args) -> None: """Checks the given command-line arguments and raises an error if some values are invalid.""" if args.delete and args.update: raise ValueError( "You can't use --delete and --update at the same time.") if not args.mavenseed_url: raise ValueError( """You must provide a Mavenseed URL via the --mavenseed-url command line option or set the MAVENSEED_URL environment variable.""") if args.discount_amount <= 0: raise ValueError("You must provide a positive amount of discount.") if args.max_uses < 1: raise ValueError("You must provide a positive number of max uses.") if not set(args.supported_types).issubset(set(EligibleType)): raise ValueError( f"You must provide a valid set of eligible types. Possible values: {[t.value for t in EligibleType]}" ) args: Args = parse(Args) validate_args(args) auth_token: str = get_auth_token(args.mavenseed_url, args.email, args.password) if args.delete: raise NotImplementedError("Delete is not implemented yet.") elif args.update: raise NotImplementedError("Update is not implemented yet.") else: create_coupon(auth_token, args.mavenseed_url, args)
def main(): """Runs the program.""" args = parse(Args) if not args.path.is_dir(): raise ValueError(f"{args.path} is not a directory. Aborting operation.") print(generate_changelog(args))
def test_hyphen(): @dataclass class FooBar: baz: str = arg(positional=True) @dataclass class BarFoo: spam: str = arg(positional=True) @argsclass class Prog: action: Union[FooBar, BarFoo] result = parse(Prog, ["foo-bar", "x"], parser=ParserTest()) assert result.action.baz == "x" result = parse(Prog, ["bar-foo", "x"], parser=ParserTest()) assert result.action.spam == "x"
def main(): args: Args = parse(Args) if not args.input_file.exists(): print_error("File {} not found. Aborting operation.".format( args.input_file.as_posix())) output: str = "" with open(file_path, "r") as input_file: content: str = input_file.read() output = process_document(content, args.input_file) print(output)
def test_aliases(): @argsclass(parser_params=dict(aliases=["foo"])) class Install: package: str = arg(positional=True) @argsclass(parser_params=dict(aliases=["bar"])) class Help: command: str = arg(positional=True) @argsclass class Pip: action: Union[Install, Help] for alias in ["install", "foo"]: result = parse(Pip, [alias, "x"], parser=ParserTest()) assert result.action.package == "x" for alias in ["help", "bar"]: result = parse(Pip, [alias, "x"], parser=ParserTest()) assert result.action.command == "x"
def main(): def find_dist_directory(start_file: Path) -> Path: max_iterations = 10 path = start_file for _ in range(max_iterations): if path.stem == "dist": return path path = path.parent return None args: Args = parse(Args) valid_filepaths: List[Path] = [ p for p in args.filepaths if p.suffix == ".html" ] if not args.output_directory.exists(): print(f"Creating directory: {args.output_directory}") args.output_directory.mkdir(parents=True) global DIST_DIRECTORY DIST_DIRECTORY = find_dist_directory(valid_filepaths[0]) if DIST_DIRECTORY is None: print("Unable to find mavenseed directory.") exit(1) # Extract the body tag, replace links and move files to the output # directory. overwrite_all: bool = args.overwrite for path in valid_filepaths: with open(path) as f_in: html: str = f_in.read() html_body: str = extract_html_body(html) html_body = replace_links(html_body) out_path: Path = args.output_directory / (path.stem + ".html") if not overwrite_all and out_path.exists(): overwrite_prompt = f"""{out_path} already exists. Overwrite? - [y]: yes for this file - [N]: no for this file - [A]: yes to all""" prompt: str = input(overwrite_prompt) overwrite_all = prompt == "A" overwrite_this_file: bool = prompt.lower() == "y" if not overwrite_this_file: continue with open(out_path, "w") as f_out: f_out.write(html_body) print(f"Wrote {out_path}") if args.print_files: print("\n".join(str(p) for p in valid_filepaths))
def main(): args = parse(Args) issues_found: bool = False for path in args.input_files: if not path.is_file(): print(f"{path} does not exist. Exiting.") exit(ERROR_FILE_DOES_NOT_EXIST) issues = lint(path, args) if issues: issues_found = True print(f"Found {len(issues)} issues in{path}.\n") for issue in sorted(issues, key=lambda i: i.line): print( f"{issue.rule.value} {issue.line}:{issue.column_start}-{issue.column_end} {issue.message}" ) if args.print_errors and issue.error: print(f"\nError message:\n\n{issue.error}") if issues_found: exit(ERROR_ISSUES_FOUND)
def test_name(): @argsclass(name="foo") class Install: package: str = arg(positional=True) @argsclass(name="bar") class Help: command: str = arg(positional=True) @argsclass class Pip: action: Union[Install, Help] result = parse(Pip, ["foo", "x"], parser=ParserTest()) assert result.action.package == "x" with raises(ParserError): parse(Pip, ["install", "x"], parser=ParserTest()) result = parse(Pip, ["bar", "x"], parser=ParserTest()) assert result.action.command == "x" with raises(ParserError): parse(Pip, ["help", "x"], parser=ParserTest())
def main(): # Parse CLI args cli_args = datargs.parse(CliArgs) # Read graph with jaxfg.utils.stopwatch("Reading g2o file"): g2o: _g2o_utils.G2OData = _g2o_utils.parse_g2o(cli_args.g2o_path) # Make factor graph with jaxfg.utils.stopwatch("Making factor graph"): graph = jaxfg.core.StackedFactorGraph.make(g2o.factors) with jaxfg.utils.stopwatch("Making initial poses"): initial_poses = jaxfg.core.VariableAssignments.make_from_dict(g2o.initial_poses) # Time solver with jaxfg.utils.stopwatch("Single-step JIT compile + solve"): solution_poses = graph.solve( initial_poses, solver=dataclasses.replace(cli_args.solver_type.value, max_iterations=1), ) solution_poses.storage.block_until_ready() with jaxfg.utils.stopwatch("Single-step solve (already compiled)"): solution_poses = graph.solve( initial_poses, solver=dataclasses.replace(cli_args.solver_type.value, max_iterations=1), ) solution_poses.storage.block_until_ready() with jaxfg.utils.stopwatch("Full solve"): solution_poses = graph.solve(initial_poses, solver=cli_args.solver_type.value) solution_poses.storage.block_until_ready() # Plot plt.figure() # Visualize 2D poses if isinstance( next(iter(solution_poses.get_variables())), jaxfg.geometry.SE2Variable ): plt.plot( *( initial_poses.get_stacked_value(jaxfg.geometry.SE2Variable) .translation() .T ), # Equivalent: # *(onp.array([initial_poses.get_value(v).translation() for v in pose_variables]).T), c="r", label="Dead-reckoned", ) plt.plot( *( solution_poses.get_stacked_value(jaxfg.geometry.SE2Variable) .translation() .T ), # Equivalent: # *(onp.array([solution_poses.get_value(v).translation() for v in pose_variables]).T), c="b", label="Optimized", ) # Visualize 3D poses elif isinstance( next(iter(solution_poses.get_variables())), jaxfg.geometry.SE3Variable ): ax = plt.axes(projection="3d") ax.set_box_aspect((1, 1, 1)) ax.plot3D( *( initial_poses.get_stacked_value(jaxfg.geometry.SE3Variable) .translation() .T ), c="r", label="Dead-reckoned", ) ax.plot3D( *( solution_poses.get_stacked_value(jaxfg.geometry.SE3Variable) .translation() .T ), c="b", label="Optimized", ) else: assert False plt.title(f"Optimization on {cli_args.g2o_path.stem}") plt.legend() plt.show()
def main(): args: Args = parse(Args) for filepath in args.files: convert_markdown(args, filepath)