From 3652717354dce342ff28e0b5053bf93091339f89 Mon Sep 17 00:00:00 2001 From: abhijeetSaroha Date: Thu, 28 Dec 2023 03:45:37 +0530 Subject: [PATCH 1/6] change backend to typer --- src/makim/__main__.py | 2 +- src/makim/makim_cli.py | 203 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 204 insertions(+), 1 deletion(-) create mode 100644 src/makim/makim_cli.py diff --git a/src/makim/__main__.py b/src/makim/__main__.py index f28fe83..c9cdf5b 100644 --- a/src/makim/__main__.py +++ b/src/makim/__main__.py @@ -1,5 +1,5 @@ """Makim app to be called from `python -m`.""" -from makim.cli import app +from makim.makim_cli import app if __name__ == '__main__': app() diff --git a/src/makim/makim_cli.py b/src/makim/makim_cli.py new file mode 100644 index 0000000..b3cd4f9 --- /dev/null +++ b/src/makim/makim_cli.py @@ -0,0 +1,203 @@ +""" +Makim CLI module. + +This module defines the command-line interface for the Makim tool. +""" +import os +import sys + +from pathlib import Path + +from typer import Argument, Option, Typer, echo +from typing_extensions import Annotated + +from makim import Makim, __version__ + +makim = Makim() +app = Typer( + name='Makim', + epilog=( + 'If you have any problem, open an issue at: ' + 'https://github.com/osl-incubator/makim' + ), +) +makim_file_default = str(Path(os.getcwd()) / '.makim.yaml') + + +@app.callback(invoke_without_command=True) +def main( + # Common Options + help: bool = Option( + None, + '--help', + '-h', + is_flag=True, + help='Show the version and exit', + ), + version: bool = Option( + None, + '--version', + '-v', + is_flag=True, + help='Show the version and exit', + ), + verbose: bool = Option( + None, + '--verbose', + is_flag=True, + help='Show the commands to be executed.', + ), + dry_run: bool = Option( + None, + '--dry-run', + is_flag=True, + help="Show the commands but don't execute them.", + ), + # Makim-specific Options + makim_file: Annotated[ + str, + Option( + '--makim-file', + help='Specify a custom location for the makim file.', + is_flag=True, + ), + ] = makim_file_default, + target: Annotated[ + str, + Argument( + ..., + help='Specify the target command to be performed.', + ), + ] = '', +):# noqa: PLR0913 + """ + Makim is a tool. + + that helps you to organize and simplify your helper commands. + """ + makim_args = extract_makim_args() + print('Makim-Args: ', makim_args) + + if version: + return show_version() + + if help or not target: + return create_help_text(makim_file) + + args = { + 'dry_run': dry_run, + 'help': help, + 'makim_file': makim_file, + 'target': target, + 'verbose': verbose, + 'version': version, + } + + makim.load(makim_file) + makim_args.update(args) + + print('After update, Makim_Args: ', makim_args) + + return makim.run(args) + + +def create_help_text(makim_file): + """Display help text with details about Makim commands and options.""" + usage = """makim [--help] [--version] [--verbose] [--dry-run] [--makim-file + MAKIM_FILE] [target]""" + + description = """Makim is a tool that helps you to organize and simplify + your helper commands.""" + + epilog = """If you have any problem, open an issue at: + https://github.com/osl-incubator/makim""" + + makim.load(makim_file) + target_help = [] + + # Iterate through groups and targets to generate help text + groups = makim.global_data.get('groups', []) + for group in groups: + target_help.append('\n' + group + ':' + '\n') + target_help.append('-' * (len(group) + 1) + '\n') + for target_name, target_data in groups[group]['targets'].items(): + target_name_qualified = f'{group}.{target_name}' + help_text = target_data['help'] if 'help' in target_data else '' + target_help.append(f' {target_name_qualified} => {help_text}\n') + + if 'args' in target_data: + target_help.append(' ARGS:\n') + + for arg_name, arg_data in target_data['args'].items(): + target_help.append( + f' --{arg_name}: ({arg_data["type"]}) ' + f'{arg_data["help"]}\n' + ) + + help_text = format_help_text(description, usage, epilog, target_help) + echo(help_text) + + +def format_help_text(description, usage, epilog, target_help): + """Format help text with usage, description, and target details.""" + return f"""{usage} + +{description} + +Positonal Arguments: +{"".join(target_help)} +{epilog}""" + + +def show_version(): + """Show version.""" + echo(__version__) + + +def extract_makim_args(): + """Extract makim arguments from the CLI call.""" + makim_args = {} + index_to_remove = [] + for ind, arg in enumerate(list(sys.argv)): + if arg in [ + '--help', + '--version', + '--verbose', + '--makim-file', + '--dry-run', + ]: + continue + + if not arg.startswith('--'): + continue + + index_to_remove.append(ind) + + arg_name = None + arg_value = None + + next_ind = ind + 1 + + arg_name = sys.argv[ind] + + if ( + len(sys.argv) == next_ind + or len(sys.argv) > next_ind + and sys.argv[next_ind].startswith('--') + ): + arg_value = True + else: + arg_value = sys.argv[next_ind] + index_to_remove.append(next_ind) + + makim_args[arg_name] = arg_value + + # remove exclusive makim flags from original sys.argv + for ind in sorted(index_to_remove, reverse=True): + sys.argv.pop(ind) + + return makim_args + + +if __name__ == '__main__': + app() From b61fa8ddfdcdb0600bb5ce90ca701ac708a3924d Mon Sep 17 00:00:00 2001 From: abhijeetSaroha Date: Thu, 28 Dec 2023 04:00:40 +0530 Subject: [PATCH 2/6] add typer to dependencies --- pyproject.toml | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/pyproject.toml b/pyproject.toml index 360f947..fbddc08 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -30,6 +30,7 @@ jinja2 = ">=2.0" xonsh = ">=0.14.0" python-dotenv = ">=0.21.1" colorama = ">=0.4.6" +typer = "^0.9.0" [tool.poetry.group.dev.dependencies] containers-sugar = "1.9.0" @@ -66,7 +67,7 @@ ignore_missing_imports = true line-length = 79 force-exclude = true src = ["./src/makim", "./tests"] -ignore = ["RUF012"] +ignore = ["RUF012", "PLR0913"] exclude = [ "docs", ] @@ -84,6 +85,9 @@ select = [ "I002", # isort ] +[tool.ruff.lint.pylint] +max-args = 6 + [tool.ruff.pydocstyle] convention = "numpy" From 4c1f8c3ca845b980cefb64f2d56926456ae5ea63 Mon Sep 17 00:00:00 2001 From: abhijeetSaroha Date: Thu, 28 Dec 2023 10:37:50 +0530 Subject: [PATCH 3/6] change ^ to >= --- pyproject.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pyproject.toml b/pyproject.toml index fbddc08..57236e7 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -30,7 +30,7 @@ jinja2 = ">=2.0" xonsh = ">=0.14.0" python-dotenv = ">=0.21.1" colorama = ">=0.4.6" -typer = "^0.9.0" +typer = ">=0.9.0" [tool.poetry.group.dev.dependencies] containers-sugar = "1.9.0" From b09fb11a63526266fe1119a858a0aaa9bde2c3f2 Mon Sep 17 00:00:00 2001 From: abhijeetSaroha Date: Thu, 28 Dec 2023 10:42:00 +0530 Subject: [PATCH 4/6] remove print statement and extract_makim_args() method --- src/makim/makim_cli.py | 55 +----------------------------------------- 1 file changed, 1 insertion(+), 54 deletions(-) diff --git a/src/makim/makim_cli.py b/src/makim/makim_cli.py index b3cd4f9..7ce7dbe 100644 --- a/src/makim/makim_cli.py +++ b/src/makim/makim_cli.py @@ -4,7 +4,6 @@ This module defines the command-line interface for the Makim tool. """ import os -import sys from pathlib import Path @@ -69,15 +68,12 @@ def main( help='Specify the target command to be performed.', ), ] = '', -):# noqa: PLR0913 +): """ Makim is a tool. that helps you to organize and simplify your helper commands. """ - makim_args = extract_makim_args() - print('Makim-Args: ', makim_args) - if version: return show_version() @@ -94,10 +90,6 @@ def main( } makim.load(makim_file) - makim_args.update(args) - - print('After update, Makim_Args: ', makim_args) - return makim.run(args) @@ -154,50 +146,5 @@ def show_version(): echo(__version__) -def extract_makim_args(): - """Extract makim arguments from the CLI call.""" - makim_args = {} - index_to_remove = [] - for ind, arg in enumerate(list(sys.argv)): - if arg in [ - '--help', - '--version', - '--verbose', - '--makim-file', - '--dry-run', - ]: - continue - - if not arg.startswith('--'): - continue - - index_to_remove.append(ind) - - arg_name = None - arg_value = None - - next_ind = ind + 1 - - arg_name = sys.argv[ind] - - if ( - len(sys.argv) == next_ind - or len(sys.argv) > next_ind - and sys.argv[next_ind].startswith('--') - ): - arg_value = True - else: - arg_value = sys.argv[next_ind] - index_to_remove.append(next_ind) - - makim_args[arg_name] = arg_value - - # remove exclusive makim flags from original sys.argv - for ind in sorted(index_to_remove, reverse=True): - sys.argv.pop(ind) - - return makim_args - - if __name__ == '__main__': app() From fff90264c9f66a68ed668487743c65f42d00904e Mon Sep 17 00:00:00 2001 From: abhijeetSaroha Date: Fri, 29 Dec 2023 09:45:03 +0530 Subject: [PATCH 5/6] remove makim_cli.py --- src/makim/makim_cli.py | 150 ----------------------------------------- 1 file changed, 150 deletions(-) delete mode 100644 src/makim/makim_cli.py diff --git a/src/makim/makim_cli.py b/src/makim/makim_cli.py deleted file mode 100644 index 7ce7dbe..0000000 --- a/src/makim/makim_cli.py +++ /dev/null @@ -1,150 +0,0 @@ -""" -Makim CLI module. - -This module defines the command-line interface for the Makim tool. -""" -import os - -from pathlib import Path - -from typer import Argument, Option, Typer, echo -from typing_extensions import Annotated - -from makim import Makim, __version__ - -makim = Makim() -app = Typer( - name='Makim', - epilog=( - 'If you have any problem, open an issue at: ' - 'https://github.com/osl-incubator/makim' - ), -) -makim_file_default = str(Path(os.getcwd()) / '.makim.yaml') - - -@app.callback(invoke_without_command=True) -def main( - # Common Options - help: bool = Option( - None, - '--help', - '-h', - is_flag=True, - help='Show the version and exit', - ), - version: bool = Option( - None, - '--version', - '-v', - is_flag=True, - help='Show the version and exit', - ), - verbose: bool = Option( - None, - '--verbose', - is_flag=True, - help='Show the commands to be executed.', - ), - dry_run: bool = Option( - None, - '--dry-run', - is_flag=True, - help="Show the commands but don't execute them.", - ), - # Makim-specific Options - makim_file: Annotated[ - str, - Option( - '--makim-file', - help='Specify a custom location for the makim file.', - is_flag=True, - ), - ] = makim_file_default, - target: Annotated[ - str, - Argument( - ..., - help='Specify the target command to be performed.', - ), - ] = '', -): - """ - Makim is a tool. - - that helps you to organize and simplify your helper commands. - """ - if version: - return show_version() - - if help or not target: - return create_help_text(makim_file) - - args = { - 'dry_run': dry_run, - 'help': help, - 'makim_file': makim_file, - 'target': target, - 'verbose': verbose, - 'version': version, - } - - makim.load(makim_file) - return makim.run(args) - - -def create_help_text(makim_file): - """Display help text with details about Makim commands and options.""" - usage = """makim [--help] [--version] [--verbose] [--dry-run] [--makim-file - MAKIM_FILE] [target]""" - - description = """Makim is a tool that helps you to organize and simplify - your helper commands.""" - - epilog = """If you have any problem, open an issue at: - https://github.com/osl-incubator/makim""" - - makim.load(makim_file) - target_help = [] - - # Iterate through groups and targets to generate help text - groups = makim.global_data.get('groups', []) - for group in groups: - target_help.append('\n' + group + ':' + '\n') - target_help.append('-' * (len(group) + 1) + '\n') - for target_name, target_data in groups[group]['targets'].items(): - target_name_qualified = f'{group}.{target_name}' - help_text = target_data['help'] if 'help' in target_data else '' - target_help.append(f' {target_name_qualified} => {help_text}\n') - - if 'args' in target_data: - target_help.append(' ARGS:\n') - - for arg_name, arg_data in target_data['args'].items(): - target_help.append( - f' --{arg_name}: ({arg_data["type"]}) ' - f'{arg_data["help"]}\n' - ) - - help_text = format_help_text(description, usage, epilog, target_help) - echo(help_text) - - -def format_help_text(description, usage, epilog, target_help): - """Format help text with usage, description, and target details.""" - return f"""{usage} - -{description} - -Positonal Arguments: -{"".join(target_help)} -{epilog}""" - - -def show_version(): - """Show version.""" - echo(__version__) - - -if __name__ == '__main__': - app() From 0453a4e76eb1c67e66a7f058f336e206712bde4f Mon Sep 17 00:00:00 2001 From: abhijeetSaroha Date: Fri, 29 Dec 2023 09:46:49 +0530 Subject: [PATCH 6/6] update files --- src/makim/__main__.py | 2 +- src/makim/cli.py | 269 +++++++++++++++++------------------------- 2 files changed, 111 insertions(+), 160 deletions(-) diff --git a/src/makim/__main__.py b/src/makim/__main__.py index c9cdf5b..f28fe83 100644 --- a/src/makim/__main__.py +++ b/src/makim/__main__.py @@ -1,5 +1,5 @@ """Makim app to be called from `python -m`.""" -from makim.makim_cli import app +from makim.cli import app if __name__ == '__main__': app() diff --git a/src/makim/cli.py b/src/makim/cli.py index 3c6820e..7ce7dbe 100644 --- a/src/makim/cli.py +++ b/src/makim/cli.py @@ -1,199 +1,150 @@ -"""Cli functions to define the arguments and to call Makim.""" -import argparse +""" +Makim CLI module. + +This module defines the command-line interface for the Makim tool. +""" import os -import sys from pathlib import Path -from makim import Makim, __version__ - - -class CustomHelpFormatter(argparse.RawTextHelpFormatter): - """Formatter for generating usage messages and argument help strings. - - Only the name of this class is considered a public API. All the methods - provided by the class are considered an implementation detail. - """ - - def __init__( - self, - prog, - indent_increment=2, - max_help_position=4, - width=None, - **kwargs, - ): - """Define the parameters for the argparse help text.""" - super().__init__( - prog, - indent_increment=indent_increment, - max_help_position=max_help_position, - width=width, - **kwargs, - ) +from typer import Argument, Option, Typer, echo +from typing_extensions import Annotated +from makim import Makim, __version__ makim = Makim() - - -def _get_args(): - """ - Define the arguments for the CLI. - - note: when added new flags, update the list of flags to be - skipped at extract_makim_args function. - """ - makim_file_default = str(Path(os.getcwd()) / '.makim.yaml') - - parser = argparse.ArgumentParser( - prog='Makim', - description=( - 'Makim is a tool that helps you to organize ' - 'and simplify your helper commands.' - ), - epilog=( - 'If you have any problem, open an issue at: ' - 'https://github.com/osl-incubator/makim' - ), - add_help=False, - formatter_class=CustomHelpFormatter, - ) - parser.add_argument( +app = Typer( + name='Makim', + epilog=( + 'If you have any problem, open an issue at: ' + 'https://github.com/osl-incubator/makim' + ), +) +makim_file_default = str(Path(os.getcwd()) / '.makim.yaml') + + +@app.callback(invoke_without_command=True) +def main( + # Common Options + help: bool = Option( + None, '--help', '-h', - action='store_true', - help='Show the help menu', - ) - - parser.add_argument( + is_flag=True, + help='Show the version and exit', + ), + version: bool = Option( + None, '--version', - action='store_true', - help='Show the version of the installed Makim tool.', - ) - - parser.add_argument( + '-v', + is_flag=True, + help='Show the version and exit', + ), + verbose: bool = Option( + None, '--verbose', - action='store_true', + is_flag=True, help='Show the commands to be executed.', - ) - - parser.add_argument( + ), + dry_run: bool = Option( + None, '--dry-run', - action='store_true', + is_flag=True, help="Show the commands but don't execute them.", - ) + ), + # Makim-specific Options + makim_file: Annotated[ + str, + Option( + '--makim-file', + help='Specify a custom location for the makim file.', + is_flag=True, + ), + ] = makim_file_default, + target: Annotated[ + str, + Argument( + ..., + help='Specify the target command to be performed.', + ), + ] = '', +): + """ + Makim is a tool. + + that helps you to organize and simplify your helper commands. + """ + if version: + return show_version() + + if help or not target: + return create_help_text(makim_file) + + args = { + 'dry_run': dry_run, + 'help': help, + 'makim_file': makim_file, + 'target': target, + 'verbose': verbose, + 'version': version, + } + + makim.load(makim_file) + return makim.run(args) + + +def create_help_text(makim_file): + """Display help text with details about Makim commands and options.""" + usage = """makim [--help] [--version] [--verbose] [--dry-run] [--makim-file + MAKIM_FILE] [target]""" - parser.add_argument( - '--makim-file', - type=str, - default=makim_file_default, - help='Specify a custom location for the makim file.', - ) + description = """Makim is a tool that helps you to organize and simplify + your helper commands.""" - try: - idx = sys.argv.index('--makim-file') - makim_file = sys.argv[idx + 1] - except ValueError: - makim_file = makim_file_default + epilog = """If you have any problem, open an issue at: + https://github.com/osl-incubator/makim""" makim.load(makim_file) target_help = [] + + # Iterate through groups and targets to generate help text groups = makim.global_data.get('groups', []) for group in groups: - target_help.append('\n' + group + ':') - target_help.append('-' * (len(group) + 1)) + target_help.append('\n' + group + ':' + '\n') + target_help.append('-' * (len(group) + 1) + '\n') for target_name, target_data in groups[group]['targets'].items(): target_name_qualified = f'{group}.{target_name}' help_text = target_data['help'] if 'help' in target_data else '' - target_help.append(f' {target_name_qualified} => {help_text}') + target_help.append(f' {target_name_qualified} => {help_text}\n') if 'args' in target_data: - target_help.append(' ARGS:') + target_help.append(' ARGS:\n') for arg_name, arg_data in target_data['args'].items(): target_help.append( f' --{arg_name}: ({arg_data["type"]}) ' - f'{arg_data["help"]}' + f'{arg_data["help"]}\n' ) - parser.add_argument( - 'target', - nargs='?', - default=None, - help=( - 'Specify the target command to be performed. Options are:\n' - + '\n'.join(target_help) - ), - ) - - return parser + help_text = format_help_text(description, usage, epilog, target_help) + echo(help_text) -def show_version(): - """Show version.""" - print(__version__) - - -def extract_makim_args(): - """Extract makim arguments from the CLI call.""" - makim_args = {} - index_to_remove = [] - for ind, arg in enumerate(list(sys.argv)): - if arg in [ - '--help', - '--version', - '--verbose', - '--makim-file', - '--dry-run', - ]: - continue +def format_help_text(description, usage, epilog, target_help): + """Format help text with usage, description, and target details.""" + return f"""{usage} - if not arg.startswith('--'): - continue +{description} - index_to_remove.append(ind) +Positonal Arguments: +{"".join(target_help)} +{epilog}""" - arg_name = None - arg_value = None - next_ind = ind + 1 - - arg_name = sys.argv[ind] - - if ( - len(sys.argv) == next_ind - or len(sys.argv) > next_ind - and sys.argv[next_ind].startswith('--') - ): - arg_value = True - else: - arg_value = sys.argv[next_ind] - index_to_remove.append(next_ind) - - makim_args[arg_name] = arg_value - - # remove exclusive makim flags from original sys.argv - for ind in sorted(index_to_remove, reverse=True): - sys.argv.pop(ind) - - return makim_args - - -def app(): - """Call the makim program with the arguments defined by the user.""" - makim_args = extract_makim_args() - args_parser = _get_args() - args = args_parser.parse_args() - - if args.version: - return show_version() - - if not args.target or args.help: - return args_parser.print_help() +def show_version(): + """Show version.""" + echo(__version__) - if args.help: - return args_parser.print_help() - makim.load(args.makim_file) - makim_args.update(dict(args._get_kwargs())) - return makim.run(makim_args) +if __name__ == '__main__': + app()