23#include <Poco/Exception.h>
26#include <boost/lexical_cast.hpp>
27#include <boost/regex.hpp>
32#include <boost/algorithm/string.hpp>
35#include <json/value.h>
49bool containsWildCard(
const std::string &ext) {
return std::string::npos != ext.find(
'*'); }
51bool isASCII(
const std::string &str) {
52 return !std::any_of(str.cbegin(), str.cend(), [](
char c) { return static_cast<unsigned char>(c) > 127; });
71 FrameworkManager::Instance().loadPlugins();
77 setCaseSensitive(Kernel::ConfigService::Instance().getValue<bool>(
"filefinder.casesensitive").value_or(
false));
110 return Kernel::ConfigService::Instance().getFullPath(filename, ignoreDirs,
m_globOption);
125 Poco::Path entry(userString);
126 std::string noExt(entry.getBaseName());
129 userString.replace(userString.size() - repNumChars, repNumChars,
"");
143 const bool returnDefaultIfNotFound)
const {
144 if ((!hint.empty()) && (!isdigit(hint[0]))) {
145 string instrName(hint);
146 Poco::Path path(instrName);
147 instrName = path.getFileName();
148 if (instrName.starts_with(
"PG3") || instrName.starts_with(
"pg3")) {
160 else if (instrName.starts_with(
"SANS2D") || instrName.starts_with(
"sans2d")) {
161 instrName =
"SANS2D";
165 const auto it = std::find_if(instrName.begin(), instrName.end(), isdigit);
166 const auto nChars = std::distance(instrName.begin(), it);
167 instrName.resize(nChars);
172 if (!instrName.empty()) {
173 const auto it = std::find_if(instrName.rbegin(), instrName.rend(), isalpha);
174 const auto nChars = std::distance(it, instrName.rend());
175 instrName.resize(nChars);
183 if (!returnDefaultIfNotFound) {
188 return Kernel::ConfigService::Instance().getInstrument();
197 g_log.
debug() <<
"toInstrumentAndNumber(" << hint <<
")\n";
198 std::string instrPart;
201 if (isdigit(hint[0])) {
202 instrPart = Kernel::ConfigService::Instance().getInstrument().shortName();
206 std::string::const_reverse_iterator it = std::find_if(hint.rbegin(), hint.rend(), std::not_fn(isdigit));
208 if (it == hint.rend() || it == hint.rbegin()) {
209 throw std::invalid_argument(
"Malformed hint to FileFinderImpl::makeFileName: " + hint);
211 std::string::size_type nChars = std::distance(it, hint.rend());
214 if (boost::algorithm::istarts_with(hint,
"PG3")) {
216 nChars = instrPart.length();
219 else if (boost::algorithm::istarts_with(hint,
"SANS2D")) {
220 instrPart =
"SANS2D";
221 nChars = instrPart.length();
223 instrPart = hint.substr(0, nChars);
226 runPart = hint.substr(nChars);
229 unsigned int irunPart(0);
231 irunPart = boost::lexical_cast<unsigned int>(runPart);
232 }
catch (boost::bad_lexical_cast &) {
233 std::ostringstream os;
234 os <<
"Cannot convert '" << runPart <<
"' to run number.";
235 throw std::invalid_argument(os.str());
240 std::string::size_type i = runPart.find_first_not_of(
'0');
242 while (runPart.size() < nZero)
243 runPart.insert(0,
"0");
244 if (runPart.size() > nZero && nZero != 0) {
245 throw std::invalid_argument(
"Run number does not match instrument's zero padding");
250 return std::make_pair(instrPart, runPart);
269 std::string filename(hint);
271 const std::string shortName = instrument.
shortName();
272 std::string delimiter = instrument.
delimiter();
275 if (filename.substr(0, shortName.size()) == shortName) {
276 filename = filename.substr(shortName.size());
277 if ((!delimiter.empty()) && (filename.substr(0, delimiter.size()) == delimiter))
278 filename = filename.substr(delimiter.size());
280 filename = shortName + filename;
286 filename = instrumentName + delimiter + runNumber + suffix;
300 g_log.
debug() <<
"getExtension(" << filename <<
", exts[" << exts.size() <<
"])\n";
303 for (
const auto &ext : exts) {
304 std::string extension =
toUpper(ext);
305 if (extension.rfind(
'*') == extension.size() - 1)
307 extension.resize(extension.rfind(
'*'));
310 std::size_t found =
toUpper(filename).rfind(extension);
311 if (found != std::string::npos) {
312 g_log.
debug() <<
"matched extension \"" << extension <<
"\" based on \"" << ext <<
"\"\n";
313 return filename.substr(found);
317 g_log.
debug() <<
"Failed to find extension. Just using last \'.\'\n";
318 std::size_t pos = filename.find_last_of(
'.');
319 if (pos != std::string::npos) {
320 return filename.substr(pos);
328 std::vector<IArchiveSearch_sptr> archs;
331 std::string archiveOpt = Kernel::ConfigService::Instance().getString(
"datasearch.searcharchive");
332 std::transform(archiveOpt.begin(), archiveOpt.end(), archiveOpt.begin(), tolower);
336 if (archiveOpt.empty() || archiveOpt ==
"off" || facility.
archiveSearch().empty())
340 auto createArchiveSearch = bool(archiveOpt ==
"all");
344 if (!createArchiveSearch) {
345 std::string faciltyName = facility.
name();
346 std::transform(faciltyName.begin(), faciltyName.end(), faciltyName.begin(), tolower);
347 if (archiveOpt ==
"on") {
348 std::string defaultFacility = Kernel::ConfigService::Instance().getString(
"default.facility");
349 std::transform(defaultFacility.begin(), defaultFacility.end(), defaultFacility.begin(), tolower);
350 createArchiveSearch = bool(faciltyName == defaultFacility);
352 createArchiveSearch = bool(archiveOpt.find(faciltyName) != std::string::npos);
357 if (createArchiveSearch) {
359 g_log.
debug() <<
"get archive search for the facility..." << facilityname <<
"\n";
360 archs.emplace_back(ArchiveSearchFactory::Instance().create(facilityname));
378 const std::vector<std::string> &extensionsProvided,
379 const bool useOnlyExtensionsProvided)
const {
381 g_log.
debug() <<
"vector findRun(\'" << hint <<
"\', exts[" << extensionsProvided.size() <<
"])\n";
388 Poco::Path hintPath(hint);
389 if (!hintPath.getExtension().empty()) {
391 g_log.
debug() <<
"hintPath is not empty, check in normal search locations"
396 if (Poco::File(path).
exists()) {
400 }
catch (Poco::Exception &) {
403 g_log.
debug() <<
"Unable to find files via directory search with the "
404 "filename that looks like a full filename"
413 const std::vector<std::string> facilityExtensions = facility.
extensions();
416 std::string filename(hint);
417 std::string extension =
getExtension(hint, facilityExtensions);
418 if (!facilityExtensions.empty())
419 filename = hint.substr(0, hint.rfind(extension));
420 if (hintPath.depth() == 0) {
425 }
catch (std::invalid_argument &) {
426 if (filename.length() >= hint.length()) {
427 g_log.
information() <<
"Could not form filename from standard rules '" << filename <<
"'\n";
432 if (filename.empty())
442 std::set<std::string> filenames;
443 filenames.insert(filename);
445 std::string transformed(filename);
446 std::transform(filename.begin(), filename.end(), transformed.begin(), toupper);
447 filenames.insert(transformed);
448 std::transform(filename.begin(), filename.end(), transformed.begin(), tolower);
449 filenames.insert(transformed);
454 std::vector<std::string> extensionsToSearch;
455 extensionsToSearch.reserve(1 + extensionsProvided.size() + facilityExtensions.size());
457 if (useOnlyExtensionsProvided) {
461 if (!extension.empty()) {
462 extensionsToSearch.emplace_back(extension);
473 auto path =
getPath(archs, filenames, extensionsToSearch);
481 if (!useOnlyExtensionsProvided && extensionsToSearch.size() == 1) {
483 extensionsToSearch.pop_back();
487 g_log.
warning() <<
"Extension ['" << extension <<
"'] not found.\n";
488 g_log.
warning() <<
"Searching for other facility extensions." << std::endl;
490 path =
getPath(archs, filenames, extensionsToSearch);
509 std::vector<std::string> &uniqueExts)
const {
511 for (
const auto &cit : extensionsToAdd) {
512 std::string transformed(cit);
513 if (!isCaseSensitive) {
514 std::transform(cit.begin(), cit.end(), transformed.begin(), tolower);
516 const auto searchItr = std::find(uniqueExts.begin(), uniqueExts.end(), transformed);
517 if (searchItr == uniqueExts.end()) {
518 uniqueExts.emplace_back(transformed);
530 if (!isASCII(searchText))
531 return "An unsupported non-ASCII character was found in the search text.";
551 const std::vector<std::string> &extensionsProvided,
552 const bool useOnlyExtensionsProvided)
const {
555 throw std::invalid_argument(
error);
558 g_log.
debug() <<
"findRuns hint = " << hint <<
"\n";
559 std::vector<std::string> res;
562 static const boost::regex digits(
"[0-9]+");
563 auto h = hints.
begin();
565 std::string instrSName;
566 for (; h != hints.
end(); ++h) {
568 bool fileSuspected =
false;
570 if ((*h).find(
"\\") != std::string::npos) {
571 fileSuspected =
true;
573 if ((*h).find(
"/") != std::string::npos) {
574 fileSuspected =
true;
577 fileSuspected =
true;
582 if ((range.
count() > 2) && (!fileSuspected)) {
583 throw std::invalid_argument(
"Malformed range of runs: " + *h);
584 }
else if ((range.
count() == 2) && (!fileSuspected)) {
586 if (boost::algorithm::istarts_with(hint,
"PG3")) {
589 std::string run = p1.second;
590 size_t nZero = run.size();
591 if (range[1].size() > nZero) {
592 throw std::invalid_argument(
"Malformed range of runs: " + *h +
593 ". The end of string value is longer than "
594 "the instrument's zero padding");
596 auto runNumber = boost::lexical_cast<int>(run);
597 std::string runEnd = run;
599 runEnd.replace(runEnd.end() - range[1].
size(), runEnd.end(), range[1]);
602 if (!boost::regex_match(runEnd, digits))
603 throw std::invalid_argument(
"Malformed range of runs: Part of the run "
604 "has a non-digit character in it.");
606 auto runEndNumber = boost::lexical_cast<int>(runEnd);
607 if (runEndNumber < runNumber) {
608 throw std::invalid_argument(
"Malformed range of runs: " + *h);
610 std::string previousPath, previousExt;
611 for (
int irun = runNumber; irun <= runEndNumber; ++irun) {
613 while (run.size() < nZero)
618 if (!previousPath.empty() && !previousExt.empty()) {
620 const Poco::File file(previousPath + p1.first + run + previousExt);
622 res.emplace_back(file.path());
627 previousPath = previousExt =
"";
632 if (boost::algorithm::istarts_with(hint,
"PG3")) {
633 path =
findRun(instrSName + run, extensionsProvided, useOnlyExtensionsProvided).result();
635 path =
findRun(p1.first + run, extensionsProvided, useOnlyExtensionsProvided).result();
640 auto tempPath = Poco::Path(path);
641 previousExt =
"." + tempPath.getExtension();
642 previousPath = tempPath.makeParent().toString();
643 res.emplace_back(path);
651 if (boost::algorithm::istarts_with(hint,
"PG3")) {
652 if (h == hints.
begin()) {
654 path =
findRun(*h, extensionsProvided, useOnlyExtensionsProvided).result();
656 path =
findRun(instrSName + *h, extensionsProvided, useOnlyExtensionsProvided).result();
659 path =
findRun(*h, extensionsProvided, useOnlyExtensionsProvided).result();
662 res.emplace_back(path);
674 const std::set<std::string> &filenames,
675 const std::vector<std::string> &exts)
const {
679 for (
const auto &filename : filenames) {
681 std::string parentDirPath;
684 parentDirPath = dataCache.getFileParentDirectoryPath(filename);
686 }
catch (
const std::invalid_argument &e) {
687 errors +=
"Data cache: " + std::string(e.what());
690 }
catch (
const Json::Exception &e) {
691 errors +=
"Data cache: Failed parsing to JSON: " + std::string(e.what()) +
692 "Error likely due to accessing instrument index file while it was being updated on IDAaaS.";
696 if (!std::filesystem::exists(parentDirPath)) {
697 errors +=
"Data cache: Directory not found: " + parentDirPath;
701 for (
const auto &ext : exts) {
702 std::filesystem::path filePath(parentDirPath +
'/' + filename + ext);
705 if (std::filesystem::exists(filePath)) {
708 }
catch (
const std::filesystem::filesystem_error &e) {
709 errors +=
"Data cache: " + std::string(e.what());
713 errors +=
"Data cache: " + filename +
" not found in " + parentDirPath;
729 const std::set<std::string> &filenames,
730 const std::vector<std::string> &exts)
const {
731 g_log.
debug() <<
"getArchivePath([IArchiveSearch_sptr], [ ";
732 for (
const auto &iter : filenames)
735 for (
const auto &iter : exts)
740 for (
const auto &arch : archs) {
742 g_log.
debug() <<
"Getting archive path for requested files\n";
743 auto path = arch->getArchivePath(filenames, exts);
747 errors += path.errors();
766 const std::set<std::string> &filenames,
767 const std::vector<std::string> &exts)
const {
770 std::vector<std::string> extensions;
771 extensions.assign(exts.begin(), exts.end());
774 extensions.erase(std::remove_if(extensions.begin(), extensions.end(), containsWildCard), extensions.end());
776 const std::vector<std::string> &searchPaths = Kernel::ConfigService::Instance().getDataSearchDirs();
784 for (
const auto &extension : extensions) {
785 for (
const auto &filename : filenames) {
786 for (
const auto &searchPath : searchPaths) {
788 const Poco::Path filePath(searchPath, filename + extension);
789 const Poco::File file(filePath);
793 }
catch (Poco::Exception &) {
799 for (
const auto &extension : extensions) {
800 for (
const auto &filename : filenames) {
803 if (!path.empty() && Poco::File(path).exists()) {
804 g_log.
debug() <<
"path returned from getFullPath() = " << path <<
'\n';
807 }
catch (std::exception &e) {
808 g_log.
error() <<
"Cannot open file " << path <<
": " << e.what() <<
'\n';
816 std::filesystem::path cachePathToSearch(Kernel::ConfigService::Instance().getString(
"datacachesearch.directory"));
818 if (std::filesystem::exists(cachePathToSearch)) {
824 return cacheFilePath;
826 errors += cacheFilePath.
errors();
829 g_log.
debug() <<
"Data cache directory not found, proceeding with the search." << std::endl;
830 errors +=
"Could not find data cache directory: " + cachePathToSearch.string() +
'\n';
834 if (!archs.empty()) {
839 if (Poco::File(archivePath.result()).exists())
841 }
catch (std::exception &e) {
842 g_log.
error() <<
"Cannot open file " << archivePath <<
": " << e.what() <<
'\n';
846 errors += archivePath.errors();
853 std::string result = src;
854 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")
bool exists(Nexus::File &file, const std::string &name)
MANTID_KERNEL_DLL std::string strip(const std::string &A)
strip pre/post spaces
std::string to_string(const wide_integer< Bits, Signed > &n)