CodeCompass
79 строк · 1.9 Кб
1#include <cstdlib>
2#include <climits>
3#include <unistd.h>
4
5#include <boost/filesystem.hpp>
6
7#include <util/filesystem.h>
8
9namespace fs = boost::filesystem;
10
11namespace cc
12{
13namespace util
14{
15
16std::string binaryPathToInstallDir(const char* path)
17{
18// Expand the path to a full path as given by the shell. This is then stripped
19// of any symbolic links and relative references.
20// The path is then parented twice (from binary to "bin" folder, and then
21// the root).
22// If the path does not exist, the given binary is searched for in the PATH
23// environment variable.
24// TODO: replace else branch with fs::search_path if Boost 1.64 or above is used.
25
26if (fs::exists(fs::system_complete(fs::path(path))))
27{
28return fs::canonical(fs::system_complete(fs::path(path)))
29.parent_path().parent_path().string();
30}
31else
32{
33fs::path pPath;
34std::string fullPath = std::getenv("PATH");
35std::string delimiter = ":";
36
37std::size_t pos = 0;
38while ((pos = fullPath.find(delimiter)) != std::string::npos)
39{
40pPath = fs::path(fullPath.substr(0, pos)) / fs::path(path);
41
42if (fs::exists(fs::path(pPath)))
43{
44return fs::canonical(pPath)
45.parent_path().parent_path().string();
46}
47
48fullPath.erase(0, pos + delimiter.length());
49}
50}
51
52throw std::runtime_error(std::string("Could not find ") + path + std::string("."));
53}
54
55std::string findCurrentExecutableDir()
56{
57char exePath[PATH_MAX];
58ssize_t len = ::readlink("/proc/self/exe", exePath, sizeof(exePath));
59
60if (len == -1 || len == sizeof(exePath))
61len = 0;
62
63exePath[len] = '\0';
64return fs::path(exePath).parent_path().string();
65}
66
67bool isRootedUnderAnyOf(
68const std::vector<std::string>& paths_,
69const std::string& path_)
70{
71auto it = paths_.begin();
72const auto end = paths_.end();
73while (it != end && path_.rfind(*it, 0) != 0)
74++it;
75return it != end;
76}
77
78} // namespace util
79} // namespace cc
80