Utopia 2
Framework for studying models of complex & adaptive systems.
Loading...
Searching...
No Matches
filesystem.hh
Go to the documentation of this file.
1#ifndef DATAIO_FILESYSTEM_HH
2#define DATAIO_FILESYSTEM_HH
3
4#include <cstdlib>
5#include <filesystem>
6#include <string>
7
8#include "../core/exceptions.hh"
9#include "../core/types.hh"
10#include "cfg_utils.hh"
11
12namespace Utopia::DataIO {
13
33
42std::string expanduser (const std::string& path) {
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}
59
61
73std::string get_abs_filepath (const Config& cfg) {
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}
89
90
91
92// end group Filesystem
// end of group DataIO
97
98} // namespace Utopia::DataIO
99
100#endif // DATAIO_FILESYSTEM_HH
YAML::Node Config
Type of a variadic dictionary-like data structure used throughout Utopia.
Definition types.hh:71
Container select_entities(const Manager &mngr, const DataIO::Config &sel_cfg)
Select entities according to parameters specified in a configuration.
Definition select.hh:213
std::string expanduser(const std::string &path)
Expands a path with a leading ~ character into an absolute path.
Definition filesystem.hh:42
std::string get_abs_filepath(const Config &cfg)
Extracts an absolute file path from a configuration.
Definition filesystem.hh:73
Definition types.hh:64