From cf36808e55c1febda565f07b705980490ffc5c04 Mon Sep 17 00:00:00 2001 From: Skye Date: Sat, 2 Dec 2023 20:16:39 -0500 Subject: [PATCH] Add support for sheets out of a `.ods` --- flake.nix | 1 + format.py | 38 +++++++++++++++++++++++++++++++++++--- 2 files changed, 36 insertions(+), 3 deletions(-) diff --git a/flake.nix b/flake.nix index 6db4336..0831faf 100644 --- a/flake.nix +++ b/flake.nix @@ -25,6 +25,7 @@ devShell = with pkgs; mkShell { packages = [ + libreoffice typst python3 python3Packages.black diff --git a/format.py b/format.py index 51914f4..ebdf753 100755 --- a/format.py +++ b/format.py @@ -6,6 +6,7 @@ import hashlib import json import os import string +import subprocess import typing import urllib.parse import xml.etree.ElementTree as ET @@ -149,7 +150,9 @@ def get_country_name( parser = argparse.ArgumentParser( prog="format", description="format postcards with latex" ) -parser.add_argument("template", help="template to use", nargs="?", type=Path, default="2card") +parser.add_argument( + "template", help="template to use", nargs="?", type=Path, default="2card" +) parser.add_argument( "-o", "--origin", help="origin country code", default="us", type=iso_code ) @@ -198,6 +201,13 @@ parser.add_argument( help="Skip content, e.g. to make postcard back labels", ) +parser.add_argument( + "--sheet-name", + default="", + type=str, + help="Which sheet to use out of a .ods", +) + parser.add_argument( "-d", "--dont-compile", action="store_true", help="Don't compile to output.pdf" ) @@ -215,6 +225,7 @@ class Args(argparse.Namespace): content_path: Path no_content: bool dont_compile: bool + sheet_name: str args = parser.parse_args(args=None, namespace=Args()) @@ -223,7 +234,26 @@ cldr_root = ET.parse( f"{os.getenv('CLDR_ROOT')}/share/unicode/cldr/common/main/{args.language}.xml" ) -csvfile = open(args.address_file) +if args.address_file.suffix == ".csv": + csv_filename = args.address_file +elif args.address_file.suffix == ".ods": + result = subprocess.run( + [ + "libreoffice", + "--headless", + "--convert-to", + "csv:Text - txt - csv (StarCalc):44,34,76,1,,0,false,true,true,false,false,-1", + "--outdir", + str(cache_dir()), + args.address_file, + ] + ) + assert result.returncode == 0 + csv_filename = cache_dir() / f"{args.address_file.stem}-{args.sheet_name}.csv" +else: + raise Exception("Unknown file type for --address-file") + +csvfile = open(csv_filename) rows = csv.DictReader(csvfile) with open("secrets.json") as secrets_file: @@ -287,11 +317,13 @@ if args.origin == "us": serial += 1 imb.write_current_serial(serial) + def serialize_paths(obj: object): if isinstance(obj, Path): return str(obj) raise TypeError("Type not Serializable") + with (root_dir() / "options.json").open("w") as options: json.dump( fp=options, @@ -299,7 +331,7 @@ with (root_dir() / "options.json").open("w") as options: "args": args.__dict__, "cards": cards, }, - default=serialize_paths + default=serialize_paths, ) if args.dont_compile: