Commit b15392f4 authored by Matt Traudt's avatar Matt Traudt
Browse files

Prompt before overwriting config.ini

GH: closes #86
parent 430fe9be
from sbws.globals import (is_initted, fail_hard, touch_file)
from sbws.util.config import get_user_example_config
from sbws.util.userquery import query_yes_no
from argparse import ArgumentDefaultsHelpFormatter
import os
import logging
......@@ -23,10 +24,18 @@ def main(args, conf):
log.info('Creating %s', args.directory)
os.makedirs(args.directory, exist_ok=False)
# Create config.log.ini ####
touch_file(os.path.join(args.directory, 'config.log.ini'))
config_fname = os.path.join(args.directory, 'config.ini')
# Create config.ini ####
fname = os.path.join(args.directory, 'config.ini')
if os.path.exists(fname) and not os.path.isfile(fname):
fail_hard('Don\'t know how to handle %s existing as a non-file', fname)
if os.path.isfile(fname) and not query_yes_no(
'Is it okay to overwrite {}?'.format(fname), default=None):
fail_hard('Cannot continue')
c = get_user_example_config()
c['paths']['sbws_home'] = args.directory
log.info('Creating %s based on example config', config_fname)
with open(config_fname, 'wt') as fd:
log.info('Creating %s based on example config', fname)
with open(fname, 'wt') as fd:
c.write(fd)
......@@ -29,7 +29,7 @@ def is_initted(d):
conf_fnames = [os.path.join(d, 'config.ini'),
os.path.join(d, 'config.log.ini')]
for fname in conf_fnames:
if not os.path.exists(fname):
if not os.path.isfile(fname):
return False
return True
......
# Based on https://stackoverflow.com/a/3041990
def query_yes_no(question, default='yes'):
'''
Ask a yes/no question via input() and return the user's answer.
:param str question: Prompt given to the user.
:param str default: The assumed answer if th user just hits **Enter**. It
must be ``'yes'`` (the default if no default is given), ``'no'``, or
``None`` (meaning an answer is required from the user).
:returns: ``True`` if we ended up with a 'yes' answer, otherwise
``False``.
'''
valid = {'yes': True, 'y': True, 'ye': True, 'no': False, 'n': False}
if default is None:
prompt = ' [y/n] '
elif default == 'yes':
prompt = ' [Y/n] '
elif default == 'no':
prompt = ' [y/N] '
else:
raise ValueError('invalid default answer: "%s"' % default)
while True:
print(question + prompt, end='')
choice = input().lower()
if default is not None and choice == '':
return valid[default]
elif choice in valid:
return valid[choice]
else:
print('Please respond with "yes" or "no" (or "y" or "n").\n')
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment