Files
pybsv/src/bsv/main.py
2023-11-29 23:25:27 +01:00

96 lines
2.7 KiB
Python

# bsv - Backup, Synchronization, Versioning
# Copyright (C) 2023 Simon Boyé
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <https://www.gnu.org/licenses/>.
from __future__ import annotations
from argparse import ArgumentParser
import os.path
from pathlib import Path
import sys
from textwrap import dedent
from bsv import __version__
from bsv.cli import get_error_console, init_consoles
from bsv.command import init_commands
from bsv.util import default_bsv_config_path
def make_parser(
prog: str = "",
exit_on_error: bool = True,
) -> ArgumentParser:
parent_parser = ArgumentParser(add_help=False)
parent_parser.add_argument(
"--color",
default = "auto",
choices = ("always", "auto", "never"),
help = dedent("""
Force or disable colors, or auto-detect terminal support.
""").strip(),
)
parent_parser.add_argument(
"--config",
default = default_bsv_config_path(),
type = Path,
dest = "config_path",
help = dedent("""
Bsv config path. Overrides default paths and BSV_CONFIG environment variable.
""").strip(),
)
parser = ArgumentParser(
prog = prog or os.path.basename(sys.argv[0]),
description = dedent("""
bsv - Backup, Synchronization, Versioning.
""").strip(),
parents = [parent_parser],
exit_on_error = exit_on_error,
)
parser.add_argument(
"--version",
action = "version",
version = f"bsv version {__version__}",
)
init_commands(parser, [parent_parser])
return parser
def main(
args: list[str] | None = None,
prog: str = "",
exit_on_error: bool = True,
) -> int:
parser = make_parser(
prog = prog or os.path.basename(sys.argv[0]),
exit_on_error = exit_on_error,
)
arg_dict = vars(parser.parse_args(args or sys.argv[1:]))
color = arg_dict.pop("color")
init_consoles(color=color)
command = arg_dict.pop("command")
try:
return command(**arg_dict)
except Exception as err:
get_error_console().print_exception()
except KeyboardInterrupt:
return 130
return 0