Add csv format option

This commit is contained in:
moanos [he/him] 2023-05-03 15:09:12 +02:00
parent fe12631ee4
commit 58429a39f0
2 changed files with 17 additions and 5 deletions

View File

@ -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()

View File

@ -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()