impose-cli 0.0.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2023 samuel-chai-902
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,11 @@
1
+ Metadata-Version: 1.0
2
+ Name: impose-cli
3
+ Version: 0.0.0
4
+ Summary: Create a CLI tool easily.
5
+ Home-page: UNKNOWN
6
+ Author: scdev
7
+ Author-email: samuel.chai.development@gmail.com
8
+ License: UNKNOWN
9
+ Description: UNKNOWN
10
+ Keywords: python,cli,click
11
+ Platform: UNKNOWN
@@ -0,0 +1,9 @@
1
+ # Impose CLI
2
+
3
+ Impose CLI is a simple tool used to generate a CLI tool by using one decorator.
4
+
5
+ ### How to use
6
+ Functions that are meant to be CLI commands should be decorator with @impose
7
+ In the main method, the impose_cli(target=None)() method should be called.
8
+
9
+ If target is None, then the commands will be from the same file. Otherwise, include the directory for your commands.
@@ -0,0 +1 @@
1
+ from impose_cli.impose_cli import impose, impose_cli
@@ -0,0 +1,117 @@
1
+ import ast
2
+ import click
3
+ from importlib.util import spec_from_file_location, module_from_spec
4
+ from inspect import getframeinfo, currentframe
5
+ from inspect import Parameter, signature as sig
6
+ from os import listdir
7
+ from os.path import exists, join, dirname, abspath
8
+
9
+
10
+ def impose(func):
11
+ return func
12
+
13
+
14
+ def expose(func: click.Group):
15
+ func()
16
+
17
+
18
+ def impose_cli(target: [str, None] = None) -> None:
19
+ """
20
+ If target is a directory, then each file will be a group and all functions will be a command
21
+ If medium is a file, then there will be no group and all functions will be a command
22
+ :param target:
23
+ :return:
24
+ """
25
+
26
+ class ImposeFunctionVisitor(ast.NodeVisitor):
27
+ def __init__(self):
28
+ self.imposed_functions = []
29
+
30
+ def visit_FunctionDef(self, node):
31
+ if hasattr(node, 'decorator_list'):
32
+ for decorator in node.decorator_list:
33
+ if isinstance(decorator, ast.Name) and decorator.id == 'impose':
34
+ self.imposed_functions.append(node.name)
35
+
36
+ def find_imposed_functions(filename):
37
+ with open(filename, 'r') as file:
38
+ file_contents = file.read()
39
+ module = ast.parse(file_contents)
40
+ visitor = ImposeFunctionVisitor()
41
+ visitor.visit(module)
42
+ return visitor.imposed_functions
43
+
44
+ def find_files(origin, target):
45
+ if target is None:
46
+ return [origin]
47
+
48
+ else:
49
+ directory = join(dirname(origin), target)
50
+ if not exists(directory):
51
+ raise FileNotFoundError(f"There is no directory {directory}.")
52
+
53
+ dirs = [x for x in listdir(directory) if x.endswith('.py')]
54
+ return [abspath(join(directory, f)) for f in dirs]
55
+
56
+ def load_module_from_file(file_path, module_name):
57
+ spec = spec_from_file_location(module_name, file_path)
58
+ module = module_from_spec(spec)
59
+ spec.loader.exec_module(module)
60
+ return module
61
+
62
+ def analyze_functions(module, function):
63
+ signature = sig(getattr(module, function))
64
+ parameters = signature.parameters
65
+ args_with_defaults = [[p.name, p.default, p.annotation if p.annotation.__name__ != '_empty' else None] for p in parameters.values() if p.default != Parameter.empty]
66
+ args_without_defaults = [[p.name, p.annotation if p.annotation.__name__ != '_empty' else None] for p in parameters.values() if p.default == Parameter.empty and p.default is not None]
67
+ return args_without_defaults, args_with_defaults
68
+
69
+ def create_dynamic_group(group_name, command_list):
70
+ dynamic_group = click.Group(name=group_name)
71
+
72
+ for cmd in command_list:
73
+ dynamic_command = click.Command(name=cmd['name'].replace('_', '-'), callback=cmd['callback'])
74
+
75
+ for arg in cmd['arguments']:
76
+ arg_name = arg[0].replace('_', '-')
77
+ if arg[1] is not None:
78
+ dynamic_command.params.append(click.Argument((arg_name,), type=arg[1]))
79
+ else:
80
+ dynamic_command.params.append(click.Argument((arg_name,)))
81
+
82
+ for opt in cmd['options']:
83
+ opt_name = opt[0].replace('_', '-')
84
+ if opt[2] is not None:
85
+ dynamic_command.params.append(click.Option((f"--{opt_name}",), default=opt[1], type=opt[2]))
86
+ else:
87
+ dynamic_command.params.append(click.Option((f"--{opt_name}",), default=opt[2]))
88
+
89
+ dynamic_group.add_command(dynamic_command)
90
+
91
+ return dynamic_group
92
+
93
+ origin_files = find_files(getframeinfo(currentframe().f_back)[0], target)
94
+
95
+ meta = {}
96
+ for origin_file in origin_files:
97
+ module_name = origin_file.split('/')[-1].replace('.py', '')
98
+ meta[module_name] = []
99
+ module = load_module_from_file(origin_file, module_name)
100
+ functions = find_imposed_functions(origin_file)
101
+ for function in functions:
102
+ args, opts = analyze_functions(module, function)
103
+ meta[module_name].append({
104
+ "name": function,
105
+ "arguments": args,
106
+ "options": opts,
107
+ "callback": getattr(module, function)
108
+ })
109
+
110
+ if target is not None:
111
+ main_group = create_dynamic_group('cli', [])
112
+ keys = meta.keys()
113
+ for key in keys:
114
+ main_group.add_command(create_dynamic_group(key, meta[key]))
115
+ return main_group
116
+ else:
117
+ return create_dynamic_group('cli', meta[list(meta.keys())[0]])
@@ -0,0 +1,11 @@
1
+ Metadata-Version: 1.0
2
+ Name: impose-cli
3
+ Version: 0.0.0
4
+ Summary: Create a CLI tool easily.
5
+ Home-page: UNKNOWN
6
+ Author: scdev
7
+ Author-email: samuel.chai.development@gmail.com
8
+ License: UNKNOWN
9
+ Description: UNKNOWN
10
+ Keywords: python,cli,click
11
+ Platform: UNKNOWN
@@ -0,0 +1,12 @@
1
+ LICENSE
2
+ README.md
3
+ setup.py
4
+ impose_cli/__init__.py
5
+ impose_cli/impose_cli.py
6
+ impose_cli.egg-info/PKG-INFO
7
+ impose_cli.egg-info/SOURCES.txt
8
+ impose_cli.egg-info/dependency_links.txt
9
+ impose_cli.egg-info/requires.txt
10
+ impose_cli.egg-info/top_level.txt
11
+ tests/__init__.py
12
+ tests/test.py
@@ -0,0 +1 @@
1
+ click
@@ -0,0 +1,2 @@
1
+ impose_cli
2
+ tests
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,26 @@
1
+ from subprocess import run, CalledProcessError
2
+ from setuptools import setup, find_packages
3
+
4
+
5
+ def get_version():
6
+ output = run('git describe --tags', capture_output=True, shell=True).stdout.decode('utf-8')
7
+ return ''.join(filter(lambda x: x.isdigit() or x == '.', list(output)))
8
+
9
+
10
+ with open('requirements.txt') as f:
11
+ requirements = f.read().splitlines()
12
+
13
+ VERSION = get_version()
14
+ DESCRIPTION = 'Create a CLI tool easily.'
15
+
16
+ # Setting up
17
+ setup(
18
+ name="impose-cli",
19
+ version=VERSION,
20
+ author="scdev",
21
+ author_email="samuel.chai.development@gmail.com",
22
+ description=DESCRIPTION,
23
+ packages=find_packages(),
24
+ install_requires=requirements,
25
+ keywords=['python', 'cli', 'click'],
26
+ )
File without changes
@@ -0,0 +1,35 @@
1
+ import pytest
2
+ from impose_cli.impose_cli import impose, impose_cli
3
+
4
+
5
+ @impose
6
+ def function_without_arguments():
7
+ return True
8
+
9
+
10
+ @impose
11
+ def function_with_arguments(arg1, arg2):
12
+ return True
13
+
14
+
15
+ @impose
16
+ def function_with_arguments_with_defaults(arg1: str = 'yes'):
17
+ return arg1
18
+
19
+
20
+ def testing_correct_argument_parsing():
21
+ commands = impose_cli().commands
22
+ assert len(commands['function-without-arguments'].params) == 0
23
+ assert len(commands['function-with-arguments'].params) == 2
24
+ assert commands['function-with-arguments'].params[0].opts == ['arg1']
25
+ assert commands['function-with-arguments'].params[0].type.name == 'text'
26
+ assert len(commands['function-with-arguments-with-defaults'].params) == 1
27
+ assert commands['function-with-arguments-with-defaults'].params[0].required == False
28
+ assert commands['function-with-arguments-with-defaults'].params[0].default == 'yes'
29
+ assert commands['function-with-arguments-with-defaults'].params[0].opts == ['--arg1']
30
+
31
+
32
+ def testing_impose_decorator():
33
+ assert function_without_arguments() == True
34
+ assert function_with_arguments(None, None) == True
35
+ assert function_with_arguments_with_defaults('str') == 'str'