NEW: basic setup with argument parser

This commit is contained in:
Jean-Claude 2022-10-30 21:47:09 +01:00
commit 586de38024
Signed by: jeanclaude
GPG Key ID: 8A300F57CBB9F63E
5 changed files with 284 additions and 0 deletions

3
mia/__init__.py Normal file
View File

@ -0,0 +1,3 @@
__description__ = "A tool to help you manage your photo archive."
__version_info__ = (0, 0, 1)
__version__ = ".".join(str(num) for num in __version_info__)

62
mia/__main__.py Normal file
View File

@ -0,0 +1,62 @@
"""Entry point for mia."""
import sys
import argparse
from typing import List, Optional
import logging
from pathlib import Path
from mia import parser
from mia.parser import Subparser
_log = logging.getLogger(__name__)
def main() -> int:
args = doSetup(sys.argv[1:])
out = customTypes.Exit.success
match args.command:
case Subparser.Import:
_log.debug("Start import handler")
case Subparser.Activate:
_log.debug("Start activate handler")
case Subparser.Deactivate:
_log.debug("Start deactivate handler")
case Subparser.List:
_log.debug("Start list handler")
return out
def doSetup(argv: List[str]) -> argparse.Namespace:
"""Setup that is done before the app is run.
Includes parsing the command line arguments and setting up the logger.
Args:
argv: List of arguments passed to the application.
Returns:
Parsed Arguments.
"""
args = parser.getArgparser().parse_args(argv)
if args.version:
import mia.version
print(mia.version.info())
sys.exit(customTypes.Exit.success)
logging.basicConfig(stream=sys.stdout, level=args.logLevel)
_log.debug(f"Start mia with {argv}")
return args
if __name__ == "__main__":
sys.exit(main())

187
mia/parser.py Normal file
View File

@ -0,0 +1,187 @@
import argparse
from pathlib import Path
from typing import List
import contextlib
import logging
import enum
import mia
@enum.unique
class Subparser(enum.StrEnum):
Import = "import"
Activate = "activate"
Deactivate = "deactivate"
List = "list"
def getArgparser() -> argparse.ArgumentParser:
"""Get the argument parser."""
parser = argparse.ArgumentParser(prog=mia.__name__, description=mia.__description__)
parser.add_argument(
"-v",
"--version",
action="store_true",
help="Print version information and exit",
)
parser.add_argument(
"--config",
type=existingFile,
metavar="FILE",
help="Use FILE as local configuration file",
)
parser.add_argument(
"--log-level",
type=loglevel,
metavar="LEVEL",
help="Set log level to LEVEL",
default="INFO",
dest="logLevel",
)
devel = parser.add_argument_group("development arguments")
devel.add_argument(
"--debug",
nargs="+",
metavar="MODULE",
default=(),
help="Show debug log messages of MODULE",
)
subparsers = parser.add_subparsers(dest="command")
# Import Parser
importParser = subparsers.add_parser(
Subparser.Import, help="Create new image import"
)
importParser.add_argument(
"-i",
"--identifier",
metavar="IDENTIFIER",
help="Specifie identifier for the import",
)
importParser.add_argument(
"-s",
"--schema",
type=validSchema,
metavar="SCHEMA",
help="Specifie schema for the import",
)
importParser.add_argument(
"-c",
"--current",
action="store_true",
help="Combine this import with the currently active import",
)
importParser.add_argument(
"imagePath",
nargs="+",
type=validImagePath,
metavar="IMAGE_PATH",
help="Images to import",
)
# Activate Parser
activateParser = subparsers.add_parser(
Subparser.Activate, help="Activate a pending import"
)
activateParser.add_argument(
"IMPORT", type=existingBranch, help="Switch to import IMPORT"
)
# Deactivate Parser
activateParser = subparsers.add_parser(
Subparser.Deactivate, help="Deactivate current import"
)
activateParser.set_defaults(deactivate=True)
# List Parser
activateParser = subparsers.add_parser(
Subparser.List, help="List all pending imports"
)
activateParser.set_defaults(list=True)
return parser
def loglevel(value: str) -> int:
"""Check if an argument value is a valid log level.
Args:
value: Value given to commandline option as string.
Returns:
Value as logging level.
"""
with contextlib.suppress(AttributeError):
return getattr(logging, value.upper())
raise argparse.ArgumentTypeError(f"Invalid log level '{value}'")
def existingFile(value: str) -> Path:
"""Check if an argument value is an existing file.
Args:
value: Value given to commandline option as string.
Returns:
Path to the file if it exists.
"""
path = Path(value).expanduser().resolve()
if path.is_file():
return path
raise argparse.ArgumentTypeError(f"No file called '{value}'")
def existingBranch(value: str) -> str:
"""Check if an argument value is an existing branch.
Args:
value: Value given to the commandline option as string.
Returns:
Branch name if it exists.
"""
# TODO: implement logic
return True
def existingImport(value: str) -> str:
"""Check if an argument value is an existing branch of a valid import.
Args:
value: Value given to the commandline option as string.
Returns:
Branch name of import if it exists.
"""
# TODO: implement logic
return True
def validSchema(value: str) -> str:
"""Check if an argument value is an defined schema.
Args:
value: Value given to the command line option as string.
Returns:
Schema name if exists.
"""
# TODO: implement logic
def validImagePath(value: str) -> Path:
"""Check if an argument value is an path to a image.
Args:
value: Value given to the command line option as string.
Returns:
Image path if exists.
"""
# TODO: implement logic
return value

24
mia/version.py Normal file
View File

@ -0,0 +1,24 @@
"""Version and configuration related information."""
import sys
import mia
def info() -> str:
"""Retrieve version information.
Returns:
Mia version and version of different dependencies.
"""
return (
f"Mia: {mia.__version__}\n\n"
f"Python: {_pythonVersion()}"
# f"Git: {}"
# f"Git-Annex: {}"
)
def _pythonVersion() -> str:
"""Get Version of Python."""
return f"{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}"

8
setup.py Normal file
View File

@ -0,0 +1,8 @@
from setuptools import setup
setup(
name="mia",
description="bla", # Get from init
version="0", # Get from init
)