Utopia 2
Framework for studying models of complex & adaptive systems.
Loading...
Searching...
No Matches
Functions
Filesystem
Collaboration diagram for Filesystem:

Functions

std::string Utopia::DataIO::expanduser (const std::string &path)
 Expands a path with a leading ~ character into an absolute path.
 
std::string Utopia::DataIO::get_abs_filepath (const Config &cfg)
 Extracts an absolute file path from a configuration.
 

Detailed Description

Filesystem tools

The Filesystem module contains tools that make interacting with the filesystem more convenient, e.g. to generate file paths from the configuration.

Function Documentation

◆ expanduser()

std::string Utopia::DataIO::expanduser ( const std::string &  path)

Expands a path with a leading ~ character into an absolute path.

This function uses the environment variable HOME and replaces a leading ~ character with that path. If there was no leading ~ character, the given path is returned.

Parameters
pathThe path to expand
Exceptions
Ifthe given path needs expansion but no HOME environment variable was set.
42 {
43 using namespace std::string_literals;
44
45 if (path.empty() or path.substr(0, 1) != "~"s) {
46 return path;
47 }
48
49 const std::string HOME = std::getenv("HOME");
50 if (HOME.empty()) {
51 throw std::invalid_argument(
52 "Cannot expand path because the environment variable 'HOME' was "
53 "not set! Use an absolute path to specify the given path: "
54 + path
55 );
56 }
57 return HOME + path.substr(1, std::string::npos);
58}

◆ get_abs_filepath()

std::string Utopia::DataIO::get_abs_filepath ( const Config cfg)

Extracts an absolute file path from a configuration.

Expected keys: filename, base_dir (optional). If no base_dir key is present, will prepend the current working directory.

If the base directory or the filename specify a relative directory, the resulting absolute path will start from the current working directory.

Furthermore, this function will call expanduser to allow using the ~ character to refer to the home directory.

Parameters
cfgThe configuration node with required key filename and optional key base_dir.
73 {
74 using std::filesystem::path;
75 using std::filesystem::current_path;
76
77 const path filename = expanduser(get_as<std::string>("filename", cfg));
78
79 path p = current_path();
80 if (cfg["base_dir"]) {
81 // By using append, we ensure that p remains an absolute path:
82 // - if base_dir is relative, will append, making it absolute
83 // - if base_dir is absolute, will overwrite current_path
84 p.append(expanduser(get_as<std::string>("base_dir", cfg)));
85 }
86 p /= filename;
87 return expanduser(p);
88}
std::string expanduser(const std::string &path)
Expands a path with a leading ~ character into an absolute path.
Definition filesystem.hh:42