69 lines
1.8 KiB
Python
69 lines
1.8 KiB
Python
|
# https://blog.stigok.com/2019/11/05/packing-python-script-binary-nicely-in-nixos.html
|
||
|
|
||
|
import argparse
|
||
|
import tomllib
|
||
|
import os
|
||
|
import subprocess
|
||
|
import sys
|
||
|
from pathlib import Path
|
||
|
|
||
|
|
||
|
def parse_directory(directory):
|
||
|
dictionary = {}
|
||
|
for entry in os.listdir(directory):
|
||
|
path = directory / entry
|
||
|
if path.is_dir():
|
||
|
dictionary[entry] = parse_directory(path)
|
||
|
else:
|
||
|
dictionary[entry] = path
|
||
|
return dictionary
|
||
|
|
||
|
|
||
|
def merge(dict1, dict2):
|
||
|
for key in iter(dict2):
|
||
|
if key in dict1:
|
||
|
if isinstance(dict1[key], dict) and isinstance(dict2[key], dict):
|
||
|
merge(dict1[key], dict2[key])
|
||
|
else:
|
||
|
dict1[key] = dict2[key]
|
||
|
else:
|
||
|
dict1[key] = dict2[key]
|
||
|
|
||
|
|
||
|
parser = argparse.ArgumentParser(prog='shortcuts.py',
|
||
|
description="shortcut dispatcher")
|
||
|
parser.add_argument('config')
|
||
|
|
||
|
args = parser.parse_args()
|
||
|
|
||
|
data = ""
|
||
|
with open(args.config, 'rb') as f:
|
||
|
data = tomllib.load(f)
|
||
|
|
||
|
dicts = []
|
||
|
for dir in data["directories"]:
|
||
|
path = Path(dir).expanduser()
|
||
|
if path.exists():
|
||
|
dicts.append(parse_directory(path))
|
||
|
|
||
|
res = {}
|
||
|
for d in dicts:
|
||
|
merge(res, d)
|
||
|
|
||
|
while isinstance(res, dict):
|
||
|
items = '\n'.join(sorted(res))
|
||
|
proc = subprocess.Popen(data["picker_command"],
|
||
|
shell=True,
|
||
|
stdin=subprocess.PIPE,
|
||
|
stdout=subprocess.PIPE)
|
||
|
proc.stdin.write(str.encode(items))
|
||
|
outs, errs = proc.communicate()
|
||
|
outs = outs.decode().strip()
|
||
|
res = res[outs]
|
||
|
|
||
|
proc = subprocess.Popen(res,
|
||
|
stdin=sys.stdin.buffer,
|
||
|
stdout=sys.stdout.buffer,
|
||
|
stderr=sys.stderr.buffer)
|
||
|
proc.wait()
|