44#include "TRestTools.h"
48#include <TClassEdit.h>
49#include <TDirectory.h>
51#include <TFileMerger.h>
54#include <TObjString.h>
56#include <TSchemaRule.h>
57#include <TSchemaRuleSet.h>
58#include <TStreamerInfo.h>
96#include "TRestStringHelper.h"
97#include "TRestStringOutput.h"
102#ifdef REST_TESTING_ENABLED
103std::atomic_bool gForceNextRootUpdatePreflightFailure{
false};
104std::atomic_bool gForceNextMergeValidationFailure{
false};
107struct StreamerInfoIdentity {
112 bool operator<(
const StreamerInfoIdentity& other)
const {
113 return std::tie(name, version, checksum) < std::tie(other.name, other.version, other.checksum);
117struct RootSchemaSnapshot {
118 std::set<StreamerInfoIdentity> streamerInfos;
119 std::set<std::string> schemaRules;
120 std::set<Int_t> numbers;
125bool IsImplementationSchema(
const std::string& name) {
126 return TClassEdit::IsStdClass(name.c_str()) || TClassEdit::IsStdPairBase(name.c_str());
129struct RootContentEntry {
130 std::string className;
131 std::optional<Long64_t> treeEntries;
134using RootContentManifest = std::map<std::string, RootContentEntry>;
136struct LocalFileIdentity {
138 std::filesystem::file_time_type modificationTime;
140 std::uintmax_t device;
141 std::uintmax_t inode;
144 bool operator==(
const LocalFileIdentity& other)
const {
145 return size == other.size && modificationTime == other.modificationTime
147 && device == other.device && inode == other.inode
153std::optional<std::filesystem::path> LocalRootPath(
const std::string& filename) {
154 TUrl url(filename.c_str(), kTRUE);
155 if (!url.IsValid() || std::string(url.GetProtocol()) !=
"file")
return std::nullopt;
156 TString expanded(url.GetFile());
157 if (gSystem->ExpandPathName(expanded))
return std::nullopt;
158 return std::filesystem::path(expanded.Data());
164std::optional<LocalFileIdentity> CaptureLocalFileIdentity(
const std::filesystem::path& path,
165 std::string& error) {
167 LocalFileIdentity identity;
168 identity.size = std::filesystem::file_size(path, ec);
170 error =
"Cannot inspect size of " + path.string() +
": " + ec.message();
173 identity.modificationTime = std::filesystem::last_write_time(path, ec);
175 error =
"Cannot inspect modification time of " + path.string() +
": " + ec.message();
179 struct stat status {};
180 if (::stat(path.c_str(), &status) != 0) {
181 error =
"Cannot inspect filesystem identity of " + path.string() +
": " + std::strerror(errno);
184 identity.device =
static_cast<std::uintmax_t
>(status.st_dev);
185 identity.inode =
static_cast<std::uintmax_t
>(status.st_ino);
192std::string NormalizeSchemaRule(
const std::string& rule) {
193 ROOT::TSchemaRule parsed;
194 if (!parsed.SetFromRule(rule.c_str()))
return "";
196 parsed.AsString(normalized);
197 return normalized.Data();
210bool ReadSchemaSnapshot(TFile& file, RootSchemaSnapshot& snapshot, std::string& error,
bool resolve =
false) {
211 if (!file.IsOpen() || file.IsZombie()) {
212 error =
"Cannot inspect StreamerInfos in a closed or invalid ROOT file";
215 if (file.GetSeekInfo() == 0)
return true;
217 std::unique_ptr<TList> infos(file.GetStreamerInfoList());
218 if (infos ==
nullptr) {
219 error =
"ROOT could not read the existing StreamerInfo record";
222 infos->SetOwner(kTRUE);
224 TIter next(infos.get());
225 while (TObject*
object = next()) {
226 if (
auto* info =
dynamic_cast<TStreamerInfo*
>(
object)) {
227 snapshot.streamerInfos.insert({info->GetName(), info->GetClassVersion(), info->GetCheckSum()});
231 auto* rules =
dynamic_cast<TList*
>(object);
232 if (rules ==
nullptr || std::string(rules->GetName()) !=
"listOfRules")
continue;
233 TIter nextRule(rules);
234 while (TObject* ruleObject = nextRule()) {
235 auto* rule =
dynamic_cast<TObjString*
>(ruleObject);
236 if (rule ==
nullptr)
continue;
237 const std::string normalized = NormalizeSchemaRule(rule->GetString().Data());
238 if (normalized.empty()) {
239 error =
"The on-disk StreamerInfo contains an invalid schema rule";
242 snapshot.schemaRules.insert(normalized);
245 if (!resolve)
return true;
250 infos->SetOwner(kFALSE);
251 bool resolved =
true;
253 while (TObject*
object = next()) {
254 auto* info =
dynamic_cast<TStreamerInfo*
>(object);
255 if (info ==
nullptr) {
256 object->SetBit(TObject::kCanDelete);
259 const StreamerInfoIdentity identity{info->GetName(), info->GetClassVersion(), info->GetCheckSum()};
260 info->BuildCheck(&file);
261 if (info->GetNumber() > 0) {
262 snapshot.numbers.insert(info->GetNumber());
263 const auto* registered =
264 dynamic_cast<TStreamerInfo*
>(gROOT->GetListOfStreamerInfo()->At(info->GetNumber()));
265 if (!IsImplementationSchema(identity.name) &&
266 (!registered || identity.name != registered->GetName() ||
269 identity.version != std::abs(registered->GetClassVersion()) ||
270 identity.checksum != registered->GetCheckSum())) {
271 error =
"Conflicting StreamerInfo for " + identity.name +
" version " +
272 std::to_string(identity.version) +
" checksum " + std::to_string(identity.checksum);
274 error +=
"; resolved to version " + std::to_string(registered->GetClassVersion()) +
275 " checksum " + std::to_string(registered->GetCheckSum());
277 ". Cannot safely preserve this schema; update or merge refused before "
278 "writing. Input files are unchanged. Check class versioning and schema-evolution "
279 "rules; an explicit migration may be needed.";
282 }
else if (!info->TestBit(TObject::kCanDelete)) {
283 error =
"Cannot preserve StreamerInfo " + std::string(info->GetName()) +
" version " +
284 std::to_string(info->GetClassVersion()) +
" checksum " +
285 std::to_string(info->GetCheckSum());
297bool IsSubset(
const RootSchemaSnapshot& expected,
const RootSchemaSnapshot& actual, std::string& error) {
298 for (
const auto& info : expected.streamerInfos) {
299 if (actual.streamerInfos.count(info) == 0) {
304 if (IsImplementationSchema(info.name))
continue;
305 error =
"Merged file lost StreamerInfo " + info.name +
" version " +
306 std::to_string(info.version) +
" checksum " + std::to_string(info.checksum);
310 for (
const auto& rule : expected.schemaRules) {
311 if (actual.schemaRules.count(rule) == 0) {
312 error =
"Merged file lost an on-disk schema-evolution rule";
323bool ReadContentManifest(TDirectory& directory,
const std::string& prefix, RootContentManifest& manifest,
324 std::string& error) {
325 TDirectory::TContext directoryContext(&directory);
326 std::map<std::string, TKey*> newestKeys;
327 TIter nextKey(directory.GetListOfKeys());
328 while (
auto* key =
dynamic_cast<TKey*
>(nextKey())) {
329 auto existing = newestKeys.find(key->GetName());
330 if (existing == newestKeys.end() || key->GetCycle() > existing->second->GetCycle())
331 newestKeys[key->GetName()] = key;
334 for (
const auto& [name, key] : newestKeys) {
335 const std::string path = prefix.empty() ? name : prefix +
"/" + name;
336 RootContentEntry entry{key->GetClassName(), std::nullopt};
337 TClass* keyClass = TClass::GetClass(key->GetClassName(), kFALSE);
338 const bool isDirectory = keyClass !=
nullptr && keyClass->InheritsFrom(TDirectory::Class());
339 const bool isTree = keyClass !=
nullptr && keyClass->InheritsFrom(TTree::Class());
341 if (isDirectory || isTree) {
342 std::unique_ptr<TObject> object(key->ReadObj());
343 if (
object ==
nullptr) {
345 "Cannot read " + std::string(isDirectory ?
"directory" :
"tree") +
" key '" + path +
"'";
349 auto* child =
dynamic_cast<TDirectory*
>(
object.get());
350 if (child ==
nullptr) {
351 error =
"Key '" + path +
"' claims directory class '" + entry.className +
352 "' but ROOT read a different object";
355 manifest[path] = entry;
356 if (!ReadContentManifest(*child, path, manifest, error))
return false;
360 auto* tree =
dynamic_cast<TTree*
>(
object.get());
361 if (tree ==
nullptr) {
362 error =
"Key '" + path +
"' claims tree class '" + entry.className +
363 "' but ROOT read a different object";
366 entry.treeEntries = tree->GetEntries();
368 manifest[path] = entry;
377bool AddContentManifest(
const RootContentManifest& source, RootContentManifest& expected,
378 std::string& error) {
379 for (
const auto& [path, sourceEntry] : source) {
380 const auto existing = expected.find(path);
381 if (existing == expected.end()) {
382 expected[path] = sourceEntry;
385 if (existing->second.className != sourceEntry.className) {
386 error =
"ROOT merge input key '" + path +
"' has incompatible classes '" +
387 existing->second.className +
"' and '" + sourceEntry.className +
"'";
390 if (existing->second.treeEntries.has_value() != sourceEntry.treeEntries.has_value()) {
391 error =
"ROOT merge input key '" + path +
"' is inconsistently identified as a TTree";
394 if (sourceEntry.treeEntries.has_value()) {
395 if (*sourceEntry.treeEntries >
396 std::numeric_limits<Long64_t>::max() - *existing->second.treeEntries) {
397 error =
"Merged TTree entry count overflows for key '" + path +
"'";
400 *existing->second.treeEntries += *sourceEntry.treeEntries;
409bool ValidateContentManifest(
const RootContentManifest& expected,
const RootContentManifest& actual,
410 std::string& error) {
411 for (
const auto& [path, expectedEntry] : expected) {
412 const auto found = actual.find(path);
413 if (found == actual.end()) {
414 error =
"Merged file lost key '" + path +
"'";
417 if (found->second.className != expectedEntry.className) {
418 error =
"Merged key '" + path +
"' changed class from '" + expectedEntry.className +
"' to '" +
419 found->second.className +
"'";
422 if (expectedEntry.treeEntries.has_value()) {
423 if (!found->second.treeEntries.has_value()) {
424 error =
"Merged key '" + path +
"' is no longer readable as a TTree";
427 if (*found->second.treeEntries != *expectedEntry.treeEntries) {
428 error =
"Merged TTree '" + path +
"' has " + std::to_string(*found->second.treeEntries) +
429 " entries; expected " + std::to_string(*expectedEntry.treeEntries);
443bool LoadOnDiskSchemaRules(
const RootSchemaSnapshot& snapshot, std::string& error) {
444 for (
const auto& text : snapshot.schemaRules) {
445 auto rule = std::make_unique<ROOT::TSchemaRule>();
446 if (!rule->SetFromRule(text.c_str())) {
447 error =
"Cannot parse an on-disk schema-evolution rule";
450 const std::string target = rule->GetTargetClass();
451 TClass* cl = TClass::GetClass(target.c_str(), kFALSE);
453 error =
"Cannot register schema rules for unloaded class " + target;
456 auto registered = [&]() {
457 if (!cl->GetSchemaRules())
return false;
458 TIter next(cl->GetSchemaRules()->GetRules());
459 while (
auto* candidate =
dynamic_cast<ROOT::TSchemaRule*
>(next())) {
461 candidate->AsString(serialized);
462 if (text == serialized.Data())
return true;
466 if (registered())
continue;
468 if (cl->GetState() <= TClass::kEmulated) {
469 auto* rules = cl->GetSchemaRules(kTRUE);
470 added = rules && rules->AddRule(rule.get(), ROOT::Detail::TSchemaRuleSet::kNoCheck);
471 if (added) rule.release();
473 added = TClass::AddRule(text.c_str());
475 if (!added || !registered()) {
476 error =
"Cannot preserve an on-disk schema rule for class " + target;
489bool ApplySchemaUpdate(TFile& file,
const std::set<Int_t>& numbers, std::string& error) {
490 TArrayC* classIndex = file.GetClassIndex();
491 if (classIndex ==
nullptr) {
492 error =
"ROOT file has no StreamerInfo class index";
495 if (!numbers.empty() && *numbers.rbegin() >= classIndex->GetSize())
496 classIndex->Set(*numbers.rbegin() + 1);
497 for (
const Int_t number : numbers) classIndex->fArray[number] = 1;
498 classIndex->fArray[0] = 1;
504void Require(
bool success,
const std::string& error) {
505 if (!success)
throw std::runtime_error(error);
508std::filesystem::path UniqueSiblingPath(
const std::filesystem::path& target,
const std::string& label) {
509 for (
int attempt = 0; attempt < 20; ++attempt) {
510 TString uuid = TUUID().AsString();
511 uuid.ReplaceAll(
"-",
"");
513 target.parent_path() / (
"." + target.filename().
string() +
".rest-" + label +
"-" + uuid.Data());
514 if (!std::filesystem::exists(candidate))
return candidate;
523bool ReplaceLocalFile(
const std::filesystem::path& temporary,
const std::filesystem::path& target,
524 const std::filesystem::path& backup, std::string& error) {
525 const bool targetExists = std::filesystem::exists(target);
528 if (!ReplaceFileW(target.wstring().c_str(), temporary.wstring().c_str(), backup.wstring().c_str(),
529 REPLACEFILE_WRITE_THROUGH,
nullptr,
nullptr)) {
530 error =
"Windows ReplaceFile failed with error " + std::to_string(GetLastError());
533 }
else if (!MoveFileExW(temporary.wstring().c_str(), target.wstring().c_str(), MOVEFILE_WRITE_THROUGH)) {
534 error =
"Windows MoveFileEx failed with error " + std::to_string(GetLastError());
540 std::filesystem::create_hard_link(target, backup, ec);
543 std::filesystem::copy_file(target, backup, std::filesystem::copy_options::none, ec);
545 error =
"Cannot create rollback backup " + backup.string() +
": " + ec.message();
550 if (::rename(temporary.c_str(), target.c_str()) != 0) {
551 error =
"Atomic rename to " + target.string() +
" failed: " + std::strerror(errno);
553 std::error_code cleanupError;
554 std::filesystem::remove(backup, cleanupError);
556 error +=
". REST also could not remove rollback backup '" + backup.string() +
557 "': " + cleanupError.message();
568bool RollBackLocalFile(
const std::filesystem::path& target,
const std::filesystem::path& backup,
569 bool targetPreviouslyExisted, std::string& error) {
570 if (!targetPreviouslyExisted) {
572 std::filesystem::remove(target, ec);
573 if (ec) error =
"Cannot remove invalid replacement " + target.string() +
": " + ec.message();
577 if (!ReplaceFileW(target.wstring().c_str(), backup.wstring().c_str(),
nullptr, REPLACEFILE_WRITE_THROUGH,
579 error =
"Cannot roll back " + target.string() +
"; Windows error " + std::to_string(GetLastError());
583 if (::rename(backup.c_str(), target.c_str()) != 0) {
584 error =
"Cannot roll back " + target.string() +
": " + std::strerror(errno);
598 TRestRootFileHandle result;
600 result.fError =
"REST refuses to mutate remote ROOT destination '" + filename +
601 "'. Choose an explicit local output file.";
605 const char* option = mode == TRestRootFileMode::Recreate ?
"RECREATE" :
"READ";
606 bool createForUpdate =
false;
607 if (mode == TRestRootFileMode::Update) {
609 const auto path = LocalRootPath(filename);
611 result.fError =
"Cannot resolve local UPDATE destination '" + filename +
"'";
614 createForUpdate = !std::filesystem::exists(*path, ec);
616 result.fError =
"Cannot inspect ROOT destination '" + filename +
"': " + ec.message();
621 if (createForUpdate) option =
"CREATE";
623 result.fFile.reset(TFile::Open(filename.c_str(), option));
624 if (result.fFile ==
nullptr || !result.fFile->IsOpen() || result.fFile->IsZombie()) {
626 "Cannot open ROOT file '" + filename +
627 (mode == TRestRootFileMode::Update && !createForUpdate ?
"' for read-only UPDATE preflight"
628 :
"' in mode " + std::string(option));
629 result.fFile.reset();
632 if ((mode == TRestRootFileMode::Recreate || createForUpdate) && !result.fFile->IsWritable()) {
633 result.fError =
"ROOT file '" + filename +
"' is not writable";
634 result.fFile.reset();
638 if (mode == TRestRootFileMode::Update && !createForUpdate &&
640 result.fFile.reset();
646 : fFile(std::move(other.fFile)), fError(std::move(other.fError)) {}
649 if (
this == &other)
return *
this;
651 fFile = std::move(other.fFile);
652 fError = std::move(other.fError);
656TRestRootFileHandle::~TRestRootFileHandle() {
Close(); }
663 if (fFile ==
nullptr)
return fError.empty();
664 if (fFile->IsOpen()) fFile->Close();
665 const bool success = !fFile->IsZombie() && !fFile->TestBit(TFile::kWriteError);
666 if (!success && fError.empty())
667 fError =
"ROOT reported a write error while closing " + std::string(fFile->GetName());
679 bool transitionAttempted =
false;
681 Require(file.IsOpen() && !file.IsZombie() && !file.IsWritable(),
682 "UPDATE preparation requires a valid TFile that is currently open in READ mode");
683 const std::string filename = file.GetName();
684 const auto path = LocalRootPath(filename);
685 Require(path.has_value(),
"REST refuses to mutate remote ROOT destination '" + filename +
686 "'. Choose an explicit local output file.");
688 const auto before = CaptureLocalFileIdentity(*path, detail);
689 Require(before.has_value(), detail);
690 RootSchemaSnapshot schema;
691 Require(ReadSchemaSnapshot(file, schema, detail,
true) && LoadOnDiskSchemaRules(schema, detail),
693#ifdef REST_TESTING_ENABLED
694 Require(!gForceNextRootUpdatePreflightFailure.exchange(
false),
695 "Forced writable ROOT preflight failure for testing");
697 transitionAttempted =
true;
698 Require(file.ReOpen(
"UPDATE") == 0 && file.IsWritable(),
699 "ROOT could not transition '" + filename +
"' from validated READ to UPDATE");
700 const auto after = CaptureLocalFileIdentity(*path, detail);
701 Require(after.has_value(), detail);
702 Require(*before == *after,
703 "ROOT file '" + filename +
"' changed during the READ-to-UPDATE transition");
704 Require(ApplySchemaUpdate(file, schema.numbers, detail), detail);
705 if (error) error->clear();
707 }
catch (
const std::exception& failure) {
708 if (transitionAttempted) file.SetWritable(kFALSE);
709 if (error) *error = failure.what();
730 const set<string> libraryExtension{
".so",
".dylib",
".dll"};
731 const set<string> excludedLibraries{
734 vector<string> ldPaths;
736 ldPaths.push_back(REST_PATH +
"/bin/");
739 ldPaths.push_back(REST_PATH +
"/lib/");
741 ldPaths.push_back(REST_USER_PATH +
"/userlib/");
743 vector<string> fileList;
744 for (
const std::filesystem::path path : ldPaths) {
749 for (
const auto& it : std::filesystem::directory_iterator(path)) {
750 if (!it.is_regular_file()) {
753 if (libraryExtension.count(it.path().extension().string()) == 0) {
757 const TString pathRootString = it.path().string();
759 if (!libName.Contains(
"Rest", TString::kExact)) {
764 bool excluded =
false;
765 for (
const TString excludedLibrary : excludedLibraries) {
766 if (libName.Contains(excludedLibrary, TString::kExact)) {
775 fileList.emplace_back(it.path().string());
780 if (!silent) cout <<
"= Loading libraries ..." << endl;
781 for (
const auto& library : fileList) {
782 if (!silent) cout <<
" - " << library << endl;
783 gSystem->Load(library.c_str());
785 if (!silent) cout << endl;
797 Int_t size = data.size();
798 if (end > 0 && size > end) size = end;
799 for (
int n = start; n < size; n++) {
800 for (
unsigned int m = 0; m < data[n].size(); m++) cout << data[n][m] <<
"\t";
819 ofstream file(fname);
820 if (!file.is_open()) {
821 RESTError <<
"Unable to open file for writing : " << fname << RESTendl;
825 for (
unsigned int n = 0; n < data.size(); n++)
826 for (
unsigned int m = 0; m < data[n].size(); m++) {
828 if (m + 1 < data[n].size()) file <<
"\t";
829 if (m + 1 == data[n].size()) file <<
"\n";
838 std::vector<std::vector<Float_t>>& data);
840 std::vector<std::vector<Double_t>>& data);
848 ofstream file(fname, ios::out | ios::binary);
849 if (!file.is_open()) {
850 RESTError <<
"Unable to open file for writing : " << fname << RESTendl;
854 for (
unsigned int n = 0; n < data.size(); n++)
855 for (
unsigned int m = 0; m < data[n].size(); m++) {
856 file.write((
char*)&data[n][m],
sizeof(T));
865 std::vector<std::vector<Float_t>>& data);
867 std::vector<std::vector<Double_t>>& data);
888 RESTError <<
"TRestTools::ReadBinaryTable. Error." << RESTendl;
889 RESTError <<
"Cannot open file : " << fName << RESTendl;
896 RESTError <<
"TRestTools::ReadBinaryTable. Format extension error." << RESTendl;
897 RESTError <<
"Please, specify the number of columns at the method 3rd argument" << RESTendl;
902 std::ifstream fin(fName, std::ios::binary);
903 fin.seekg(0, std::ios::end);
904 const size_t num_elements = fin.tellg() /
sizeof(T);
905 fin.seekg(0, std::ios::beg);
907 if (num_elements % columns != 0) {
908 cout <<
"TRestTools::ReadBinaryTable. Error." << endl;
909 cout <<
"Number of elements : " << num_elements
910 <<
" is not compatible with the number of columns : " << columns << endl;
915 std::vector<T> dataArray(columns);
916 fin.read(
reinterpret_cast<char*
>(&dataArray[0]), columns *
sizeof(T));
918 data.push_back(dataArray);
919 fin.read(
reinterpret_cast<char*
>(&dataArray[0]), columns *
sizeof(T));
950 if (extension.find(
"N") != 0) {
954 size_t pos = extension.find(
"i");
955 if (pos != string::npos) {
959 pos = extension.find(
"f");
960 if (pos != string::npos) {
964 pos = extension.find(
"d");
965 if (pos != string::npos) {
969 RESTError <<
"Format " <<
ToUpper(extension) <<
" not recognized" << RESTendl;
979 if (data.size() == 0)
return;
981 std::vector<std::vector<T>> trans_vec(data[0].size(), std::vector<T>());
983 for (
unsigned int i = 0; i < data.size(); i++)
984 for (
unsigned int j = 0; j < data[i].size(); j++) trans_vec[j].push_back(data[i][j]);
1002template <
typename T>
1004 if (data.size() == 0)
return 0;
1005 if (column > -1 && data[0].size() <= (
unsigned int)column)
return 0;
1007 T maxValue = data[0][0];
1009 for (
unsigned int n = 0; n < data.size(); n++)
1010 for (
unsigned int c = 0; c < data[n].size(); c++)
1011 if (maxValue < data[n][c]) maxValue = data[n][c];
1013 maxValue = data[0][column];
1014 for (
unsigned int n = 0; n < data.size(); n++)
1015 if (maxValue < data[n][column]) maxValue = data[n][column];
1037template <
typename T>
1039 if (data.empty())
return 0;
1040 if (column != -1 && data[0].size() <= (
unsigned int)column)
return 0;
1042 T minValue = data[0][0];
1044 for (
unsigned int n = 0; n < data.size(); n++)
1045 for (
unsigned int c = 0; c < data[n].size(); c++)
1046 if (minValue > data[n][c]) minValue = data[n][c];
1048 minValue = data[0][column];
1049 for (
unsigned int n = 0; n < data.size(); n++)
1050 if (minValue > data[n][column]) minValue = data[n][column];
1074template <
typename T>
1076 if (data.size() == 0 || data[0].size() <= (
unsigned int)column)
return 0;
1077 T lowestIncrease = abs(data[0][column] - data[1][column]);
1078 for (
unsigned int n = 1; n < data.size(); n++) {
1079 T value = abs(data[n - 1][column] - data[n][column]);
1080 if (lowestIncrease == 0) lowestIncrease = value;
1081 if (value > 0 && value < lowestIncrease) lowestIncrease = value;
1083 return lowestIncrease;
1104template <
typename T>
1106 if (data.size() == 0)
return 0;
1108 for (
unsigned int n = 0; n < data.size(); n++) {
1109 for (
unsigned int m = 0; m < data[n].size(); m++) sum += data[n][m];
1126template <
typename T>
1128 std::vector<T> columnData;
1129 if (data.size() == 0 || data[0].size() <= column)
return columnData;
1131 for (
unsigned int n = 0; n < data.size(); n++) columnData.push_back(data[n][column]);
1137 unsigned int column);
1140 const std::vector<std::vector<Float_t>>& data,
unsigned int column);
1143 const std::vector<std::vector<Double_t>>& data,
unsigned int column);
1146 const std::vector<std::vector<std::string>>& data,
unsigned int column);
1162 std::string separator) {
1164 cout <<
"TRestTools::ReadASCIITable. Error" << endl;
1165 cout <<
"Cannot open file : " << fName << endl;
1171 std::ifstream fin(fName);
1174 std::vector<std::vector<string>> values;
1176 for (
string line; std::getline(fin, line);) {
1177 if (skipLines > 0) {
1182 if (line.find(
"#") == string::npos) {
1183 std::istringstream in(line);
1186 std::vector<std::string> tokens;
1187 while (std::getline(in, token, (
char)separator[0])) {
1188 tokens.push_back(token);
1190 data.push_back(tokens);
1211 std::string separator) {
1213 cout <<
"TRestTools::ReadASCIITable. Error" << endl;
1214 cout <<
"Cannot open file : " << fName << endl;
1220 std::ifstream fin(fName);
1223 std::vector<std::vector<string>> values;
1225 for (
string line; std::getline(fin, line);) {
1226 if (skipLines > 0) {
1231 if (line.find(
"#") == string::npos) {
1232 std::istringstream in(line);
1235 std::vector<std::string> tokens;
1236 while (std::getline(in, token, (
char)separator[0])) {
1237 tokens.push_back(token);
1239 values.push_back(tokens);
1244 for (
unsigned int n = 0; n < values.size(); n++) {
1245 std::vector<Double_t> dblTmp;
1248 for (
unsigned int m = 0; m < values[n].size(); m++) dblTmp.push_back(
StringToDouble(values[n][m]));
1250 data.push_back(dblTmp);
1270 std::string separator) {
1272 cout <<
"TRestTools::ReadASCIITable. Error" << endl;
1273 cout <<
"Cannot open file : " << fName << endl;
1279 std::ifstream fin(fName);
1282 std::vector<std::vector<string>> values;
1284 for (
string line; std::getline(fin, line);) {
1285 if (skipLines > 0) {
1290 if (line.find(
"#") == string::npos) {
1291 std::istringstream in(line);
1294 std::vector<std::string> tokens;
1295 while (std::getline(in, token, (
char)separator[0])) {
1296 tokens.push_back(token);
1298 values.push_back(tokens);
1303 for (
unsigned int n = 0; n < values.size(); n++) {
1304 std::vector<Float_t> dblTmp;
1307 for (
unsigned int m = 0; m < values[n].size(); m++) dblTmp.push_back(
StringToFloat(values[n][m]));
1309 data.push_back(dblTmp);
1374 TFile* f = TFile::Open((TString)filename);
1376 TIter nextkey(f->GetListOfKeys());
1378 while ((key = (TKey*)nextkey())) {
1379 if ((std::string)key->GetClassName() ==
"TRestRun")
return true;
1392 TFile* f = TFile::Open((TString)filename);
1394 TIter nextkey(f->GetListOfKeys());
1396 while ((key = (TKey*)nextkey())) {
1397 if ((std::string)key->GetClassName() ==
"TRestDataSet")
return true;
1406 std::regex pattern(
"^https?://(.+)");
1407 return std::regex_match(s, pattern);
1414 TUrl url(filename.c_str(), kTRUE);
1415 return url.IsValid() && std::string(url.GetProtocol()) !=
"file";
1418#ifdef REST_TESTING_ENABLED
1422void TRestTools::ForceNextRootUpdatePreflightFailureForTesting() {
1423 gForceNextRootUpdatePreflightFailure.store(
true);
1429void TRestTools::ForceNextTransactionalMergeValidationFailureForTesting() {
1430 gForceNextMergeValidationFailure.store(
true);
1452 const std::vector<std::string>& inputFiles,
1453 const std::string& existingTarget,
bool removeInputsOnSuccess,
1454 std::string* error) {
1455 namespace fs = std::filesystem;
1458 const auto localOutput = LocalRootPath(outputFile);
1459 Require(localOutput.has_value(),
"REST refuses to replace remote ROOT destination '" + outputFile +
1460 "'. Choose an explicit local output file.");
1461 const fs::path target = fs::weakly_canonical(fs::absolute(*localOutput));
1462 Require(fs::is_directory(target.parent_path()),
1463 "Output directory does not exist for '" + target.string() +
"'");
1465 std::vector<std::string> sources;
1466 if (!existingTarget.empty()) sources.push_back(existingTarget);
1467 sources.insert(sources.end(), inputFiles.begin(), inputFiles.end());
1468 Require(!sources.empty(),
"No ROOT input files were provided for transactional merge");
1470 RootSchemaSnapshot schema;
1471 RootContentManifest content, workers;
1473 for (std::size_t index = 0; index < sources.size(); ++index) {
1475 Require(
bool(source), source.Error());
1476 RootContentManifest incoming;
1477 if (!ReadSchemaSnapshot(*source, schema, detail,
true) ||
1478 !LoadOnDiskSchemaRules(schema, detail) ||
1479 !ReadContentManifest(*source,
"", incoming, detail) ||
1480 !AddContentManifest(incoming, !existingTarget.empty() && index == 0 ? content : workers,
1482 throw std::runtime_error(
"Cannot prepare merge input '" + sources[index] +
"': " + detail);
1486 for (
const auto& [path, incoming] : workers) {
1487 const auto found = content.find(path);
1488 Require(found == content.end() || found->second.className == incoming.className,
1489 "ROOT merge input key '" + path +
"' has incompatible classes");
1490 content[path] = incoming;
1493 temporary = UniqueSiblingPath(target,
"merge");
1494 const auto backup = UniqueSiblingPath(target,
"backup");
1495 Require(!temporary.empty() && !backup.empty(),
1496 "Cannot allocate temporary paths next to '" + target.string() +
"'");
1497 if (!existingTarget.empty()) {
1498 const auto localExisting = LocalRootPath(existingTarget);
1500 fs::copy_file(*localExisting, temporary);
1502 Require(TFile::Cp(existingTarget.c_str(), temporary.c_str(), kFALSE),
1503 "ROOT could not seed temporary merge output from '" + existingTarget +
"'");
1507 ? TRestRootFileMode::Recreate
1508 : TRestRootFileMode::Update);
1509 Require(
bool(output), output.Error());
1510 Require(ApplySchemaUpdate(*output, schema.numbers, detail), detail);
1511 if (inputFiles.empty()) {
1512 Require(output.Close(), output.Error());
1514 TFileMerger merger(kFALSE);
1515 merger.SetPrintLevel(0);
1516 Require(merger.OutputFile(std::move(output.fFile)),
1517 "ROOT could not adopt temporary merge output '" + temporary.string() +
"'");
1518 for (
const auto& input : inputFiles)
1519 Require(merger.AddFile(input.c_str(), kFALSE),
1520 "ROOT could not add merge input '" + input +
"'");
1521 Require(merger.Merge(),
"ROOT failed while merging into '" + temporary.string() +
"'");
1525 auto validate = [&](
const fs::path& path) {
1527 Require(
bool(file), file.Error());
1528 RootSchemaSnapshot actualSchema;
1529 RootContentManifest actualContent;
1530 Require(ReadSchemaSnapshot(*file, actualSchema, detail) &&
1531 IsSubset(schema, actualSchema, detail) &&
1532 ReadContentManifest(*file,
"", actualContent, detail) &&
1533 ValidateContentManifest(content, actualContent, detail),
1536 validate(temporary);
1537 const bool targetExisted = fs::exists(target);
1538 if (targetExisted) fs::permissions(temporary, fs::status(target).permissions());
1539 Require(ReplaceLocalFile(temporary, target, backup, detail), detail);
1542#ifdef REST_TESTING_ENABLED
1543 Require(!gForceNextMergeValidationFailure.exchange(
false),
1544 "Forced post-replacement ROOT validation failure for testing");
1546 }
catch (
const std::exception& failure) {
1547 std::string rollbackError;
1548 detail = failure.what();
1549 if (!RollBackLocalFile(target, backup, targetExisted, rollbackError))
1550 detail +=
". Rollback also failed: " + rollbackError +
". The backup is at '" +
1551 backup.string() +
"'";
1552 throw std::runtime_error(detail);
1555 if (targetExisted) {
1557 fs::remove(backup, ec);
1558 Require(!ec,
"Merged output is valid, but REST could not remove rollback backup '" +
1559 backup.string() +
"': " + ec.message());
1561 if (removeInputsOnSuccess) {
1562 std::string failures;
1563 for (
const auto& input : inputFiles) {
1564 const auto localInput = LocalRootPath(input);
1565 if (!localInput)
continue;
1567 const auto absoluteInput = fs::weakly_canonical(fs::absolute(*localInput), ec);
1568 if (!ec && absoluteInput == target)
continue;
1569 if (!ec) fs::remove(*localInput, ec);
1570 if (ec) failures +=
"'" + input +
"': " + ec.message() +
"; ";
1572 Require(failures.empty(),
1573 "Merged output is valid, but REST could not remove input file(s): " + failures);
1575 if (error) error->clear();
1577 }
catch (
const std::exception& failure) {
1580 std::string detail = failure.what();
1581 if (!temporary.empty()) {
1583 std::filesystem::remove(temporary, ec);
1584 if (ec) detail +=
". Cannot remove temporary file '" + temporary.string() +
"': " + ec.message();
1586 if (error) *error = detail;
1597 result = _access(path.c_str(), 2);
1599 result = access(path.c_str(), 2);
1612 if (path[0] ==
'/' || path[0] ==
'~' || path.find(
':') != string::npos) {
1630 filesystem::path path(fullname);
1631 return {path.parent_path().string(), path.filename().string()};
1640 string extension = filesystem::path(fullname).extension().string();
1641 if (extension.size() > 1)
return extension.substr(1);
1651 return filesystem::path(fullname).stem().string();
1664 bool removeDuplicates) {
1665 std::vector<std::string> obsList;
1666 std::string text = observablesStr;
1667 while (text.find(
"_") != std::string::npos) {
1668 size_t pos_ = text.find(
"_");
1669 size_t beginning = text.find_last_of(
" -+*/)(^%<>", pos_) + 1;
1670 size_t end = text.find_first_of(
" -+*/)(^%<>", pos_);
1671 std::string obs = text.substr(beginning, end - beginning);
1672 text =
Replace(text, obs,
"1", 0, removeDuplicates ? 0 : 1);
1673 obsList.push_back(obs);
1690 const std::vector<std::string>& wantedStrings) {
1691 std::set<std::string> result;
1692 for (
auto& ws : wantedStrings) {
1693 if (ws.find(
"*") != std::string::npos || ws.find(
"?") != std::string::npos) {
1694 for (
auto& c : stack)
1696 }
else if (std::find(stack.begin(), stack.end(), ws) != stack.end())
1711 string to_replace =
"//";
1712 size_t start_pos = str.find(to_replace);
1713 while (start_pos != string::npos) {
1714 str.replace(start_pos, to_replace.length(),
"/");
1715 start_pos = str.find(to_replace);
1734 filesystem::path path;
1735 for (
const auto& directory : filesystem::path(filename)) {
1736 if (path.empty() && directory ==
"~") {
1738 const auto envVariableHome = getenv(
"HOME");
1739 if (envVariableHome ==
nullptr) {
1740 cout <<
"TRestTools::ToAbsoluteName - ERROR - "
1741 "cannot resolve ~ because 'HOME' env variable does not exist"
1745 const auto userHomePath = filesystem::path(envVariableHome);
1746 if (userHomePath.empty()) {
1747 cout <<
"TRestTools::ToAbsoluteName - ERROR - "
1748 "cannot resolve ~ because 'HOME' env variable is not set to a valid value"
1752 path /= userHomePath;
1757 return filesystem::weakly_canonical(path).string();
1770 vector<string> result;
1772 std::filesystem::path path(_path);
1774 std::filesystem::directory_iterator iter(path);
1775 for (
auto& it : iter) {
1776 if (it.is_directory()) {
1777 result.push_back(it.path().string());
1779 if (recursion != 0) {
1781 result.insert(result.begin(), subD.begin(), subD.end());
1798 for (
unsigned int i = 0; i < paths.size(); i++) {
1799 string path = paths[i];
1800 if (path[path.size() - 1] !=
'/') {
1805 return path + filename;
1810 for (
unsigned int j = 0; j < pathsExpanded.size(); j++)
1811 if (
fileExists(pathsExpanded[j] +
"/" + filename))
return pathsExpanded[j] +
"/" + filename;
1823 ifs.open(filename.c_str());
1842 std::vector<string> outputFileNames;
1843 if (pattern !=
"") {
1844 vector<string> items =
Split(pattern,
"\n");
1845 for (
auto item : items) {
1846 if (item.find_first_of(
"*?") != string::npos) {
1848 item =
Replace(item,
"/",
"\\");
1850 item.substr(0, item.find_first_of(
"*?"));
1852 string _path = path_name.first;
1853 if (!std::filesystem::exists(_path)) {
1854 RESTError <<
"TRestTools::GetFilesMatchingPattern(): path " << _path <<
" does not exist!"
1856 return outputFileNames;
1859 std::filesystem::path path(_path);
1860 std::filesystem::recursive_directory_iterator iter(path);
1861 for (
auto& it : iter) {
1862 if (it.is_regular_file()) {
1863 string filename = it.path().string();
1865 outputFileNames.push_back(it.path().string());
1872 std::string currentDir = filesystem::current_path();
1873 ChangeDirectory(path_name.first);
1874 string a =
Execute(
"find -type f -name \'" + path_name.second +
"\'");
1875 ChangeDirectory(currentDir);
1876 auto b =
Split(a,
"\n");
1878 for (
unsigned int i = 0; i < b.size(); i++) {
1879 outputFileNames.push_back(path_name.first +
"/" + b[i]);
1883 string a =
Execute(
"find " + item);
1884 auto b =
Split(a,
"\n");
1886 for (
unsigned int i = 0; i < b.size(); i++) {
1887 outputFileNames.push_back(b[i]);
1893 if (
fileExists(item)) outputFileNames.push_back(item);
1897 return outputFileNames;
1905#define REST_VERSION(a, b, c) (((a) << 16) + ((b) << 8) + (c))
1907 vector<string> ver =
Split(in,
".");
1908 if (ver.size() == 3) {
1910 for (
auto v : ver) {
1911 int n =
StringToInteger(v.substr(0, v.find_first_not_of(
"0123456789")));
1913 verint.push_back(n);
1918 return REST_VERSION(verint[0], verint[1], verint[2]);
1927 std::array<char, 128> buffer;
1930 std::unique_ptr<FILE,
decltype(&_pclose)> pipe(_popen((
"powershell.exe " + cmd).c_str(),
"r"), _pclose);
1932 std::unique_ptr<FILE,
decltype(&pclose)> pipe(popen(cmd.c_str(),
"r"), pclose);
1936 throw std::runtime_error(
"popen() failed!");
1938 while (fgets(buffer.data(), buffer.size(), pipe.get()) !=
nullptr) {
1939 result += buffer.data();
1942 if (result.size() > 0 && result[result.size() - 1] ==
'\n')
1943 result = result.substr(0, result.size() - 1);
1961 std::istream::sentry se(is,
true);
1962 std::streambuf* sb = is.rdbuf();
1965 int c = sb->sbumpc();
1970 if (sb->sgetc() ==
'\n') sb->sbumpc();
1972 case std::streambuf::traits_type::eof():
1974 if (t.empty()) is.setstate(std::ios::eofbit);
1991 if (pureName.empty()) {
1992 RESTWarning <<
"error! (TRestTools::DownloadRemoteFile): url is not a file!" << RESTendl;
1993 RESTWarning <<
"please specify a concrete file name in this url" << RESTendl;
1994 RESTWarning <<
"url: " << url << RESTendl;
1998 if (url.find(
"local:") == 0) {
1999 return Replace(url,
"local:",
"");
2002 REST_USER_PATH +
"/download/" + (pidPrefix ?
"PID_" + ToString(getpid()) +
"_" :
"") + pureName;
2008 RESTWarning <<
"Retrying download in 5 seconds" << RESTendl;
2009 std::this_thread::sleep_for(std::chrono::seconds(5));
2010 }
else if (attempts < 10) {
2011 RESTSuccess <<
"Download succeeded after " << 10 - attempts <<
" attempts" << RESTendl;
2014 }
while (out == 1024 && attempts > 0);
2031 TUrl url(remoteFile.c_str());
2033 RESTInfo <<
"Downloading remote file : " << remoteFile << RESTendl;
2034 RESTInfo <<
"To local file : " << localFile << RESTendl;
2036 string localFiletmp = localFile +
".restdownload";
2037 if ((
string)url.GetProtocol() ==
"https" || (
string)url.GetProtocol() ==
"http") {
2040 if (!filesystem::create_directories(path)) {
2041 std::cerr <<
"mkdir failed to create directory: " << path << std::endl;
2046 string cmd =
"wget --no-check-certificate " + EscapeSpecialLetters(remoteFile) +
" -O " +
2047 EscapeSpecialLetters(localFiletmp) +
" -q";
2048 RESTDebug << cmd << RESTendl;
2049 int a = system(cmd.c_str());
2052 rename(localFiletmp.c_str(), localFile.c_str());
2055 RESTError <<
"download failed! (" << remoteFile <<
")" << RESTendl;
2057 RESTError <<
"Network connection problem?" << RESTendl;
2061 RESTError <<
"File does NOT exist in remotely?" << RESTendl;
2065 }
else if ((
string)url.GetProtocol() ==
"ssh") {
2066 string cmd =
"scp -P " + ToString(url.GetPort() == 0 ? 22 : url.GetPort()) +
" " + url.GetUser() +
2067 "@" + url.GetHost() +
":" + EscapeSpecialLetters(url.GetFile()) +
" " + localFiletmp;
2068 cout << cmd << endl;
2069 int a = system(cmd.c_str());
2071 rename(localFiletmp.c_str(), localFile.c_str());
2076 RESTWarning <<
"Trying to download: " << remoteFile << RESTendl;
2077 RESTWarning <<
"Unknown protocol!" << RESTendl;
2089 std::string file_content =
"";
2094 string filename = REST_USER_PATH +
"/download/curl.out";
2097 curl_global_init(CURL_GLOBAL_ALL);
2099 FILE* f = fopen(filename.c_str(),
"wt");
2101 std::string request =
"";
2103 for (
auto const& x : keys) {
2104 if (n > 0) request +=
"&";
2105 request += x.first +
"=" + x.second;
2109 curl = curl_easy_init();
2114 curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
2115 curl_easy_setopt(curl, CURLOPT_WRITEDATA, (
void*)f);
2117 curl_easy_setopt(curl, CURLOPT_POSTFIELDS, request.c_str());
2120 res = curl_easy_perform(curl);
2122 if (res != CURLE_OK)
2123 RESTError <<
"curl_easy_perform() failed: " << curl_easy_strerror(res) << RESTendl;
2126 curl_easy_cleanup(curl);
2129 curl_global_cleanup();
2131 std::getline(std::ifstream(filename), file_content,
'\0');
2133 RESTError <<
"TRestTools::POSTRequest. REST framework was compiled without CURL support" << RESTendl;
2134 RESTError <<
"Please recompile REST after installing curl development libraries." << RESTendl;
2135 RESTError <<
"Depending on your system this might be: curl-dev, curl-devel or libcurl-openssl-dev. "
2137 RESTError <<
"No file will be downloaded" << RESTendl;
2140 return file_content;
2152 cout <<
"error! local file not exist!" << endl;
2157 TUrl url(remoteFile.c_str());
2158 TUrl method(methodUrl.c_str());
2159 if (method.GetProtocol() != (
string)
"") url.SetProtocol(method.GetProtocol());
2160 if (method.GetPort() != 0) url.SetPort(method.GetPort());
2161 if (method.GetUser() != (
string)
"") url.SetUser(method.GetUser());
2162 if (method.GetPasswd() != (
string)
"") url.SetPasswd(method.GetPasswd());
2164 if ((
string)url.GetProtocol() ==
"https" || (
string)url.GetProtocol() ==
"http") {
2166 }
else if ((
string)url.GetProtocol() ==
"ssh") {
2167 string cmd =
"scp -P " + ToString(url.GetPort() == 0 ? 22 : url.GetPort()) +
" " +
2168 EscapeSpecialLetters(localFile) +
" " + url.GetUser() +
"@" + url.GetHost() +
":" +
2169 EscapeSpecialLetters(url.GetFile());
2170 cout << cmd << endl;
2171 int a = system(cmd.c_str());
2174 RESTError << __PRETTY_FUNCTION__ << RESTendl;
2175 RESTError <<
"problem copying gases definitions to remote server" << RESTendl;
2176 RESTError <<
"Please report this problem at "
2177 "http://gifna.unizar.es/rest-forum/"
2187void TRestTools::ChangeDirectory(
const string& toDirectory) { filesystem::current_path(toDirectory); }
2199 for (
int i = 2; i * i <= n; i += 1 + (i > 2)) {
2200 while ((n % i) == 0) {
2205 if (n != 1) r.push_back(n);
2207 while (r.size() > 2) {
2210 auto min1 = std::min_element(r.begin(), r.end());
2214 auto it = std::find(r.begin(), r.end(), low1);
2215 if (it != r.end()) {
2216 std::iter_swap(it, r.end() - 1);
2217 r.erase(r.end() - 1);
2220 auto min2 = std::min_element(r.begin(), r.end());
2224 it = std::find(r.begin(), r.end(), low2);
2225 if (it != r.end()) {
2226 std::iter_swap(it, r.end() - 1);
2227 r.erase(r.end() - 1);
2230 int resultado = low1 * low2;
2231 r.push_back(resultado);
2234 std::sort(r.begin(), r.end());
2236 if (r.size() == 1) r.push_back(1);
2241string ValueWithQuantity::ToString()
const {
2243 auto value = fValue;
2244 if (fQuantity == ENERGY) {
2247 }
else if (fQuantity == TIME) {
2250 }
else if (fQuantity == LENGTH) {
2257 const auto abs = TMath::Abs(value);
2259 return TString::Format(
"%d", 0).Data();
2260 }
else if (abs < 1E-6) {
2261 return TString::Format(
"%.2f %s%s", value * 1E9,
"n", unit.c_str()).Data();
2262 }
else if (abs < 1E-3) {
2263 return TString::Format(
"%.2f %s%s", value * 1E6,
"u", unit.c_str()).Data();
2264 }
else if (abs < 1E0) {
2265 return TString::Format(
"%.2f %s%s", value * 1E3,
"m", unit.c_str()).Data();
2266 }
else if (abs < 1E3) {
2267 return TString::Format(
"%.2f %s%s", value * 1E0,
"", unit.c_str()).Data();
2268 }
else if (abs < 1E6) {
2269 return TString::Format(
"%.2f %s%s", value * 1E-3,
"k", unit.c_str()).Data();
2270 }
else if (abs < 1E9) {
2271 return TString::Format(
"%.2f %s%s", value * 1E-6,
"M", unit.c_str()).Data();
2272 }
else if (abs < 1E12) {
2273 return TString::Format(
"%.2f %s%s", value * 1E-9,
"G", unit.c_str()).Data();
2275 return TString::Format(
"%.2f %s%s", value * 1E-12,
"T", unit.c_str()).Data();
2279string ToTimeStringLong(
double seconds) {
2280 const auto abs = TMath::Abs(seconds);
2282 return TString::Format(
"%.2f %s", seconds,
"seconds").Data();
2283 }
else if (abs < 60 * 60) {
2284 return TString::Format(
"%.2f %s", seconds / 60.0,
"minutes").Data();
2285 }
else if (abs < 60 * 60 * 24) {
2286 return TString::Format(
"%.2f %s", seconds / (60.0 * 60.0),
"hours").Data();
2288 return TString::Format(
"%.2f %s", seconds / (60.0 * 60.0 * 24.0),
"days").Data();
static TRestRootFileHandle Open(const std::string &filename, TRestRootFileMode mode)
static bool PrepareBorrowedUpdate(TFile &file, std::string *error=nullptr)
Float_t StringToFloat(std::string in)
Gets a float from a string.
std::vector< std::string > Split(std::string in, std::string separator, bool allowBlankString=false, bool removeWhiteSpaces=false, int startPos=-1)
Split the input string according to the given separator. Returning a vector of fragments.
Bool_t MatchString(std::string str, std::string matcher)
This method matches a string with certain matcher. Returns true if matched. Supports wildcard charact...
Double_t StringToDouble(std::string in)
Gets a double from a string.
std::string ToUpper(std::string in)
Convert string to its upper case. Alternative of TString::ToUpper.
Int_t StringToInteger(std::string in)
Gets an integer from a string.
std::string Replace(std::string in, std::string thisString, std::string byThisString, size_t fromPosition=0, Int_t N=0)
Replace any occurences of thisSring by byThisString inside string in.