18 #include <boost/algorithm/string/predicate.hpp>
19 #include <boost/algorithm/string/regex.hpp>
20 #include <boost/filesystem.hpp>
29 return "package://picovoice_driver/resources";
34 return std::string(
"/tmp/picovoice_driver/" +
name);
39 if (!boost::filesystem::exists(path))
41 throw std::runtime_error(
"Path '" + path +
"' does not exist");
43 if (!extension.empty() && !boost::algorithm::ends_with(path, extension))
45 throw std::runtime_error(
"Path '" + path +
"' does not match extension '" + extension +
"'");
49 std::string
pathFromUrl(
const std::string&
url,
const std::string& extension,
const std::string& directory)
53 if (
url.find(
"://") == std::string::npos && !directory.empty())
57 if (boost::filesystem::exists(directory +
"/" +
url) && boost::algorithm::ends_with(
url, extension))
59 return directory +
"/" +
url;
61 if (boost::filesystem::exists(directory +
"/" +
url + extension))
63 return directory +
"/" +
url + extension;
66 std::vector<std::string> candidates;
67 for (
const auto& entry : boost::make_iterator_range(boost::filesystem::directory_iterator(directory)))
69 if (entry.path().extension().string() == extension)
71 candidates.push_back(entry.path().stem().string());
74 throw std::runtime_error(
"Invalid relative file '" +
url +
"'. Available: " +
toString(candidates));
77 std::vector<std::string> parts;
78 boost::algorithm::split_regex(parts,
url, boost::regex(
"://"));
79 if (parts.size() != 2)
81 throw std::runtime_error(
"Invalid package or file url");
83 const std::string& url_type = parts.front();
84 const std::string& url_arg = parts.back();
86 if (url_type ==
"package")
88 size_t first_slash_pos = url_arg.find(
"/");
89 std::string
package = url_arg.substr(0, first_slash_pos);
90 std::string path_relative_to_package = first_slash_pos < url_arg.size() ? url_arg.substr(first_slash_pos) :
"";
95 throw std::runtime_error(
"Could not find package + '" +
package +
"'");
97 auto path = pkg_path + path_relative_to_package;
101 else if (url_type ==
"file")
106 throw std::runtime_error(
"Invalid url type '" + url_type +
"'");
108 catch (
const std::exception& e)
110 std::string err =
"Failed to get path from url '" +
url +
"': " + std::string(e.what()) +
111 " - The url should be of form {package://path_relative_to_package" + extension +
112 ", file:///absolute/path" + extension +
"}";
113 if (!directory.empty() && !extension.empty())
115 err +=
" or a filename[" + extension +
"] relative to directory '" + directory +
"'";
117 throw std::runtime_error(err);