From 7478bc28781815d14706e9d9555629f8bc5e5c23 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sergio=20Alvari=C3=B1o?= Date: Thu, 13 Jan 2022 10:45:49 +0100 Subject: [PATCH] Add config file and argparse - '~/.config/mach5/config.ini' will be default config file, can be changed in command line - '~/.config/mach5/menu.yml' is the default menu file. Can be changed in command line parameters or in config file. Comman line parameters take preference. --- README.md | 10 +++++++++- mach5 | 49 ++++++++++++++++++++++++++++++++++++++++++++++--- 2 files changed, 55 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index 01d703f..3be7718 100644 --- a/README.md +++ b/README.md @@ -5,4 +5,12 @@ A chords app for Linux ## TODO -- More checks on command contructor +- More checks on Command constructor +- Add checks on Menu constructor +- Add config +- Add logger + +## Referencias + +- [Autokey](https://github.com/autokey/) + diff --git a/mach5 b/mach5 index 2cf0f37..8c5994c 100755 --- a/mach5 +++ b/mach5 @@ -2,7 +2,50 @@ from machlib.menu import Menu, get_data_from -# import subprocess -# from getkey import getkey, keys +import argparse +from configparser import ConfigParser, ExtendedInterpolation +import os +import os.path +import errno -Menu(get_data_from('~/.config/mach5/menu.yml')).get_command().execute() +# default configuration and menu files +_default_configuration_file = '~/.config/mach5/config.ini' + + +# -------------------- MAIN -------------------- + +# Parse command line options +arg_parser = argparse.ArgumentParser( + description='Our simple chords application') +arg_parser.add_argument('-c', '--cfg', help='Config ini file') +arg_parser.add_argument('-m', '--menu', help='Menu yaml file') + +args = arg_parser.parse_args() + +# load config file +cfg_file = args.cfg if args.cfg else _default_configuration_file +cfg_file = os.path.expanduser(cfg_file) + +if not os.path.exists(cfg_file): + raise FileNotFoundError(errno.ENOENT, + os.strerror(errno.ENOENT), cfg_file) + + +_configuration = ConfigParser(interpolation=ExtendedInterpolation()) +found = _configuration.read(cfg_file) + +# [TODO] next lines should raise an error +if (not found): + print('[ERROR] Config file not found') + raise FileNotFoundError + +menu_file = args.menu if args.menu\ + else _configuration['General']['default_menu_file'] +menu_file = os.path.expanduser(menu_file) + +if not os.path.exists(menu_file): + raise FileNotFoundError(errno.ENOENT, + os.strerror(errno.ENOENT), menu_file) + + +Menu(get_data_from(menu_file)).get_command().execute()