Skip to content

Commit 15f704b

Browse files
committed
feat: Add config management module
This module is to set and read a config file where the main archive storage folder for planetarypy is determined.
1 parent a1a49b4 commit 15f704b

File tree

1 file changed

+69
-0
lines changed

1 file changed

+69
-0
lines changed

src/planetarypy/config.py

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
import logging
2+
from pathlib import Path
3+
4+
import toml
5+
6+
logger = logging.getLogger(__name__)
7+
8+
# create configpath depending on package name
9+
pkg_name = __name__.split(".")[0]
10+
configpath = Path.home() / f".{pkg_name}.toml"
11+
12+
13+
def print_error():
14+
print("No configuration file {} found.\n".format(configpath))
15+
print(
16+
"""Please run `planetarypy.config.set_database_path('path_to_archive')` and provide
17+
the path where `planetarypy` should archive all downloaded and created data."""
18+
)
19+
print(
20+
f"`planetarypy` will store this path in {configpath}, where you can easily change it later."
21+
)
22+
23+
24+
def set_database_path(dbfolder):
25+
"""Use to write the database path into the config.
26+
27+
Parameters
28+
----------
29+
dbfolder: str or pathlib.Path
30+
Path to where planetarypy will store data it downloads..
31+
"""
32+
# First check if there's a config file, so that we don't overwrite
33+
# anything:
34+
try:
35+
config = toml.load(str(configpath))
36+
except IOError: # config file doesn't exist
37+
config = {} # create new config dictionary
38+
39+
# check if there's an `data_archive` sub-dic
40+
try:
41+
archive_config = config["data_archive"]
42+
except KeyError:
43+
config["data_archive"] = {"path": dbfolder}
44+
else:
45+
archive_config["path"] = dbfolder
46+
47+
with open(configpath, "w") as f:
48+
ret = toml.dump(config, f)
49+
print(f"Saved database path {dbfolder} into {configpath}.")
50+
51+
52+
def get_data_root():
53+
config = toml.load(str(configpath))
54+
data_root = Path(config["data_archive"]["path"]).expanduser()
55+
data_root.mkdir(exist_ok=True, parents=True)
56+
return data_root
57+
58+
59+
if not configpath.exists():
60+
print(f"No configuration file {configpath} found.\n")
61+
savepath = input(
62+
"Provide the path where all planetarypy-managed data should be stored:"
63+
)
64+
set_database_path(savepath)
65+
66+
# get config object into module global
67+
config = toml.load(str(configpath))
68+
# get the archive path into module global
69+
data_root = get_data_root()

0 commit comments

Comments
 (0)