From 02fb32ef23aba16c77f99c22c1bfb2a8ca2a0a6f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rafa=C5=82=20Tr=C3=B3jniak?= Date: Thu, 4 Jun 2020 17:11:05 +0200 Subject: [PATCH] feat: add JSON support to export Add support for JSON-formatted export --- src/hamster-cli.py | 4 ++-- src/hamster/reports.py | 23 +++++++++++++++++++++++ 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/src/hamster-cli.py b/src/hamster-cli.py index 9c6786787..2da4bd757 100644 --- a/src/hamster-cli.py +++ b/src/hamster-cli.py @@ -237,7 +237,7 @@ def assist(self, *args): if assist_command == "start": hamster_client._activities(sys.argv[-1]) elif assist_command == "export": - formats = "html tsv xml ical".split() + formats = "html tsv xml ical json".split() chosen = sys.argv[-1] formats = [f for f in formats if not chosen or f.startswith(chosen)] print("\n".join(formats)) @@ -422,7 +422,7 @@ def version(self): * list [start-date [end-date]]: List activities * search [terms] [start-date [end-date]]: List activities matching a search term - * export [html|tsv|ical|xml] [start-date [end-date]]: Export activities with + * export [html|tsv|ical|xml|json] [start-date [end-date]]: Export activities with the specified format * current: Print current activity * activities: List all the activities names, one per line. diff --git a/src/hamster/reports.py b/src/hamster/reports.py index 69a4a258d..14cf8a9cf 100644 --- a/src/hamster/reports.py +++ b/src/hamster/reports.py @@ -51,6 +51,8 @@ def simple(facts, start_date, end_date, format, path = None): if format == "tsv": writer = TSVWriter(report_path) + if format == "json": + writer = JSONWriter(report_path) elif format == "xml": writer = XMLWriter(report_path) elif format == "ical": @@ -323,3 +325,24 @@ def _finish(self, facts): self.file.write(Template(self.main_template).safe_substitute(data)) return + +class JSONWriter(ReportWriter): + def __init__(self, path): + ReportWriter.__init__(self, path) + self.activity_list = [] + + def _write_fact(self, fact): + self.activity_list.append( + { + "name": fact.activity, + "start_time": str(fact.start_time), + "end_time": str(fact.end_time), + "duration_minutes": stuff.duration_minutes(fact.delta), + "category": fact.category, + "description": fact.description, + "tags": ": ".join(fact.tags), + } + ) + + def _finish(self, facts): + self.file.write(json.dumps(self.activity_list))