scripts/bin/tootctl.py

233 lines
5 KiB
Python
Executable file

#!/usr/bin/env python3
__software__ = 'PyTootctl'
__version__ = '0.1.2'
__author__ = 'Zoey Mae'
__homepage__ = 'https://git.barkshark.xyz/izaliamae/scripts/tootctl.py'
__license__ = 'CNPL v7+'
__license_url__ = 'https://thufie.lain.haus/files/CNPLv7.md'
import json, logging, os, sys
from os import environ
from pathlib import Path
from subprocess import Popen
home = Path('~').expanduser()
jemalloc = Path('/usr/lib/x86_64-linux-gnu/libjemalloc.so.2')
cfg_path = home.joinpath('.config/barkshark/pytootctl.json')
name = Path(__file__).name
class Config(dict):
defaults = dict(
ruby = Path(environ.get('RUBY_BIN', home.joinpath('.rbenv/shims/ruby'))),
mastodon = home.joinpath('mastodon'),
environment = 'production',
log_level = 'INFO'
)
def __init__(self):
super().__init__(**self.defaults)
if cfg_path.exists():
self.read()
def __setitem__(self, key, value):
key = key.lower()
if key not in self.defaults:
raise KeyError(f'Not a valid config option: {key}')
if value == 'default':
value = self.defaults[key]
elif key in ['ruby', 'mastodon']:
value = Path(value).resolve()
elif key == 'environment' and value not in ['production', 'development']:
raise ValueError(f'Environment should be "production" or "development", not "{value}"')
elif key == 'log_level':
if value.upper() not in ['CRITICAL', 'ERROR', 'WARNING', 'INFO', 'DEBUG']:
raise ValueError(f'Invalid logging level: {value}')
value = value.upper()
logging.getLogger().setLevel(value)
super().__setitem__(key, value)
def __getattr__(self, key):
return self[key]
def __setattr__(self, key, value):
self[key] = value
def update(self, data):
for key, value in data.items():
self[key] = value
def json(self, indent=4):
return json.dumps({k: str(v) for k,v in self.items()}, indent=indent)
def read(self):
with cfg_path.open('r') as fd:
try:
self.update(json.loads(fd.read()))
except json.decoder.JSONDecodeError:
logging.error('Failed to parse config. Continuing with defaults.')
def write(self):
cfg_path.parent.mkdir(parents=True, exist_ok=True)
with cfg_path.open('w') as fd:
fd.write(self.json())
class Command:
def __init__(self, arguments):
try:
cmd = arguments[0]
except IndexError:
raise AttributeError('No command specified')
args = arguments[1:] if len(arguments) > 1 else []
self.response = self[cmd](*args)
def __getitem__(self, key):
try:
return getattr(self, f'cmd_{key}')
except AttributeError:
raise InvalidCommandError(f'Not a valid command: {key}')
def cmd_config(self, key=None, value=None):
if key and value:
logging.debug(f'Setting {key}: {value}')
config[key] = value
config.write()
self.cmd_config()
elif key and not value:
print(f'Value for "{key}": {config[key]}')
elif not key:
print('Current config:')
for k,v in config.items():
line = f' {k}: {v}'
if isinstance(v, Path) and not v.exists():
line += ' (missing)'
print(line)
def cmd_usage(self, command=None):
print(f'''PyTootctl v{__version__}
Usage:
{name} config [key] [value]
Gets or sets the config. Specify a key and value to set a config option.
Only specify a key to get the value of a specific option. Leave out the key
and value to get all the options and their values
{name} usage
This message
{name} (tootctl command) [arguments]
Run tootctl with the specified command and arguments. Any path arguments
will be properly parsed and passed to tootctl so relative paths work from
the current directory''')
def debian_11_check():
info = {}
if not jemalloc.exists():
return False
if not Path('/etc/os-release').exists():
return False
for line in open('/etc/os-release', 'r').readlines():
key, value = line.split('=', 1)
value = value.replace('\n', '')
if value.startswith('"') and value.endswith('"'):
value = value[1:-1]
info[key] = value
return info['ID'].lower() == 'debian' and info['VERSION_ID'] == "11"
class InvalidCommandError(Exception):
pass
if __name__ == '__main__':
logging.basicConfig()
config = Config()
tootctl = config.mastodon.joinpath('bin/tootctl')
args = sys.argv[1:] if len(sys.argv) > 1 else []
try:
Command(args)
sys.exit(0)
except InvalidCommandError:
pass
if not config.ruby.exists():
logging.error(f'Cannot find ruby at "{config.ruby}"')
sys.exit(1)
if not tootctl.exists():
logging.error(f'Cannot find tootctl at "{tootctl}"')
sys.exit(1)
environment = environ.copy()
environment.update({
'RAILS_ENV': config.environment,
'NODE_ENV': config.environment
})
if debian_11_check():
logging.debug('Debian Bullseye with Jemalloc detected. Applying workaround.')
environment['LD_PRELOAD'] = str(jemalloc)
if 'emoji' in args and len(args) > 2:
parsed_args = args[2:]
args = args[:2]
for arg in parsed_args:
path = Path(arg).resolve()
if path.exists():
arg = str(path)
args.append(arg)
proc = Popen([str(config.ruby), str(tootctl), *args], env=environment, cwd=config.mastodon)
try:
proc.wait()
except KeyboardInterrupt:
proc.terminate()