Skip to content

Commit

Permalink
feat: Add config management module
Browse files Browse the repository at this point in the history
This module is to set and read a config file where the main archive storage folder for planetarypy is determined.
  • Loading branch information
michaelaye committed Dec 22, 2020
1 parent a1a49b4 commit 15f704b
Showing 1 changed file with 69 additions and 0 deletions.
69 changes: 69 additions & 0 deletions src/planetarypy/config.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import logging
from pathlib import Path

import toml

logger = logging.getLogger(__name__)

# create configpath depending on package name
pkg_name = __name__.split(".")[0]
configpath = Path.home() / f".{pkg_name}.toml"


def print_error():
print("No configuration file {} found.\n".format(configpath))
print(
"""Please run `planetarypy.config.set_database_path('path_to_archive')` and provide
the path where `planetarypy` should archive all downloaded and created data."""
)
print(
f"`planetarypy` will store this path in {configpath}, where you can easily change it later."
)


def set_database_path(dbfolder):
"""Use to write the database path into the config.
Parameters
----------
dbfolder: str or pathlib.Path
Path to where planetarypy will store data it downloads..
"""
# First check if there's a config file, so that we don't overwrite
# anything:
try:
config = toml.load(str(configpath))
except IOError: # config file doesn't exist
config = {} # create new config dictionary

# check if there's an `data_archive` sub-dic
try:
archive_config = config["data_archive"]
except KeyError:
config["data_archive"] = {"path": dbfolder}
else:
archive_config["path"] = dbfolder

with open(configpath, "w") as f:
ret = toml.dump(config, f)
print(f"Saved database path {dbfolder} into {configpath}.")


def get_data_root():
config = toml.load(str(configpath))
data_root = Path(config["data_archive"]["path"]).expanduser()
data_root.mkdir(exist_ok=True, parents=True)
return data_root


if not configpath.exists():
print(f"No configuration file {configpath} found.\n")
savepath = input(
"Provide the path where all planetarypy-managed data should be stored:"
)
set_database_path(savepath)

# get config object into module global
config = toml.load(str(configpath))
# get the archive path into module global
data_root = get_data_root()

0 comments on commit 15f704b

Please sign in to comment.