23#include <boost/lexical_cast.hpp>
24#include <boost/regex.hpp>
29#include <boost/algorithm/string.hpp>
32#include <json/value.h>
46bool containsWildCard(
const std::string &ext) {
return std::string::npos != ext.find(
'*'); }
48bool isASCII(
const std::string &str) {
49 return !std::any_of(str.cbegin(), str.cend(), [](
char c) { return static_cast<unsigned char>(c) > 127; });
68 FrameworkManager::Instance().loadPlugins();
74 setCaseSensitive(Kernel::ConfigService::Instance().getValue<bool>(
"filefinder.casesensitive").value_or(
false));
107 return Kernel::ConfigService::Instance().getFullPath(filename, ignoreDirs,
m_globOption);
122 std::filesystem::path entry(userString);
123 std::string noExt(entry.stem().string());
126 userString.replace(userString.size() - repNumChars, repNumChars,
"");
140 const bool returnDefaultIfNotFound)
const {
141 if ((!hint.empty()) && (!isdigit(hint[0]))) {
142 string instrName(hint);
143 std::filesystem::path path(instrName);
144 instrName = path.filename().string();
145 if (instrName.starts_with(
"PG3") || instrName.starts_with(
"pg3")) {
157 else if (instrName.starts_with(
"SANS2D") || instrName.starts_with(
"sans2d")) {
158 instrName =
"SANS2D";
162 const auto it = std::find_if(instrName.begin(), instrName.end(), isdigit);
163 const auto nChars = std::distance(instrName.begin(), it);
164 instrName.resize(nChars);
169 if (!instrName.empty()) {
170 const auto it = std::find_if(instrName.rbegin(), instrName.rend(), isalpha);
171 const auto nChars = std::distance(it, instrName.rend());
172 instrName.resize(nChars);
180 if (!returnDefaultIfNotFound) {
185 return Kernel::ConfigService::Instance().getInstrument();
194 g_log.
debug() <<
"toInstrumentAndNumber(" << hint <<
")\n";
195 std::string instrPart;
198 if (isdigit(hint[0])) {
199 instrPart = Kernel::ConfigService::Instance().getInstrument().shortName();
203 std::string::const_reverse_iterator it = std::find_if(hint.rbegin(), hint.rend(), std::not_fn(isdigit));
205 if (it == hint.rend() || it == hint.rbegin()) {
206 throw std::invalid_argument(
"Malformed hint to FileFinderImpl::makeFileName: " + hint);
208 std::string::size_type nChars = std::distance(it, hint.rend());
211 if (boost::algorithm::istarts_with(hint,
"PG3")) {
213 nChars = instrPart.length();
216 else if (boost::algorithm::istarts_with(hint,
"SANS2D")) {
217 instrPart =
"SANS2D";
218 nChars = instrPart.length();
220 instrPart = hint.substr(0, nChars);
223 runPart = hint.substr(nChars);
226 unsigned int irunPart(0);
228 irunPart = boost::lexical_cast<unsigned int>(runPart);
229 }
catch (boost::bad_lexical_cast &) {
230 std::ostringstream os;
231 os <<
"Cannot convert '" << runPart <<
"' to run number.";
232 throw std::invalid_argument(os.str());
237 std::string::size_type i = runPart.find_first_not_of(
'0');
239 while (runPart.size() < nZero)
240 runPart.insert(0,
"0");
241 if (runPart.size() > nZero && nZero != 0) {
242 throw std::invalid_argument(
"Run number does not match instrument's zero padding");
247 return std::make_pair(instrPart, runPart);
266 std::string filename(hint);
268 const std::string shortName = instrument.
shortName();
269 std::string delimiter = instrument.
delimiter();
272 if (filename.substr(0, shortName.size()) == shortName) {
273 filename = filename.substr(shortName.size());
274 if ((!delimiter.empty()) && (filename.substr(0, delimiter.size()) == delimiter))
275 filename = filename.substr(delimiter.size());
277 filename = shortName + filename;
283 filename = instrumentName + delimiter + runNumber + suffix;
297 g_log.
debug() <<
"getExtension(" << filename <<
", exts[" << exts.size() <<
"])\n";
300 for (
const auto &ext : exts) {
301 std::string extension =
toUpper(ext);
302 if (extension.rfind(
'*') == extension.size() - 1)
304 extension.resize(extension.rfind(
'*'));
307 std::size_t found =
toUpper(filename).rfind(extension);
308 if (found != std::string::npos) {
309 g_log.
debug() <<
"matched extension \"" << extension <<
"\" based on \"" << ext <<
"\"\n";
310 return filename.substr(found);
314 g_log.
debug() <<
"Failed to find extension. Just using last \'.\'\n";
315 std::size_t pos = filename.find_last_of(
'.');
316 if (pos != std::string::npos) {
317 return filename.substr(pos);
325 std::vector<IArchiveSearch_sptr> archs;
328 std::string archiveOpt = Kernel::ConfigService::Instance().getString(
"datasearch.searcharchive");
329 std::transform(archiveOpt.begin(), archiveOpt.end(), archiveOpt.begin(), tolower);
333 if (archiveOpt.empty() || archiveOpt ==
"off" || facility.
archiveSearch().empty())
337 auto createArchiveSearch = bool(archiveOpt ==
"all");
341 if (!createArchiveSearch) {
342 std::string faciltyName = facility.
name();
343 std::transform(faciltyName.begin(), faciltyName.end(), faciltyName.begin(), tolower);
344 if (archiveOpt ==
"on") {
345 std::string defaultFacility = Kernel::ConfigService::Instance().getString(
"default.facility");
346 std::transform(defaultFacility.begin(), defaultFacility.end(), defaultFacility.begin(), tolower);
347 createArchiveSearch = bool(faciltyName == defaultFacility);
349 createArchiveSearch = bool(archiveOpt.find(faciltyName) != std::string::npos);
354 if (createArchiveSearch) {
356 g_log.
debug() <<
"get archive search for the facility..." << facilityname <<
"\n";
357 archs.emplace_back(ArchiveSearchFactory::Instance().create(facilityname));
375 const std::vector<std::string> &extensionsProvided,
376 const bool useOnlyExtensionsProvided)
const {
378 g_log.
debug() <<
"vector findRun(\'" << hint <<
"\', exts[" << extensionsProvided.size() <<
"])\n";
385 std::filesystem::path hintPath(hint);
386 if (hintPath.has_extension()) {
388 g_log.
debug() <<
"hintPath is not empty, check in normal search locations"
393 if (std::filesystem::exists(path)) {
397 }
catch (
const std::exception &) {
400 g_log.
debug() <<
"Unable to find files via directory search with the "
401 "filename that looks like a full filename"
410 const std::vector<std::string> facilityExtensions = facility.
extensions();
413 std::string filename(hint);
414 std::string extension =
getExtension(hint, facilityExtensions);
415 if (!facilityExtensions.empty())
416 filename = hint.substr(0, hint.rfind(extension));
417 if (hintPath.parent_path().empty()) {
422 }
catch (std::invalid_argument &) {
423 if (filename.length() >= hint.length()) {
424 g_log.
information() <<
"Could not form filename from standard rules '" << filename <<
"'\n";
429 if (filename.empty())
439 std::set<std::string> filenames;
440 filenames.insert(filename);
442 std::string transformed(filename);
443 std::transform(filename.begin(), filename.end(), transformed.begin(), toupper);
444 filenames.insert(transformed);
445 std::transform(filename.begin(), filename.end(), transformed.begin(), tolower);
446 filenames.insert(transformed);
451 std::vector<std::string> extensionsToSearch;
452 extensionsToSearch.reserve(1 + extensionsProvided.size() + facilityExtensions.size());
454 if (useOnlyExtensionsProvided) {
458 if (!extension.empty()) {
459 extensionsToSearch.emplace_back(extension);
470 auto path =
getPath(archs, filenames, extensionsToSearch);
478 if (!useOnlyExtensionsProvided && extensionsToSearch.size() == 1) {
480 extensionsToSearch.pop_back();
484 g_log.
warning() <<
"Extension ['" << extension <<
"'] not found.\n";
485 g_log.
warning() <<
"Searching for other facility extensions." << std::endl;
487 path =
getPath(archs, filenames, extensionsToSearch);
506 std::vector<std::string> &uniqueExts)
const {
508 for (
const auto &cit : extensionsToAdd) {
509 std::string transformed(cit);
510 if (!isCaseSensitive) {
511 std::transform(cit.begin(), cit.end(), transformed.begin(), tolower);
513 const auto searchItr = std::find(uniqueExts.begin(), uniqueExts.end(), transformed);
514 if (searchItr == uniqueExts.end()) {
515 uniqueExts.emplace_back(transformed);
527 if (!isASCII(searchText))
528 return "An unsupported non-ASCII character was found in the search text.";
548 const std::vector<std::string> &extensionsProvided,
549 const bool useOnlyExtensionsProvided)
const {
552 throw std::invalid_argument(
error);
555 g_log.
debug() <<
"findRuns hint = " << hint <<
"\n";
556 std::vector<std::string> res;
559 static const boost::regex digits(
"[0-9]+");
560 auto h = hints.
begin();
562 std::string instrSName;
563 for (; h != hints.
end(); ++h) {
565 bool fileSuspected =
false;
567 if ((*h).find(
"\\") != std::string::npos) {
568 fileSuspected =
true;
570 if ((*h).find(
"/") != std::string::npos) {
571 fileSuspected =
true;
574 fileSuspected =
true;
579 if ((range.
count() > 2) && (!fileSuspected)) {
580 throw std::invalid_argument(
"Malformed range of runs: " + *h);
581 }
else if ((range.
count() == 2) && (!fileSuspected)) {
583 if (boost::algorithm::istarts_with(hint,
"PG3")) {
586 std::string run = p1.second;
587 size_t nZero = run.size();
588 if (range[1].size() > nZero) {
589 throw std::invalid_argument(
"Malformed range of runs: " + *h +
590 ". The end of string value is longer than "
591 "the instrument's zero padding");
593 auto runNumber = boost::lexical_cast<int>(run);
594 std::string runEnd = run;
596 runEnd.replace(runEnd.end() - range[1].
size(), runEnd.end(), range[1]);
599 if (!boost::regex_match(runEnd, digits))
600 throw std::invalid_argument(
"Malformed range of runs: Part of the run "
601 "has a non-digit character in it.");
603 auto runEndNumber = boost::lexical_cast<int>(runEnd);
604 if (runEndNumber < runNumber) {
605 throw std::invalid_argument(
"Malformed range of runs: " + *h);
607 std::string previousPath, previousExt;
608 for (
int irun = runNumber; irun <= runEndNumber; ++irun) {
610 while (run.size() < nZero)
615 if (!previousPath.empty() && !previousExt.empty()) {
617 const std::filesystem::path file(previousPath + p1.first + run + previousExt);
618 if (std::filesystem::exists(file)) {
619 res.emplace_back(file.string());
624 previousPath = previousExt =
"";
629 if (boost::algorithm::istarts_with(hint,
"PG3")) {
630 path =
findRun(instrSName + run, extensionsProvided, useOnlyExtensionsProvided).result();
632 path =
findRun(p1.first + run, extensionsProvided, useOnlyExtensionsProvided).result();
637 std::filesystem::path tempPath(path);
638 previousExt = tempPath.extension().string();
640 previousPath = tempPath.parent_path().string() + std::string(1, std::filesystem::path::preferred_separator);
641 res.emplace_back(path);
649 if (boost::algorithm::istarts_with(hint,
"PG3")) {
650 if (h == hints.
begin()) {
652 path =
findRun(*h, extensionsProvided, useOnlyExtensionsProvided).result();
654 path =
findRun(instrSName + *h, extensionsProvided, useOnlyExtensionsProvided).result();
657 path =
findRun(*h, extensionsProvided, useOnlyExtensionsProvided).result();
660 res.emplace_back(path);
672 const std::set<std::string> &filenames,
673 const std::vector<std::string> &exts)
const {
677 for (
const auto &filename : filenames) {
679 std::string parentDirPath;
682 parentDirPath = dataCache.getFileParentDirectoryPath(filename);
684 }
catch (
const std::invalid_argument &e) {
685 errors +=
"Data cache: " + std::string(e.what());
688 }
catch (
const Json::Exception &e) {
689 errors +=
"Data cache: Failed parsing to JSON: " + std::string(e.what()) +
690 "Error likely due to accessing instrument index file while it was being updated on IDAaaS.";
694 if (!std::filesystem::exists(parentDirPath)) {
695 errors +=
"Data cache: Directory not found: " + parentDirPath;
699 for (
const auto &ext : exts) {
700 std::filesystem::path filePath(parentDirPath +
'/' + filename + ext);
703 if (std::filesystem::exists(filePath)) {
706 }
catch (
const std::filesystem::filesystem_error &e) {
707 errors +=
"Data cache: " + std::string(e.what());
711 errors +=
"Data cache: " + filename +
" not found in " + parentDirPath;
727 const std::set<std::string> &filenames,
728 const std::vector<std::string> &exts)
const {
729 g_log.
debug() <<
"getArchivePath([IArchiveSearch_sptr], [ ";
730 for (
const auto &iter : filenames)
733 for (
const auto &iter : exts)
738 for (
const auto &arch : archs) {
740 g_log.
debug() <<
"Getting archive path for requested files\n";
741 auto path = arch->getArchivePath(filenames, exts);
745 errors += path.errors();
764 const std::set<std::string> &filenames,
765 const std::vector<std::string> &exts)
const {
768 std::vector<std::string> extensions;
769 extensions.assign(exts.begin(), exts.end());
772 extensions.erase(std::remove_if(extensions.begin(), extensions.end(), containsWildCard), extensions.end());
774 const std::vector<std::string> &searchPaths = Kernel::ConfigService::Instance().getDataSearchDirs();
782 for (
const auto &extension : extensions) {
783 for (
const auto &filename : filenames) {
784 for (
const auto &searchPath : searchPaths) {
786 const std::filesystem::path filePath = std::filesystem::path(searchPath) / (filename + extension);
787 if (std::filesystem::exists(filePath))
790 }
catch (
const std::exception &) {
796 for (
const auto &extension : extensions) {
797 for (
const auto &filename : filenames) {
800 if (!path.empty() && std::filesystem::exists(path)) {
801 g_log.
debug() <<
"path returned from getFullPath() = " << path <<
'\n';
804 }
catch (std::exception &e) {
805 g_log.
error() <<
"Cannot open file " << path <<
": " << e.what() <<
'\n';
813 std::filesystem::path cachePathToSearch(Kernel::ConfigService::Instance().getString(
"datacachesearch.directory"));
815 if (std::filesystem::exists(cachePathToSearch)) {
821 return cacheFilePath;
823 errors += cacheFilePath.
errors();
826 g_log.
debug() <<
"Data cache directory not found, proceeding with the search." << std::endl;
827 errors +=
"Could not find data cache directory: " + cachePathToSearch.string() +
'\n';
831 if (!archs.empty()) {
836 if (std::filesystem::exists(archivePath.result()))
838 }
catch (std::exception &e) {
839 g_log.
error() <<
"Cannot open file " << archivePath <<
": " << e.what() <<
'\n';
843 errors += archivePath.errors();
850 std::string result = src;
851 std::transform(result.begin(), result.end(), result.begin(), toupper);
std::string validateRuns(const std::string &searchText) const
A method that returns error messages if the provided runs are invalid.
std::pair< std::string, std::string > toInstrumentAndNumber(const std::string &hint) const
Extracts the instrument name and run number from a hint.
std::string makeFileName(const std::string &hint, const Kernel::InstrumentInfo &instrument) const
DO NOT USE! MADE PUBLIC FOR TESTING ONLY.
static std::vector< IArchiveSearch_sptr > getArchiveSearch(const Kernel::FacilityInfo &facility)
bool getCaseSensitive() const
Option to get if file finder should be case sensitive.
std::string getExtension(const std::string &filename, const std::vector< std::string > &exts) const
DO NOT USE! MADE PUBLIC FOR TESTING ONLY.
const API::Result< std::string > findRun(const std::string &hintstr, const std::vector< std::string > &exts={}, const bool useExtsOnly=false) const
Find a path to a single file from a hint.
std::string getFullPath(const std::string &filename, const bool ignoreDirs=false) const
Return the full path to the file given its name.
int m_globOption
glob option - set to case sensitive or insensitive
std::string extractAllowedSuffix(std::string &userString) const
Run numbers can be followed by an allowed string.
std::vector< std::string > findRuns(const std::string &hintstr, const std::vector< std::string > &exts={}, const bool useExtsOnly=false) const
Find a list of files file given a hint.
static const std::string ALLOWED_SUFFIX
a string that is allowed at the end of any run number
FileFinderImpl()
Default constructor.
void getUniqueExtensions(const std::vector< std::string > &extensionsToAdd, std::vector< std::string > &uniqueExts) const
Given a set of already determined extensions and new extensions, create a set of all extensions.
std::string toUpper(const std::string &src) const
void setCaseSensitive(const bool cs)
Option to set if file finder should be case sensitive.
const API::Result< std::string > getPath(const std::vector< IArchiveSearch_sptr > &archs, const std::set< std::string > &filenames, const std::vector< std::string > &exts) const
Return the full path to the file given its name, checking local directories first.
const API::Result< std::string > getArchivePath(const std::vector< IArchiveSearch_sptr > &archs, const std::set< std::string > &filenames, const std::vector< std::string > &exts) const
Return the path to the file found in archive.
const API::Result< std::string > getISISInstrumentDataCachePath(const std::string &cachePathToSearch, const std::set< std::string > &filenames, const std::vector< std::string > &exts) const
const Kernel::InstrumentInfo getInstrument(const std::string &hint, const bool returnDefaultIfNotFound=true) const
DO NOT USE! MADE PUBLIC FOR TESTING ONLY.
const std::string & errors() const
Exception for when an item is not found in a collection.
const char * what() const noexcept override
Writes out the range and limits.
A class that holds information about a facility.
const std::vector< std::string > & archiveSearch() const
Return the archive search interface names.
const std::vector< std::string > & extensions() const
Returns a list of file extensions.
bool noFilePrefix() const
Returns a bool indicating whether prefix is required in file names.
const std::string & name() const
Return the name of the facility.
static constexpr int GLOB_DEFAULT
Glob option constants (compatible with Poco::Glob)
static constexpr int GLOB_CASELESS
A class that holds information about an instrument.
const std::string & shortName() const
Return the short name of the instrument.
std::string filePrefix(unsigned int runNumber) const
Returns file prefix for this instrument and a run number.
const FacilityInfo & facility() const
The facility to which this instrument belongs.
const std::string & delimiter() const
Returns the default delimiter between instrument name and run number.
int zeroPadding(unsigned int runNumber) const
Returns zero padding for this instrument and a run number.
The Logger class is in charge of the publishing messages from the framework through various channels.
void debug(const std::string &msg)
Logs at debug level.
void error(const std::string &msg)
Logs at error level.
void warning(const std::string &msg)
Logs at warning level.
void information(const std::string &msg)
Logs at information level.
Iterator begin()
Iterator referring to first element in the container.
@ TOK_IGNORE_EMPTY
ignore empty tokens
@ TOK_TRIM
remove leading and trailing whitespace from tokens
std::size_t size() const noexcept
Get the total number of tokens.
Iterator end()
Iterator referring to the past-the-end element in the container.
std::size_t count() const
Get the total number of tokens.
Kernel::Logger g_log("ExperimentInfo")
static logger object
Kernel::Logger g_log("DetermineSpinStateOrder")
MANTID_KERNEL_DLL std::string strip(const std::string &A)
strip pre/post spaces
std::string to_string(const wide_integer< Bits, Signed > &n)