1
0
forked from blue/pica
pica/utils/helpers.cpp

62 lines
2.0 KiB
C++
Raw Normal View History

// SPDX-FileCopyrightText: 2023 Yury Gubich <blue@macaw.me>
// SPDX-License-Identifier: GPL-3.0-or-later
#include "helpers.h"
#include "iostream"
#include "config.h"
static bool installed = false;
static std::filesystem::path sPath;
void setAbsoluteSharedPath () {
installed = true;
sPath = FULL_DATA_DIR "/" PROJECT_NAME; // should be something like /usr/share/pica or /local/usr/share/pica
}
void initPaths(const char* programPath) {
std::filesystem::path pp(programPath);
if (pp.filename() == programPath)
return setAbsoluteSharedPath();
std::filesystem::path cp;
try {
cp = std::filesystem::canonical(pp);
} catch (const std::filesystem::filesystem_error& e) {
setAbsoluteSharedPath();
return;
}
if (cp.parent_path() == FULL_BIN_DIR)
return setAbsoluteSharedPath();
std::cout << cp << std::endl;
std::filesystem::path parent = cp.parent_path();
if (endsWith(parent.string(), BIN_DIR)) { //this is the case when the program is installed somewhere but not system root
std::filesystem::path bin(BIN_DIR); //so it will read from something like ../share/pica/ relative to the binary
for (const auto& hop : bin) {
(void)hop; //I do this just to make as many ups as many members are in bin
parent = parent.parent_path();
}
sPath = parent / DATA_DIR / PROJECT_NAME;
} else {
sPath = parent / DATA_DIR; //this should read something like ./share relative to the binary
}
}
const std::filesystem::path& sharedPath() {
return sPath;
}
bool endsWith(const std::string& string, const std::string& query) {
std::string::size_type sl = string.length();
std::string::size_type ql = query.length();
if (sl >= ql) {
unsigned int result = string.compare(sl - ql, ql, query);
return result == 0;
} else {
return false;
}
}