diff --git a/lib/invoice/cli.py b/lib/invoice/cli.py index 60e19cd..bdd334b 100644 --- a/lib/invoice/cli.py +++ b/lib/invoice/cli.py @@ -23,8 +23,7 @@ class Application: def __init__(self, template_path): self._parse_args() - exec(open(os.path.expanduser(os.path.join(self.args.user_data, "config"))).read(), - {"__builtins__": None}, self.__dict__) + self._load_config() self.year = self.args.__dict__.pop("year") self.user_path = os.path.expanduser(self.args.__dict__.pop("user_data")) self.method = self.args.__dict__.pop("method") @@ -36,6 +35,19 @@ class Application: year = self.year, data_path = self.data_path) + def _load_config(self): + config_dir = os.path.expanduser(self.args.user_data) + config_file = os.path.join(config_dir, "config") + + if not os.path.exists(config_dir): + os.mkdir(config_dir) + if not os.path.exists(config_file): + with open(config_file, "w") as f: + pass + + exec(open(config_file).read(), + {"__builtins__": None}, self.__dict__) + def _parse_args(self): parser = argparse.ArgumentParser( description = "Pavel Šimerda's invoice CLI application.", @@ -178,7 +190,7 @@ class Application: log.debug("Customer: {0}".format(customer_data._data)) log.debug("Creating TeX invoice...") - self._check_path(self.tmp_path) + self._ensure_directory(self.tmp_path) format_decimal=lambda x: '{:20,.2f}'.format(x).replace(',', '\\,').replace('.', ',') format_eur=lambda x: format_decimal(x) + ' EUR' @@ -198,7 +210,7 @@ class Application: assert(os.path.exists(tmp_pdf_file)) log.debug("Moving PDF file to the output directory...") - self._check_path(output_path) + self._ensure_directory(output_path) os.rename(tmp_pdf_file, pdf_file) assert(os.path.exists(pdf_file)) @@ -209,6 +221,12 @@ class Application: if not os.path.exists(path): raise LookupError("Directory doesn't exist: {0}".format(path)) + def _ensure_directory(self, path): + try: + self._check_path(path) + except LookupError as e: + os.makedirs(path, exist_ok=True) + def do_delete(self, selector, force): """List invoices.""" if selector: diff --git a/lib/invoice/db/base.py b/lib/invoice/db/base.py index bef157c..f5410d3 100644 --- a/lib/invoice/db/base.py +++ b/lib/invoice/db/base.py @@ -28,6 +28,8 @@ class List(object): self._year = year self._path = os.path.expanduser(data_path.format( year=year, directory=self._directory)) + if not os.path.exists(self._path): + os.makedirs(self._path, exist_ok=True) self._db = db log.debug("{0}: {1}".format(self.__class__.__name__, self._path))