From 58429a39f0ab590b654e42e276a58bbfe6d95651 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Julian-Samuel=20Geb=C3=BChr?= Date: Wed, 3 May 2023 15:09:12 +0200 Subject: [PATCH] Add csv format option --- mastodon_blocklist_deploy/cli.py | 10 ++++++---- mastodon_blocklist_deploy/helpers.py | 12 +++++++++++- 2 files changed, 17 insertions(+), 5 deletions(-) diff --git a/mastodon_blocklist_deploy/cli.py b/mastodon_blocklist_deploy/cli.py index 55abf97..4b4b7e4 100644 --- a/mastodon_blocklist_deploy/cli.py +++ b/mastodon_blocklist_deploy/cli.py @@ -7,7 +7,7 @@ import os import toml from mastodon_blocklist_deploy.models import Instance -from mastodon_blocklist_deploy.helpers import blocklist_to_markdown, blocklist_to_toml +from mastodon_blocklist_deploy.helpers import blocklist_to_markdown, blocklist_to_toml, blocklist_to_csv def load_blocklist_file(filename: str) -> [Instance]: @@ -46,10 +46,12 @@ def remove_key_from_dict(dict, key): def exporter(blocklist, output=None, format: str = "toml", private: bool = False): - if format == "markdown": - exported_text = blocklist_to_markdown(blocklist, private) if format == "toml": exported_text = blocklist_to_toml(blocklist, private) + if format == "csv": + exported_text = blocklist_to_csv(blocklist, private) + if format == "markdown": + exported_text = blocklist_to_markdown(blocklist, private) # Output the text if output is not None: @@ -74,7 +76,7 @@ def cli(): parser.add_argument('-o', '--output', help="Filename where to export the blocklist") parser.add_argument('-v', '--verbose', action='store_true') parser.add_argument('-n', '--no-delete', action='store_true', help="Do not delete existing blocks") - parser.add_argument('--format', help="Export format: toml|markdown") + parser.add_argument('--format', help="Export format: toml|markdown|csv") parser.add_argument('--private', action='store_true', help="When the flag is set, private comment will also be " "exported.") args = parser.parse_args() diff --git a/mastodon_blocklist_deploy/helpers.py b/mastodon_blocklist_deploy/helpers.py index 93d7b30..ed35b21 100644 --- a/mastodon_blocklist_deploy/helpers.py +++ b/mastodon_blocklist_deploy/helpers.py @@ -1,6 +1,7 @@ from mastodon_blocklist_deploy.models import Instance import toml - +import io +import csv def blocklist_to_markdown(blocklist: [Instance], private: bool = False): if private: @@ -19,3 +20,12 @@ def blocklist_to_markdown(blocklist: [Instance], private: bool = False): def blocklist_to_toml(blocklist: [Instance], private: bool = False): toml_string = toml.dumps({"instances": [b.as_dict(private) for b in blocklist]}) return toml_string + +def blocklist_to_csv(blocklist: [Instance], private: bool = False): + csv_string = io.StringIO() + blocklist_as_dict = [b.as_dict(private) for b in blocklist] + keys = blocklist_as_dict[0].keys() + w = csv.DictWriter(csv_string, keys) + w.writeheader() + w.writerows(blocklist_as_dict) + return csv_string.getvalue()