#!/usr/bin/env python3 # coding:utf-8 """ Author: Sir Garbagetruck -- Purpose: Sort fonts by use Created: 2020/07/24 """ import argparse import subprocess import os import json def newfontlist(): """generate a new fontlist with all zero uses of current fonts""" fonts = subprocess.Popen( ["fc-list", ":spacing=mono"], stdout=subprocess.PIPE) fontscut = subprocess.Popen( ["cut", "-d:", "-f2"], stdin=fonts.stdout, stdout=subprocess.PIPE) fontsort = subprocess.Popen( ["sort"], stdin=fontscut.stdout, stdout=subprocess.PIPE) fontuniq = subprocess.Popen( ["uniq"], stdin=fontsort.stdout, stdout=subprocess.PIPE) fonts.stdout.close() fontscut.stdout.close() fontsort.stdout.close() fontlist = fontuniq.communicate()[0].decode().split('\n') newlist = [] for i in fontlist: newlist.append([0, i.lstrip()]) return newlist def jsonpretty(thing): """prettify a thing as json to stdout""" return json.dumps(thing, check_circular=True, indent=4, sort_keys=True) def writelist(fontlist, outfile): with open(outfile, 'w+') as fh: fh.write(jsonpretty(fontlist)) def readfile(filename): thefile = os.path.expanduser(filename) with open(thefile) as fh: fontlist = json.loads(fh.read()) return fontlist def increment_font(fontlist, fontname): """increment the named font by one use""" newlist = [] for i in fontlist: if i[1] == fontname: newlist.append([i[0] + 1, i[1]]) else: newlist.append(i) return newlist def main(args): """open json, or create new, and spit out the sorted list.""" if args.output is not None: outfile = os.path.expanduser(args.output) else: outfile = os.path.expanduser(args.filename) if args.renew is not None: print("this is not written yet") exit(1) if args.increment is not None: fontlist = readfile(args.filename) fontlist = increment_font(fontlist, args.increment) writelist(fontlist, outfile) exit(0) if args.new: fontlist = newfontlist() writelist(fontlist, outfile) else: fontlist = readfile(args.filename) sortedlist = sorted(fontlist, key=lambda font: font[0], reverse=True) for i in sortedlist: print(i[1]) if __name__ == '__main__': ap = argparse.ArgumentParser() ap.add_argument('-f', '--filename', help='json "use" file to load', default='~/.config/fonts.json') ap.add_argument('--new', help='create new (all zero) json file', action='store_true', default=False) ap.add_argument('--renew', help='load old json and add any new fonts') ap.add_argument('-o', '--output', help='write to this output json file') ap.add_argument('-i', '--increment', help="increment named font by 1") main(ap.parse_args())