diff options
| author | Kevin Van Brunt <kmvanbrunt@gmail.com> | 2021-06-09 18:15:19 -0400 |
|---|---|---|
| committer | Kevin Van Brunt <kmvanbrunt@gmail.com> | 2021-06-14 11:28:25 -0400 |
| commit | b94d04a9d82258c4b25584de97c707c0e3804f5b (patch) | |
| tree | e22bedc4460ba659339ad6c461046330503b1261 /cmd2/parsing.py | |
| parent | 5700c5706a513043d244b1f95ef9f08767110fe7 (diff) | |
| download | cmd2-git-b94d04a9d82258c4b25584de97c707c0e3804f5b.tar.gz | |
Converted persistent history files from pickle to JSON format
Diffstat (limited to 'cmd2/parsing.py')
| -rwxr-xr-x | cmd2/parsing.py | 28 |
1 files changed, 28 insertions, 0 deletions
diff --git a/cmd2/parsing.py b/cmd2/parsing.py index 3893cb23..9069cea2 100755 --- a/cmd2/parsing.py +++ b/cmd2/parsing.py @@ -147,6 +147,9 @@ class Statement(str): # type: ignore[override] # if output was redirected, the destination file token (quotes preserved) output_to: str = attr.ib(default='', validator=attr.validators.instance_of(str)) + # Used in JSON dictionaries + _args_field = 'args' + def __new__(cls, value: object, *pos_args: Any, **kw_args: Any) -> 'Statement': """Create a new instance of Statement. @@ -221,6 +224,31 @@ class Statement(str): # type: ignore[override] return rtn + def to_dict(self) -> Dict[str, Any]: + """Utility method to convert this Statement into a dictionary for use in persistent JSON history files""" + return self.__dict__.copy() + + @staticmethod + def from_dict(source_dict: Dict[str, Any]) -> 'Statement': + """ + Utility method to restore a Statement from a dictionary + + :param source_dict: source data dictionary (generated using to_dict()) + :return: Statement object + :raises KeyError: if source_dict is missing required elements + """ + # value needs to be passed as a positional argument. It corresponds to the args field. + try: + value = source_dict[Statement._args_field] + except KeyError as ex: + raise KeyError(f"Statement dictionary is missing {ex} field") + + # Pass the rest at kwargs (minus args) + kwargs = source_dict.copy() + del kwargs[Statement._args_field] + + return Statement(value, **kwargs) + class StatementParser: """Parse user input as a string into discrete command components.""" |
