-#!/bin/bash
-set -ex
-cd ~/
-file=".aspell.en.pws"
-header=$(head -1 ${file} | sed 's: [0-9]* *$::')
-(
-sed 1d ${file}
-printf '%s\n' "$@"
-) | LC_ALL=en_US sort -u | sed '/^[[:space:]]*$/d' > ${file}.tmp
-(
-echo "${header} $(wc -l ${file}.tmp | awk '{print $1}') "
-cat ${file}.tmp
-) > ${file}
-rm ${file}.tmp
+#!/usr/bin/env python3
+
+"""Update & sort personal dictionaries."""
+
+import argparse
+import locale
+from pathlib import Path
+import subprocess
+import sys
+
+
+def get_parser():
+ """Return a CLI parser."""
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument(
+ "--commit", action="store_true", help="commit to git"
+ )
+ parser.add_argument("words", nargs="*", help="words to add to the dictionary")
+ return parser
+
+
+def main(argv):
+ parser = get_parser()
+ opts = parser.parse_args(argv)
+
+ # For stable sorting.
+ locale.setlocale(locale.LC_COLLATE, "en_US.UTF8")
+
+ home = Path.home()
+
+ # Pull out the current set of words.
+ # Strip any git conflicts to make things easier.
+ pws = home / ".aspell.en.pws"
+ words = set(
+ x.strip() for x in pws.read_text(encoding="utf-8").splitlines() if " " not in x
+ )
+ words -= {"<<<<<<<", "|||||||", "=======", ">>>>>>>"}
+
+ # Add any words from the user.
+ words.update(opts.words)
+
+ # Update the aspell dict.
+ words = sorted(words, key=locale.strxfrm)
+ content = "\n".join(words) + "\n"
+ header = f"personal_ws-1.1 en {len(words)} \n"
+ with pws.open("w", encoding="utf-8") as fp:
+ fp.write(header)
+ fp.write(content)
+
+ # Update Chrome's dict.
+ chrome_pws = home / ".config" / "google-chrome" / "Custom Dictionary.txt"
+ chrome_pws.write_text(content, encoding="utf-8")
+
+ if opts.commit:
+ subprocess.run(
+ ["git", "commit", "-m", "dict: add more words", pws, chrome_pws], cwd=home
+ )
+
+
+if __name__ == "__main__":
+ sys.exit(main(sys.argv[1:]))