From 006c2bc8e4c9ca75b15c94de14bb2cbf5c6c4de0 Mon Sep 17 00:00:00 2001 From: Anthony Sottile Date: Tue, 17 Mar 2020 12:40:49 -0700 Subject: [PATCH] Add script for downloading themes --- README.md | 3 ++- bin/download-theme | 62 ++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 64 insertions(+), 1 deletion(-) create mode 100755 bin/download-theme diff --git a/README.md b/README.md index 7877881..d899fec 100644 --- a/README.md +++ b/README.md @@ -65,7 +65,8 @@ the syntax highlighting setup is a bit manual right now 1. from a clone of babi, run `./bin/download-syntax` -- you will likely need to install some additional packages to download them (`pip install cson`) 2. find a visual studio code theme, convert it to json (if it is not already - json) and put it at `~/.config/babi/theme.json` + json) and put it at `~/.config/babi/theme.json`. a helper script is + provided to make this easier: `./bin/download-theme NAME URL` ## demos diff --git a/bin/download-theme b/bin/download-theme new file mode 100755 index 0000000..bb516d9 --- /dev/null +++ b/bin/download-theme @@ -0,0 +1,62 @@ +#!/usr/bin/env python3 +import argparse +import json +import os.path +import plistlib +import re +import urllib.request +from typing import Any + +import cson # pip install cson + +# yes I know this is wrong, but it's good enough for now +UN_COMMENT = re.compile(rb'^\s*//.*$', re.MULTILINE) + + +def json_with_comments(src: bytes) -> Any: + return json.loads(UN_COMMENT.sub(b'', src)) + + +STRATEGIES = (json.loads, plistlib.loads, cson.loads, json_with_comments) + + +def main() -> int: + parser = argparse.ArgumentParser() + parser.add_argument('name') + parser.add_argument('url') + args = parser.parse_args() + + if '/blob/' in args.url: + url = args.url.replace('/blob/', '/raw/') + else: + url = args.url + + contents = urllib.request.urlopen(url).read() + + errors = [] + for strategy in STRATEGIES: + try: + loaded = strategy(contents) + except Exception as e: + errors.append((f'{strategy.__module__}.{strategy.__name__}', e)) + else: + break + else: + errors_s = '\n'.join(f'\t{name}: {error}' for name, error in errors) + raise AssertionError(f'could not load as json/plist/cson:\n{errors_s}') + + config_dir = os.path.expanduser('~/.config/babi') + os.makedirs(config_dir, exist_ok=True) + dest = os.path.join(config_dir, f'{args.name}.json') + with open(dest, 'w') as f: + json.dump(loaded, f) + + theme_json = os.path.join(config_dir, 'theme.json') + if os.path.lexists(theme_json): + os.remove(theme_json) + os.symlink(dest, theme_json) + return 0 + + +if __name__ == '__main__': + exit(main())