summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorElena ``of Valhalla'' Grandi <valhalla@trueelena.org>2022-08-04 18:08:52 +0200
committerElena ``of Valhalla'' Grandi <valhalla@trueelena.org>2022-08-04 18:08:52 +0200
commitb099f593d5227453b999271ec2f00d8e81ab5b86 (patch)
tree7e20c335bd6ff89c2bb15122b5abef2cb6351f5e
parent1fe460ea2d1339358ea9cd4c909151ed7eccdcfc (diff)
Use hazwaz to generate command line commands
-rw-r--r--CHANGELOG.rst3
-rw-r--r--lesana/command.py117
-rwxr-xr-xscripts/lesana26
-rw-r--r--setup.py1
4 files changed, 34 insertions, 113 deletions
diff --git a/CHANGELOG.rst b/CHANGELOG.rst
index a52ce38..19d0926 100644
--- a/CHANGELOG.rst
+++ b/CHANGELOG.rst
@@ -5,6 +5,9 @@
Unreleased
==========
+* Command line code has been split in the hazwaz library.
+* Code cleanup.
+
0.9.1
=====
diff --git a/lesana/command.py b/lesana/command.py
index ac7eba2..8c0ac15 100644
--- a/lesana/command.py
+++ b/lesana/command.py
@@ -1,9 +1,10 @@
import argparse
import logging
import os
-import subprocess
import sys
+import hazwaz
+
try:
import argcomplete
except ImportError:
@@ -14,110 +15,20 @@ from . import Collection, Entry, TemplatingError
logger = logging.getLogger(__name__)
-def _get_first_docstring_line(obj):
- try:
- return obj.__doc__.split('\n')[1].strip()
- except (AttributeError, IndexError):
- return None
-
-
-class MainCommand:
- commands = ()
-
- def _main(self, args):
- self.parser.print_help()
-
- def main(self):
- desc = _get_first_docstring_line(self)
- self.parser = argparse.ArgumentParser(description=desc)
- self.parser.add_argument('--verbose', '-v',
- action='store_true',
- help="Display debug messages")
- self.parser.set_defaults(func=self._main)
- self.subparsers = self.parser.add_subparsers()
- for name, sub in self.commands:
- sub_help = _get_first_docstring_line(sub)
- s_parser = self.subparsers.add_parser(
- name,
- help=sub_help,
- description=sub.__doc__,
- )
- for arg in sub.arguments:
- s_parser.add_argument(*arg[0], **arg[1])
- s_parser.set_defaults(func=sub._main)
- if argcomplete:
- argcomplete.autocomplete(self.parser)
- self.args = self.parser.parse_args()
-
- if self.args.verbose:
- logging.getLogger('lesana').setLevel(logging.DEBUG)
-
- self.args.func(self.args)
-
-
-class Command:
+class Command(hazwaz.Command):
def __init__(self, collection_class=Collection, entry_class=Entry):
+ super().__init__()
self.collection_class = collection_class
self.entry_class = entry_class
- def _main(self, args):
- self.args = args
- self.main()
-
- def edit_file_in_external_editor(self, filepath):
- # First we try to use $EDITOR
- editor = os.environ.get('EDITOR')
- if editor:
- try:
- subprocess.call([editor, filepath])
- except FileNotFoundError as e:
- if editor in str(e):
- logger.info(
- 'Could not open file {} with $EDITOR (currently {})'
- .format(
- filepath, editor
- )
- )
- else:
- logger.warning("Could not open file {}".format(filepath))
- return False
- else:
- return True
- # then we try to use sensible-editor (which should be available on
- # debian and derivatives)
- try:
- subprocess.call(['sensible-editor', filepath])
- except FileNotFoundError as e:
- if 'sensible-editor' in e.strerror:
- logger.debug(
- "Could not open file {} with editor: sensible-editor"
- .format(filepath)
- )
- else:
- logger.warning("Could not open file {}".format(filepath))
- return False
- else:
- return True
- # and finally we fallback to vi, because ed is the standard editor,
- # but that would be way too cruel, and vi is also in posix
- try:
- subprocess.call(['vi', filepath])
- except FileNotFoundError as e:
- if 'vi' in e.strerror:
- logger.warning(
- "Could not open file {} with any known editor".format(
- filepath
- )
- )
- return False
- else:
- logger.warning("Could not open file {}".format(filepath))
- return False
- else:
- return True
+ def add_arguments(self, parser: argparse.ArgumentParser):
+ # compatibility with the old way to add arguments: for new
+ # commands override add_arguments directly
+ for arg in self.arguments:
+ parser.add_argument(*arg[0], **arg[1])
-class New(Command):
+class New(Command, hazwaz.mixins.ExternalEditorMixin):
"""
Create a new entry
"""
@@ -149,7 +60,7 @@ class New(Command):
print(saved_entry)
-class Edit(Command):
+class Edit(Command, hazwaz.mixins.ExternalEditorMixin):
"""
Edit a lesana entry
"""
@@ -358,6 +269,8 @@ class GetValues(Command):
"""
List all values for one field, with entry counts.
"""
+ name = "get-values"
+
arguments = [
(
['--collection', '-c'],
@@ -451,7 +364,7 @@ class Export(Command):
sys.exit(1)
-class Init(Command):
+class Init(Command, hazwaz.mixins.ExternalEditorMixin):
"""
Initialize a lesana collection
"""
@@ -482,6 +395,8 @@ class Remove(Command):
"""
Remove an entry from a collection
"""
+ name = "rm"
+
arguments = [
(
['--collection', '-c'],
diff --git a/scripts/lesana b/scripts/lesana
index ed6084a..5c84d56 100755
--- a/scripts/lesana
+++ b/scripts/lesana
@@ -4,25 +4,27 @@ Lesana Command Line interface
"""
import logging
+import hazwaz
+
import lesana.command
-class Lesana(lesana.command.MainCommand):
+class Lesana(hazwaz.MainCommand):
"""
Manage collections
"""
commands = (
- ("new", lesana.command.New()),
- ("edit", lesana.command.Edit()),
- ("show", lesana.command.Show()),
- ("index", lesana.command.Index()),
- ("search", lesana.command.Search()),
- ("get-values", lesana.command.GetValues()),
- ("update", lesana.command.Update()),
- ("export", lesana.command.Export()),
- ("init", lesana.command.Init()),
- ("rm", lesana.command.Remove()),
+ lesana.command.New(),
+ lesana.command.Edit(),
+ lesana.command.Show(),
+ lesana.command.Index(),
+ lesana.command.Search(),
+ lesana.command.GetValues(),
+ lesana.command.Update(),
+ lesana.command.Export(),
+ lesana.command.Init(),
+ lesana.command.Remove(),
)
@@ -36,4 +38,4 @@ if __name__ == "__main__":
logger.addHandler(ch)
logger.setLevel(logging.INFO)
- Lesana().main()
+ Lesana().run()
diff --git a/setup.py b/setup.py
index edbec63..ec85f17 100644
--- a/setup.py
+++ b/setup.py
@@ -21,6 +21,7 @@ setup(
'ruamel.yaml',
'jinja2',
'python-dateutil',
+ 'hazwaz',
],
python_requires='>=3',
# Metadata