-
Notifications
You must be signed in to change notification settings - Fork 3
feat: add command line interface #72
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
e69b3b4
feat: add command line interface
njzjz a4df1e1
[pre-commit.ci] auto fixes from pre-commit.com hooks
pre-commit-ci[bot] 6d7e068
fix typing
njzjz 914aa04
add trim_pattern option
njzjz 71e1a3f
B904
njzjz a8d538c
add `sphinxarg.ext` to sphinx `extensions`
njzjz 4eda21a
support multiple inputs
njzjz File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,6 @@ | ||
from __future__ import annotations | ||
|
||
from dargs.cli import main | ||
|
||
if __name__ == "__main__": | ||
main() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,25 @@ | ||
from __future__ import annotations | ||
|
||
from typing import List | ||
|
||
from dargs.dargs import Argument | ||
|
||
|
||
def test_arguments() -> list[Argument]: | ||
"""Returns a list of arguments.""" | ||
return [ | ||
Argument(name="test1", dtype=int, doc="Argument 1"), | ||
Argument(name="test2", dtype=[float, None], doc="Argument 2"), | ||
Argument( | ||
name="test3", | ||
dtype=List[str], | ||
default=["test"], | ||
optional=True, | ||
doc="Argument 3", | ||
), | ||
] | ||
|
||
|
||
__all__ = [ | ||
"test_arguments", | ||
] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,35 @@ | ||
from __future__ import annotations | ||
|
||
from dargs.dargs import Argument | ||
|
||
|
||
def check( | ||
arginfo: Argument | list[Argument] | tuple[Argument, ...], | ||
data: dict, | ||
strict: bool = True, | ||
trim_pattern: str = "_*", | ||
) -> dict: | ||
"""Check and normalize input data. | ||
|
||
Parameters | ||
---------- | ||
arginfo : Union[Argument, List[Argument], Tuple[Argument, ...]] | ||
Argument object | ||
data : dict | ||
data to check | ||
strict : bool, optional | ||
If True, raise an error if the key is not pre-defined, by default True | ||
trim_pattern : str, optional | ||
Pattern to trim the key, by default "_*" | ||
|
||
Returns | ||
------- | ||
dict | ||
normalized data | ||
""" | ||
if isinstance(arginfo, (list, tuple)): | ||
arginfo = Argument("base", dtype=dict, sub_fields=arginfo) | ||
|
||
data = arginfo.normalize_value(data, trim_pattern=trim_pattern) | ||
arginfo.check_value(data, strict=strict) | ||
return data |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,107 @@ | ||
from __future__ import annotations | ||
|
||
import argparse | ||
import json | ||
import sys | ||
from typing import IO | ||
|
||
from dargs._version import __version__ | ||
from dargs.check import check | ||
|
||
|
||
def main_parser() -> argparse.ArgumentParser: | ||
"""Create the main parser for the command line interface. | ||
|
||
Returns | ||
------- | ||
argparse.ArgumentParser | ||
The main parser | ||
""" | ||
parser = argparse.ArgumentParser( | ||
description="dargs: Argument checking for Python programs" | ||
) | ||
subparsers = parser.add_subparsers(help="Sub-commands") | ||
parser_check = subparsers.add_parser( | ||
"check", | ||
help="Check a JSON file against an Argument", | ||
epilog="Example: dargs check -f dargs._test.test_arguments test_arguments.json", | ||
) | ||
parser_check.add_argument( | ||
"-f", | ||
"--func", | ||
type=str, | ||
help="Function that returns an Argument object. E.g., `dargs._test.test_arguments`", | ||
required=True, | ||
) | ||
parser_check.add_argument( | ||
"jdata", | ||
type=argparse.FileType("r"), | ||
default=[sys.stdin], | ||
nargs="*", | ||
help="Path to the JSON file. If not given, read from stdin.", | ||
) | ||
parser_check.add_argument( | ||
"--no-strict", | ||
action="store_false", | ||
dest="strict", | ||
help="Do not raise an error if the key is not pre-defined", | ||
) | ||
parser_check.add_argument( | ||
"--trim-pattern", | ||
type=str, | ||
default="_*", | ||
help="Pattern to trim the key", | ||
) | ||
parser_check.set_defaults(entrypoint=check_cli) | ||
|
||
# --version | ||
parser.add_argument("--version", action="version", version=__version__) | ||
return parser | ||
|
||
|
||
def main(): | ||
"""Main entry point for the command line interface.""" | ||
parser = main_parser() | ||
args = parser.parse_args() | ||
|
||
args.entrypoint(**vars(args)) | ||
njzjz marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
|
||
def check_cli( | ||
*, | ||
func: str, | ||
jdata: list[IO], | ||
strict: bool, | ||
**kwargs, | ||
) -> None: | ||
"""Normalize and check input data. | ||
|
||
Parameters | ||
---------- | ||
func : str | ||
Function that returns an Argument object. E.g., `dargs._test.test_arguments` | ||
jdata : IO | ||
File object that contains the JSON data | ||
strict : bool | ||
If True, raise an error if the key is not pre-defined | ||
|
||
Returns | ||
------- | ||
dict | ||
normalized data | ||
""" | ||
module_name, attr_name = func.rsplit(".", 1) | ||
try: | ||
mod = __import__(module_name, globals(), locals(), [attr_name]) | ||
except ImportError as e: | ||
raise RuntimeError( | ||
f'Failed to import "{attr_name}" from "{module_name}".\n{sys.exc_info()[1]}' | ||
) from e | ||
|
||
if not hasattr(mod, attr_name): | ||
raise RuntimeError(f'Module "{module_name}" has no attribute "{attr_name}"') | ||
func_obj = getattr(mod, attr_name) | ||
arginfo = func_obj() | ||
for jj in jdata: | ||
data = json.load(jj) | ||
check(arginfo, data, strict=strict) | ||
njzjz marked this conversation as resolved.
Show resolved
Hide resolved
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,9 @@ | ||
.. _cli: | ||
|
||
Command line interface | ||
====================== | ||
|
||
.. argparse:: | ||
:module: dargs.cli | ||
:func: main_parser | ||
:prog: dargs |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -11,6 +11,7 @@ Welcome to dargs's documentation! | |
:caption: Contents: | ||
|
||
intro | ||
cli | ||
sphinx | ||
dpgui | ||
nb | ||
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -3,3 +3,4 @@ numpydoc | |
deepmodeling_sphinx>=0.1.1 | ||
myst-nb | ||
sphinx_rtd_theme | ||
sphinx-argparse |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,4 @@ | ||
{ | ||
"test1": 1, | ||
"test2": 2 | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,44 @@ | ||
from __future__ import annotations | ||
|
||
import subprocess | ||
import sys | ||
import unittest | ||
from pathlib import Path | ||
|
||
this_directory = Path(__file__).parent | ||
|
||
|
||
class TestCli(unittest.TestCase): | ||
def test_check(self): | ||
subprocess.check_call( | ||
[ | ||
"dargs", | ||
"check", | ||
"-f", | ||
"dargs._test.test_arguments", | ||
str(this_directory / "test_arguments.json"), | ||
str(this_directory / "test_arguments.json"), | ||
] | ||
) | ||
subprocess.check_call( | ||
[ | ||
sys.executable, | ||
"-m", | ||
"dargs", | ||
"check", | ||
"-f", | ||
"dargs._test.test_arguments", | ||
str(this_directory / "test_arguments.json"), | ||
str(this_directory / "test_arguments.json"), | ||
] | ||
) | ||
with (this_directory / "test_arguments.json").open() as f: | ||
subprocess.check_call( | ||
[ | ||
"dargs", | ||
"check", | ||
"-f", | ||
"dargs._test.test_arguments", | ||
], | ||
stdin=f, | ||
) |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.