corrlib/corrlib/toml.py
Justus Kuhlmann 975501635a put more cli
2024-08-26 12:48:51 +00:00

89 lines
3.1 KiB
Python

"""
TOML interface
--------------
Remember, that keys with dots have to be quoted.
Apart from improting projects yourdelf with python scripts, this package also allows for
the import of projects via TOML.
"""
import tomllib as toml
import shutil
from .input import sfcf
from .main import import_project
from .meas_io import write_measurement
import datalad.api as dl
import os
def check_project_data(d):
if 'project' not in d.keys() or 'measurements' not in d.keys() or len(list(d.keys())) > 2:
raise ValueError('There should only be two key on the top level, "project" and "measurements"!')
project_data = d['project']
if 'url' not in project_data.keys():
raise ValueError('project.url is missing!')
if 'code' not in project_data.keys():
raise ValueError('project.code is missing!')
if 'measurements' not in d.keys():
raise ValueError('No measurements to import!')
return
def import_toml(path, file, copy_file=True):
"""
Import a project decribed by a .toml file.
Parameters
----------
path: str
Path to the backlog directory.
file: str
Path to the description file.
"""
print("Import project as decribed in " + file)
with open(file, 'rb') as fp:
toml_dict = toml.load(fp)
check_project_data(toml_dict)
project = toml_dict['project']
measurements = toml_dict['measurements']
uuid = import_project(path, project['url'])
for mname, md in measurements.items():
print("Import measurement: " + mname)
ensemble = md['ensemble']
param = sfcf.read_param(path, uuid, md['param_file'])
if 'names' in md.keys():
measurement = sfcf.read_data(path, uuid, md['path'], md['prefix'], param,
version=md['version'], cfg_seperator=md['cfg_seperator'], sep='/', names=md['names'])
else:
measurement = sfcf.read_data(path, uuid, md['path'], md['prefix'], param,
version=md['version'], cfg_seperator=md['cfg_seperator'], sep='/')
write_measurement(path, ensemble, measurement, uuid,
project['code'], md['param_file'])
print(mname + " imported.")
if not os.path.exists(os.path.join(path, "toml_imports", uuid)):
os.makedirs(os.path.join(path, "toml_imports", uuid))
if copy_file:
import_file = os.path.join(path, "toml_imports", uuid, file)
shutil.copy(file, import_file)
dl.save(path + import_file, message="Import using " + import_file, dataset=path)
print("Imported project, file copied to " + import_file)
return
def reimport_project(path, uuid):
"""
Reimport an existing project using the files that are already available for this project.
Parameters
----------
path: str
Path to repository
uuid: str
uuid of the project that is to be reimported.
"""
config_path = "/".join([path, "import_scripts", uuid])
for p, filenames, dirnames in os.walk(config_path):
for fname in filenames:
import_toml(path, os.path.join(config_path, fname), copy_file=False)
return