shell-scripts/banana-runner/banana-runner.py

70 lines
1.5 KiB
Python
Raw Permalink Normal View History

2023-07-06 11:07:16 -04:00
#!/usr/bin/python
from configparser import ConfigParser
from os import chdir, getcwd
from os.path import devnull, expanduser, isdir, isfile
from re import search
from shlex import split
from subprocess import Popen, run
from sys import argv, stdin, stdout, stderr
config = ConfigParser()
CONFIG_PATH = f'{getcwd()}/.banana'
if not isfile(CONFIG_PATH):
print("banana-runner: no config found!")
exit(1)
config.read(CONFIG_PATH)
sections = config.sections()
sections.remove("$")
if len(argv) == 1 or argv[0] == "$":
print("banana-runner: no arguments given")
exit(1)
if argv[1] == '-l' or argv[1] == '--list':
# do thing
for section in sections:
if section == '$':
continue
print(f'{section}')
exit()
name = argv[1]
if name not in sections:
print(f'banana-runner: no section {name} found')
exit(1)
section = config[name]
cmd = section['command']
alias_list = config['$']
def sub_aliases(string):
output = string
for alias in alias_list:
substring = '${' + alias.upper() + "}"
if substring in output:
output = output.replace(substring, alias_list[alias])
return output
cmd = sub_aliases(cmd)
if 'target' in section:
tdir = sub_aliases(section['target'])
tdir = expanduser(tdir)
if isdir(tdir):
chdir(tdir)
else:
if isfile(tdir):
print(f'banana-runner: "{tdir}" is not a directory!')
else:
print(f'banana-runner: "{tdir}" does not exist!')
exit(1)
print(f"{cmd}")
if 'shell' in section and section['shell']:
run(split(cmd))
else:
with open(devnull, 'w') as _:
Popen(cmd, shell = True, stdout = _, stderr = _)