improve tootctl some more

This commit is contained in:
Izalia Mae 2021-09-08 20:01:45 -04:00
parent 20cf654b38
commit cd0065f184

View file

@ -1,23 +1,11 @@
#!/usr/bin/env python3
__software__ = 'PyTootctl'
__version__ = '0.1.1'
__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'
## Usage:
## Toss in a directory in path (optional) and run like any other program. ex: tootctl.py media remove --days=4
## PyTootctl-specific commands:
## tootctl.py set {key} {value}: set a config option
## tootctl.py config: list the current config. Any invalid paths will be noted.
## Note:
## This can be safely ran from cron or other environments that don't import your .bashrc or .profile.
## Todo:
## Add help command
import json, logging, os, sys
@ -28,12 +16,8 @@ from subprocess import Popen
home = Path('~').expanduser()
jemalloc = Path('/usr/lib/x86_64-linux-gnu/libjemalloc.so.2')
if str(home) == os.getcwd():
cfg_path = Path('pytootctl.json').resolve()
else:
cfg_path = home.joinpath('.config/barkshark/pytootctl.json')
cfg_path = home.joinpath('.config/barkshark/pytootctl.json')
name = Path(__file__).name
class Config(dict):
@ -61,9 +45,12 @@ class Config(dict):
if value == 'default':
value = self.defaults[key]
if key in ['ruby', 'mastodon']:
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}')
@ -121,30 +108,51 @@ class Command:
def __getitem__(self, key):
return getattr(self, f'cmd_{key}')
try:
return getattr(self, f'cmd_{key}')
except AttributeError:
raise InvalidCommandError(f'Not a valid command: {key}')
def cmd_set(self, key, value):
logging.debug(f'Setting {key}: {value}')
config[key] = value
config.write()
self.cmd_config()
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]}')
def cmd_config(self):
print('Current config:')
elif not key:
print('Current config:')
for k,v in config.items():
line = f' {k}: {v}'
for k,v in config.items():
line = f' {k}: {v}'
if isinstance(v, Path) and not v.exists():
line += ' (missing)'
if isinstance(v, Path) and not v.exists():
line += ' (missing)'
print(line)
print(line)
def cmd_usage(self, command=None):
print('Not implemented yet')
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():
@ -153,6 +161,9 @@ def debian_11_check():
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', '')
@ -165,6 +176,10 @@ def debian_11_check():
return info['ID'].lower() == 'debian' and info['VERSION_ID'] == "11"
class InvalidCommandError(Exception):
pass
if __name__ == '__main__':
logging.basicConfig()
@ -175,7 +190,7 @@ if __name__ == '__main__':
try:
Command(args)
sys.exit(0)
except AttributeError:
except InvalidCommandError:
pass
if not config.ruby.exists():
@ -196,6 +211,18 @@ if __name__ == '__main__':
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: