Files
tembo/tembo/cli.py
2021-11-01 19:58:32 +00:00

193 lines
6.0 KiB
Python

import pathlib
import click
import tembo
from tembo.journal import pages
from tembo import exceptions
CONTEXT_SETTINGS = dict(help_option_names=["-h", "--help"])
@click.group(context_settings=CONTEXT_SETTINGS, options_metavar="<options>")
@click.version_option(
tembo.__version__,
"-v",
"--version",
prog_name="Tembo",
message=f"Tembo v{tembo.__version__} 🐘",
)
def run():
"""
Tembo - an organiser for work notes.
"""
@click.command(options_metavar="<options>", name="list")
def list_all():
"""List all scopes defined in the config.yml"""
_all_scopes = [user_scope["name"] for user_scope in tembo.CONFIG.scopes]
tembo.logger.info(
"%s names found in config.yml: '%s'", len(_all_scopes), "', '".join(_all_scopes)
)
raise SystemExit(0)
@click.command(options_metavar="<options>")
@click.argument("scope", metavar="<scope>")
@click.argument(
"inputs",
nargs=-1,
metavar="<inputs>",
)
@click.option("--dry-run", is_flag=True, default=False)
@click.option("--example", is_flag=True, default=False)
def new(scope, inputs, dry_run, example):
r"""
Create a new page.
<scope>\n
The name of the scope in the config.yml.
<inputs>\n
Any input token values that are defined in the config.yml for this scope.
Accepts multiple inputs separated by a space.
Example: tembo new meeting my_presentation
"""
# get the name from the tembo config.yml
_cli_verify_name_exists(scope)
# get the scope information from the tembo config.yml
config_scope = _cli_get_config_scope(scope)
# print the example to the user
if example:
tembo.logger.info(
"Example for 'tembo new %s': %s",
config_scope["name"],
config_scope["example"]
if isinstance(config_scope["example"], str)
else "No example in config.yml",
)
raise SystemExit(0)
# if the name is in the config.yml, create the scoped page
page_creator_options = pages.PageCreatorOptions(
base_path=tembo.CONFIG.base_path,
page_path=config_scope["path"],
filename=config_scope["filename"],
extension=config_scope["extension"],
name=config_scope["name"],
example=config_scope["example"],
user_input=inputs,
template_filename=config_scope["template_filename"],
template_path=tembo.CONFIG.template_path,
)
try:
scoped_page = pages.ScopedPageCreator(page_creator_options).create_page()
except exceptions.BasePathDoesNotExistError as base_path_does_not_exist_error:
tembo.logger.critical(base_path_does_not_exist_error)
raise SystemExit(1) from base_path_does_not_exist_error
except exceptions.TemplateFileNotFoundError as template_file_not_found_error:
tembo.logger.critical(template_file_not_found_error.args[0])
raise SystemExit(1) from template_file_not_found_error
except exceptions.MismatchedTokenError as mismatched_token_error:
if config_scope["example"] is not None:
tembo.logger.critical(
"Your tembo config.yml/template specifies %s input tokens, you gave %s. Example: %s",
mismatched_token_error.expected,
mismatched_token_error.given,
config_scope["example"],
)
raise SystemExit(1) from mismatched_token_error
tembo.logger.critical(
"Your tembo config.yml/template specifies %s input tokens, you gave %s",
mismatched_token_error.expected,
mismatched_token_error.given,
)
raise SystemExit(1) from mismatched_token_error
if dry_run:
click.echo(cli_message(f"{scoped_page.path} will be created"))
raise SystemExit(0)
try:
scoped_page.save_to_disk()
raise SystemExit(0)
except exceptions.ScopedPageAlreadyExists as scoped_page_already_exists:
cli_message(f"File {scoped_page_already_exists}")
raise SystemExit(0) from scoped_page_already_exists
def _cli_verify_name_exists(scope: str) -> None:
_name_found = scope in [
user_scope["name"] for user_scope in tembo.CONFIG.scopes
]
if _name_found:
return
if len(tembo.CONFIG.scopes) > 0:
# if the name is missing in the config.yml, raise error
cli_message(f"Command {scope} not found in config.yml.")
raise SystemExit(0)
# raise error if no config.yml found
if pathlib.Path(tembo.CONFIG.config_path).exists():
tembo.logger.critical(
"Config.yml found in %s is empty - exiting", tembo.CONFIG.config_path
)
else:
tembo.logger.critical(
"No config.yml found in %s - exiting", tembo.CONFIG.config_path
)
raise SystemExit(1)
def _cli_get_config_scope(scope: str) -> dict:
config_scope = {}
for option in [
"name",
"example",
"path",
"filename",
"extension",
"template_filename",
]:
try:
config_scope.update(
{
option: str(user_scope[option])
for user_scope in tembo.CONFIG.scopes
if user_scope["name"] == scope
}
)
except KeyError as key_error:
if key_error.args[0] in ["example", "template_filename"]:
config_scope.update({key_error.args[0]: None})
continue
tembo.logger.critical(
"Key %s not found in config. yml - exiting", key_error
)
raise SystemExit(1) from key_error
return config_scope
def cli_message(message: str) -> None:
click.echo(f"[TEMBO] {message} 🐘")
run.add_command(new)
run.add_command(list_all)
if __name__ == "__main__":
# new(["meeting", "robs presentation", "meeting on gcp"])
new(["meeting", "a", "b", "c", "d"])
# new(["meeting", "robs presentation"])
# pyinstaller
# if getattr(sys, "frozen", False):
# run(sys.argv[1:])
# run(sys.argv[1:])