Source code for tools.tpaths
"""Module to manage paths."""
from __future__ import annotations
import typing
import os
import os.path as op
import tempfile
import glob
import yaml
[docs]
def resolve_relative_path(path: str, reference: str):
"""If ``path`` is relative, turns it into an absolute path w.r.t. ``reference``.
If it is an absolute path, just return the path itself."""
if ":" not in path:
return op.abspath(op.join(reference, path))
else:
return path
[docs]
def resolve_relative_paths(paths: str | typing.List[str], reference: str):
"""Same as :py:func:`resolve_relative_path` but input can be one path or
a list of paths."""
if isinstance(paths, str):
return resolve_relative_path(paths, reference)
else:
return [resolve_relative_path(path, reference) for path in paths]
[docs]
def write_yaml_temp_file(dictionnary: dict, **kwargs) -> tempfile.NamedTemporaryFile:
"""Write a dictionnary to a temporary YAML file.
Args:
dictionnary: dictionnary to dump
kwargs: passed to :py:func:`tempfile.NamedTemporaryFile`
Returns:
Written temporary file
"""
yaml_tmpfile = tempfile.NamedTemporaryFile(suffix=".yaml", mode="w", **kwargs)
yaml.dump(dictionnary, yaml_tmpfile, Dumper=yaml.SafeDumper)
return yaml_tmpfile
[docs]
def write_yaml_file(dictionnary: dict, path: str):
"""Write a dictionnary to a YAML file."""
os.makedirs(op.dirname(path), exist_ok=True)
with open(path, "w") as yaml_file:
yaml.dump(dictionnary, yaml_file, Dumper=yaml.SafeDumper)
print("YAML file written in", path)
[docs]
def expand_paths(paths: typing.List[str]) -> typing.List[str]:
"""Expand paths in a list of paths that have a ``*``.
Args:
paths: list of paths. The paths that contain a star ``*`` are expanded using
the python :py:func:`glob.glob` function
**kwargs: passed to :py:func:`glob.glob`
Returns:
List of paths, where the paths that contain ``*`` have been expanded
"""
expanded_paths = []
for path in paths:
if ":" not in path and "*" in path:
expanded_paths += glob.glob(path)
else:
expanded_paths += [path]
return expanded_paths