-
-
Notifications
You must be signed in to change notification settings - Fork 43
Added cli_serializer & from_cli function #311
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
fabiocaccamo
merged 3 commits into
fabiocaccamo:main
from
Denperidge-Redpencil:args_support
Jul 15, 2023
Merged
Changes from 2 commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
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
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,81 @@ | ||
| from argparse import ArgumentError, ArgumentParser | ||
| from collections import Counter | ||
| from re import finditer | ||
|
|
||
| from benedict.serializers.abstract import AbstractSerializer | ||
| from benedict.utils import type_util | ||
|
|
||
| regex_keys_with_values = r"-+\w+(?=\s[^\s-])" | ||
| regex_all_keys = r"-+\w+" | ||
|
|
||
|
|
||
| def parse_keys(regex, string): | ||
| # For some reason findall didn't work | ||
| results = [match.group(0) for match in finditer(regex, string)] | ||
| return results | ||
|
|
||
|
|
||
| class CLISerializer(AbstractSerializer): | ||
| """ | ||
| This class describes a CLI serializer. | ||
| """ | ||
|
|
||
| def __init__(self): | ||
| super().__init__( | ||
| extensions=["cli"], | ||
| ) | ||
|
|
||
| @staticmethod | ||
| def _get_parser(options): | ||
| parser = ArgumentParser(**options) | ||
| return parser | ||
|
|
||
| def decode(self, s=None, **kwargs): | ||
| parser = self._get_parser(options=kwargs) | ||
|
|
||
| keys_with_values = set(parse_keys(regex_keys_with_values, s)) | ||
| all_keys = Counter(parse_keys(regex_all_keys, s)) | ||
| for key in all_keys: | ||
| count = all_keys[key] | ||
|
|
||
| # If the key has a value... | ||
| if key in keys_with_values: | ||
| # and is defined once, collect the values | ||
| if count == 1: | ||
| parser.add_argument( | ||
| key, | ||
| nargs="*", | ||
| # This puts multiple values in a list | ||
| # even though this won't always be wanted | ||
| # This is adressed after the dict is generated | ||
| required=False, | ||
| ) | ||
| # and is defined multiple times, collect the values | ||
| else: | ||
| parser.add_argument(key, action="append", required=False) | ||
|
|
||
| # If the key doesn't have a value... | ||
| else: | ||
| # and is defined once, store as bool | ||
| if count <= 1: | ||
| parser.add_argument(key, action="store_true", required=False) | ||
| # and is defined multiple times, count how many times | ||
| else: | ||
| parser.add_argument(key, action="count", required=False) | ||
|
|
||
| try: | ||
| args = parser.parse_args(s.split()) | ||
| except ArgumentError as error: | ||
Denperidge marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| raise ValueError from error | ||
| except BaseException as error: | ||
| raise ValueError from error | ||
|
|
||
| dict = vars(args) | ||
| for key in dict: | ||
| value = dict[key] | ||
| # If only one value was written, | ||
| # return that value instead of a list | ||
| if type_util.is_list(value) and len(value) == 1: | ||
| dict[key] = value[0] | ||
|
|
||
| return dict | ||
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,37 @@ | ||
| from benedict.dicts.io import IODict | ||
|
|
||
| from .test_io_dict import io_dict_test_case | ||
|
|
||
|
|
||
| class io_dict_cli_test_case(io_dict_test_case): | ||
| """ | ||
| This class describes an IODict / cli test case. | ||
| """ | ||
|
|
||
| def test_from_cli_with_valid_data(self): | ||
| s = """--url "https://github.com" --usernames another handle --languages Python --languages JavaScript -v --count --count --count""" | ||
| # static method | ||
| r = { | ||
| "url": '"https://github.com"', | ||
| "usernames": ["another", "handle"], | ||
| "languages": ["Python", "JavaScript"], | ||
| "v": True, | ||
| "count": 3, | ||
| } | ||
|
|
||
| d = IODict.from_cli(s) | ||
| self.assertTrue(isinstance(d, dict)) | ||
| self.assertEqual(d, r) | ||
| # constructor | ||
| d = IODict(s, format="cli") | ||
| self.assertTrue(isinstance(d, dict)) | ||
| self.assertEqual(d, r) | ||
|
|
||
| def test_from_cli_with_invalid_data(self): | ||
| s = "Lorem ipsum est in ea occaecat nisi officia." | ||
| # static method | ||
| with self.assertRaises(ValueError): | ||
| IODict.from_cli(s) | ||
| # constructor | ||
| with self.assertRaises(ValueError): | ||
| IODict(s, format="cli") |
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.