1
0
Fork 0
mirror of https://github.com/Findus23/invoices.git synced 2024-09-19 15:13:47 +02:00
invoices/utils.py

72 lines
2 KiB
Python
Raw Normal View History

2018-03-04 21:04:54 +01:00
import os
2019-10-09 19:36:09 +02:00
import readline
2018-03-13 22:03:13 +01:00
from glob import glob
2018-03-04 21:04:54 +01:00
2018-03-13 22:03:13 +01:00
import dateparser
2018-03-04 21:04:54 +01:00
import yaml
2019-10-09 19:36:09 +02:00
# noinspection PyStatementEffect
readline # this does nothing but make sure the import readline is not removed accidently
2018-03-04 21:04:54 +01:00
def load_yaml(filename):
with open(filename, 'r') as stream:
2019-10-09 20:16:08 +02:00
return yaml.safe_load(stream)
2018-03-04 21:04:54 +01:00
2018-03-13 22:03:13 +01:00
def save_yaml(data, filename):
with open(filename, 'w') as outfile:
yaml.dump(data, outfile, default_flow_style=False)
2018-03-04 21:04:54 +01:00
def remove_tmp_files(base):
for ext in ["aux", "log"]:
os.remove(base + "." + ext)
2018-03-13 22:03:13 +01:00
def get_possible_recipents():
return [os.path.splitext(os.path.basename(file))[0] for file in glob("recipients/*.yaml")]
def ask(question, validator=None, default=None, set=None):
while True:
string = question + (" [{default}]".format(default=default) if default else "") + ": "
answer = input(string)
if answer == "":
if default:
answer = default
print("\033[F" + string + str(answer))
else:
continue
if validator == "float":
try:
answer = float(answer)
except ValueError:
continue
if validator == "money":
try:
2018-05-19 15:55:14 +02:00
answer = int(float(answer) * 100)
2018-03-13 22:03:13 +01:00
except ValueError:
continue
if validator == "int":
try:
answer = int(answer)
except ValueError:
continue
if validator == "date":
answer = dateparser.parse(answer).date()
if answer is None:
continue
if validator == "set":
if answer not in set:
print("only [{formats}] are allowed".format(formats=", ".join(set)))
continue
2018-03-19 18:55:22 +01:00
if validator == "boolean":
if answer.lower() in ['true', '1', 't', 'y', 'yes']:
return True
elif answer.lower() in ["false", "0", "f", "n", "no"]:
return False
else:
continue
2018-03-13 22:03:13 +01:00
return answer