Compare commits

..

No commits in common. "e36e5a1428bba003bd02175ba0de21f0cd910731" and "58e4e42b301971b575f42a3f8738229709d7e24e" have entirely different histories.

5 changed files with 18 additions and 85 deletions

View File

@ -1,18 +1,11 @@
import argparse import argparse
import configparser
import logging
import traceback
import sys import sys
from pathlib import Path
try: try:
from importlib import metadata from importlib import metadata
except ImportError: # Python <3.8 except ImportError: # Python <3.8
import importlib_metadata as metadata import importlib_metadata as metadata
CONFIG_FILE = '~/.negromate/config.ini'
def main(): def main():
""" """
Build parser for all the commands and launch appropiate command. Build parser for all the commands and launch appropiate command.
@ -22,31 +15,25 @@ def main():
* name: String with the command name. Will be used for * name: String with the command name. Will be used for
argparse subcommand. argparse subcommand.
* help_text: String with the help text. * help_text: String with the help text.
* initial_config: Dict for initial configuration of commands.
* options: Function to build the parser of the command. Takes * options: Function to build the parser of the command. Takes
two parametters, the argparser parser instance for this one parametter, the argparser parser instance for this
subcommand and the ConfigParser instance with all the subcommand.
configuration. * run: Function that runs the actual command. Takes one
* run: Function that runs the actual command. Takes two parametter, the Namespace with the arguments.
parametters, the argparse Namespace with the arguments and
the ConfigParser with all the configuration.
Minimal module example: Minimal module example:
# hello_world.py # hello_world.py
name = 'hello' name = 'hello'
help_text = 'Sample command' help_text = 'Sample command'
initial_config = {
'who': 'World',
}
def options(parser, config, **kwargs): def options(parser):
parser.add_argument( parser.add_argument(
'-w', '--who', default=config['hello']['who'], '-w', '--who', default='World'
help="Who to say hello, defaults to '{}'".format(config['hello']['who']) help="Who to say hello, defaults to 'World'"
) )
def run(args, **kwargs): def run(args):
print("Hello {}".format(args.who)) print("Hello {}".format(args.who))
To add more commands to negromate register 'negromate.commands' To add more commands to negromate register 'negromate.commands'
@ -63,52 +50,22 @@ def main():
args = sys.argv.copy() args = sys.argv.copy()
sys.argv = args[:1] sys.argv = args[:1]
# Load commands from entry_point
entry_points = metadata.entry_points().get('negromate.commands', []) entry_points = metadata.entry_points().get('negromate.commands', [])
for entry_point in entry_points: for entry_point in entry_points:
try: commands.append(entry_point.load())
command = entry_point.load()
except Exception as e:
traceback.print_exc()
print(e)
continue
commands.append(command)
# Load initial configuration for commands
initial_config = {
'global': {
'song_folder': '~/negro_mate/bideoak/',
'lyrics_file': '~/negro_mate/libreto/libreto.pdf',
}
}
for command in commands:
if hasattr(command, 'initial_config'):
initial_config[command.name] = command.initial_config
# Load configuration
config = configparser.ConfigParser()
config.read_dict(initial_config)
config.read(Path(CONFIG_FILE).expanduser())
# Build parser
parser = argparse.ArgumentParser() parser = argparse.ArgumentParser()
parser.add_argument(
'-v', '--verbose', action='store_true',
help="Display informational messages.")
parser.set_defaults(command=None) parser.set_defaults(command=None)
subparsers = parser.add_subparsers() subparsers = parser.add_subparsers()
for command in commands: for command in commands:
command_parser = subparsers.add_parser(command.name, help=command.help_text) command_parser = subparsers.add_parser(command.name, help=command.help_text)
command_parser.set_defaults(command=command.name) command_parser.set_defaults(command=command.name)
command.options(parser=command_parser, config=config) command.options(command_parser)
# Run command
args = parser.parse_args(args[1:]) args = parser.parse_args(args[1:])
if args.verbose:
logging.basicConfig(level=logging.DEBUG)
if args.command is None: if args.command is None:
parser.print_usage() parser.print_usage()
else: else:
for command in commands: for command in commands:
if args.command == command.name: if args.command == command.name:
command.run(args=args, config=config) command.run(args)

View File

@ -1,21 +0,0 @@
import sys
from pathlib import Path
name = 'config'
help_text = 'Write the configuration'
initial_config = {
'file': '~/.negromate/config.ini',
}
def options(parser, config, **kwargs):
parser.add_argument(
'-f', '--file', type=Path,
default=config['config']['file'],
help="Configuration file, defaults to {}".format(
config['config']['file']))
def run(args, config, **kwargs):
with args.file.expanduser().open('w') as f:
config.write(f)

View File

@ -7,16 +7,14 @@ name = 'songs'
help_text = 'Update song database' help_text = 'Update song database'
def options(parser, config, **kwargs): def options(parser):
parser.add_argument( parser.add_argument(
'-s', '--song_folder', type=Path, 'song_folder', type=Path,
default=config['global']['song_folder'], help="Folder with the song database.")
help="Folder with the song database, defaults to {}".format(
config['global']['song_folder']))
def run(args, **kwargs): def run(args):
songs, pending_songs = load_songs(args.song_folder.expanduser()) songs, pending_songs = load_songs(args.song_folder)
print( print(
"#######\n" "#######\n"
" Songs\n" " Songs\n"

View File

@ -6,7 +6,7 @@ name = 'thumbnail'
help_text = 'Generate cover and thumbnail for a video.' help_text = 'Generate cover and thumbnail for a video.'
def options(parser, config, **kwargs): def options(parser):
parser.add_argument( parser.add_argument(
'video', help="Video of the song.", type=Path) 'video', help="Video of the song.", type=Path)
parser.add_argument( parser.add_argument(
@ -14,7 +14,7 @@ def options(parser, config, **kwargs):
help='Take snapshot at this second.') help='Take snapshot at this second.')
def run(args, **kwargs): def run(args):
video = args.video video = args.video
cover = video.parent / 'cover.jpg' cover = video.parent / 'cover.jpg'
thumbnail = video.parent / 'thumb.jpg' thumbnail = video.parent / 'thumb.jpg'

View File

@ -32,7 +32,6 @@ console_scripts =
negromate = negromate.songs.commands:main negromate = negromate.songs.commands:main
negromate.commands = negromate.commands =
songs = negromate.songs.commands.songs songs = negromate.songs.commands.songs
config = negromate.songs.commands.config
thumbnail = negromate.songs.commands.thumbnail thumbnail = negromate.songs.commands.thumbnail
[bdist_wheel] [bdist_wheel]