71 lines
2.5 KiB
Python
71 lines
2.5 KiB
Python
import click
|
|
from pathlib import Path
|
|
import logging
|
|
from logging.handlers import RotatingFileHandler
|
|
import sys
|
|
from iottb.models.iottb_config import IottbConfig
|
|
from iottb.definitions import DB_NAME, CFG_FILE_PATH
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
@click.command()
|
|
@click.option('-d', '--dest', type=click.Path(exists=True, file_okay=False, dir_okay=True),
|
|
help='Location to put (new) iottb database')
|
|
@click.option('-n', '--name', default=DB_NAME, type=str,
|
|
help='Name of new database.')
|
|
@click.option('--update-default/--no-update-default', default=True,
|
|
help='If new db should be set as the new default')
|
|
@click.pass_context
|
|
def init_db(ctx, dest, name, update_default):
|
|
logger.info('init-db invoked')
|
|
config = ctx.obj['CONFIG']
|
|
logger.debug(f'str(config)')
|
|
# Use the default path from config if dest is not provided
|
|
known_dbs = config.get_known_databases()
|
|
logger.debug(f'Known databases: {known_dbs}')
|
|
if name in known_dbs:
|
|
dest = config.get_database_location(name)
|
|
if Path(dest).joinpath(name).is_dir():
|
|
click.echo(f'A database {name} already exists.')
|
|
logger.debug(f'DB {name} exists in {dest}')
|
|
click.echo(f'Exiting...')
|
|
sys.exit()
|
|
logger.debug(f'DB name {name} registered but does not exist.')
|
|
if not dest:
|
|
logger.info('No dest set, choosing default destination.')
|
|
dest = Path(config.default_db_location)
|
|
|
|
db_path = Path(dest).joinpath(name)
|
|
logger.debug(f'Full path for db {str(db_path)}')
|
|
# Create the directory if it doesn't exist
|
|
db_path.mkdir(parents=True, exist_ok=True)
|
|
logger.info(f"mkdir {db_path} successful")
|
|
click.echo(f'Created {db_path}')
|
|
|
|
# Update configuration
|
|
config.set_database_location(name, str(dest))
|
|
if update_default:
|
|
config.set_default_database(name, str(dest))
|
|
config.save_config()
|
|
logger.info(f"Updated configuration with database {name} at {db_path}")
|
|
|
|
|
|
# @click.group('config')
|
|
# @click.pass_context
|
|
# def cfg(ctx):
|
|
# pass
|
|
#
|
|
# @click.command('set', help='Set the location of a database.')
|
|
# @click.argument('database', help='Name of database')
|
|
# @click.argument('location', help='Where the database is located (i.e. its parent directory)')
|
|
# @click.pass_context
|
|
# def set(ctx, key, value):
|
|
# click.echo(f'Setting {key} to {value} in config')
|
|
# config = ctx.obj['CONFIG']
|
|
# logger.warning('No checks performed!')
|
|
# config.set_database_location(key, value)
|
|
# config.save_config()
|
|
|
|
|