ACTS
Experiment-independent tracking
Loading...
Searching...
No Matches
create_path.hpp
1// This file is part of the ACTS project.
2//
3// Copyright (C) 2016 CERN for the benefit of the ACTS project
4//
5// This Source Code Form is subject to the terms of the Mozilla Public
6// License, v. 2.0. If a copy of the MPL was not distributed with this
7// file, You can obtain one at https://mozilla.org/MPL/2.0/.
8
9#pragma once
10
11// System include(s).
12#include <filesystem>
13#include <stdexcept>
14#include <string>
15#include <system_error>
16
17namespace detray::io {
18
22inline bool file_exists(const std::string& outdir) {
23 auto path = std::filesystem::path(outdir);
24
25 return std::filesystem::exists(path);
26}
27
31inline std::string alt_file_name(const std::string& name) {
32 auto path = std::filesystem::path(name);
33 auto parent_path = path.parent_path();
34 std::string stem = path.stem();
35 std::string extension = path.extension();
36
38 auto get_alternate_file_stem = [](std::string& file_stem,
39 const std::size_t n) {
40 const std::string delim{"_"};
41
42 // File stem already comes with a number, simply update it
43 if (n > 2u) {
44 std::size_t pos{file_stem.rfind(delim)};
45 if (pos == std::string::npos || (pos + 1 == file_stem.size())) {
46 throw std::runtime_error("Malformed file name");
47 }
48
49 // Leave the delimiter where it is and replace the file number
50 ++pos;
51 file_stem.replace(pos, file_stem.size() - pos, std::to_string(n));
52
53 return file_stem;
54 }
55
56 return file_stem + delim + std::to_string(n);
57 };
58
59 std::size_t n_trials{2u};
60 while (std::filesystem::exists(path)) {
61 stem = get_alternate_file_stem(stem, n_trials);
62 path = parent_path / std::filesystem::path{stem + extension};
63 ++n_trials;
64
65 // The maximum here is arbitrary
66 if (n_trials >= 10000u) {
67 throw std::runtime_error("Too many versions of file exist: " + stem +
68 extension);
69 }
70 }
71
72 path = parent_path / std::filesystem::path{stem + extension};
73 return path.string();
74}
75
79inline auto create_path(const std::string& outdir) {
80 auto path = std::filesystem::path(outdir);
81
82 if (!path.empty() && !std::filesystem::exists(path)) {
83 if (std::error_code err; !std::filesystem::create_directories(path, err)) {
84 throw std::runtime_error(err.message());
85 }
86 }
87
88 return path;
89}
90
91} // namespace detray::io
The following enums are global for all detectors.
Definition concepts.hpp:18
std::string alt_file_name(const std::string &name)
Find an unused numbered alternative to an existing file name.
Definition create_path.hpp:31
auto create_path(const std::string &outdir)
Check if a given file path exists and generate it if not.
Definition create_path.hpp:79
bool file_exists(const std::string &outdir)
Check if a file exists.
Definition create_path.hpp:22