aboutsummaryrefslogtreecommitdiffstats
path: root/src/utils.cpp
diff options
context:
space:
mode:
Diffstat (limited to 'src/utils.cpp')
-rw-r--r--src/utils.cpp311
1 files changed, 311 insertions, 0 deletions
diff --git a/src/utils.cpp b/src/utils.cpp
new file mode 100644
index 0000000..cb68829
--- /dev/null
+++ b/src/utils.cpp
@@ -0,0 +1,311 @@
+/* Copyright (C) 2022 The Qt Company Ltd.
+ *
+ * SPDX-License-Identifier: GPL-3.0-only WITH Qt-GPL-exception-1.0
+*/
+
+#include "utils.h"
+
+namespace utils
+{
+
+// Trim whitespaces from start of a string
+void trimLeft(std::string &s)
+{
+ s.erase(s.begin(), std::find_if (s.begin(), s.end(), [](unsigned char ch)
+ { return !std::isspace(ch); }));
+}
+
+// Trim whitespaces from end of a string
+void trimRight(std::string &s)
+{
+ s.erase(std::find_if (s.rbegin(), s.rend(), [](unsigned char ch)
+ { return !std::isspace(ch); })
+ .base(),
+ s.end());
+}
+
+// Trim whitespaces from both ends of a string
+std::string trimStr(const std::string &s)
+{
+ std::string trimmed = s;
+ trimLeft(trimmed);
+ trimRight(trimmed);
+
+ return trimmed;
+}
+
+// Split a string by a char (Defaults to a space)
+std::vector<std::string> splitStr(const std::string &str, const char delimiter)
+{
+ std::vector<std::string> strings;
+ std::istringstream ss(str);
+ std::string tmpStr;
+ while (getline(ss, tmpStr, delimiter)) {
+ tmpStr = trimStr(tmpStr);
+ strings.push_back(tmpStr);
+ }
+ return strings;
+}
+
+// Convert string to lower case
+std::string strToLower(const std::string &str)
+{
+ std::string ret = str;
+ std::transform(ret.begin(), ret.end(), ret.begin(), ::tolower);
+ return ret;
+}
+
+// Convert string to upper case
+std::string strToUpper(const std::string &str)
+{
+ std::string ret = str;
+ std::transform(ret.begin(), ret.end(), ret.begin(), ::toupper);
+ return ret;
+}
+
+// String to int: Because stoi() raises an exception upon failing
+int strToInt(const std::string &str)
+{
+ int retVal = 0;
+ try {
+ retVal = stoi(str);
+ }
+ catch (...) {
+ printf("ERROR: Unable to convert '%s' to an int\n", str.c_str());
+ }
+ return retVal;
+}
+
+std::string getUserHomeDir()
+{
+ // Try to find current user's home
+ std::string retVal = "";
+ const char* homedir;
+#if __linux__ || __APPLE__ || __MACH__
+ // Linux and Mac
+ homedir = std::getenv("HOME");
+ if (homedir == nullptr) {
+ homedir = getpwuid(getuid())->pw_dir;
+ }
+#else
+ // Windows
+ homedir = getenv("HOMEPATH");
+ if (homedir != nullptr) {
+ retVal = SYSTEM_ROOT;
+ }
+#endif
+ if (homedir == nullptr) {
+ printf("ERROR Not able to determine user's home directory\n");
+ return "Not able to get homedir";
+ }
+ retVal += std::string(homedir);
+ return retVal;
+}
+
+// Write data to the file
+int writeToFile(const std::string &filepath, const std::string &data, bool append)
+{
+ std::string path;
+ std::ofstream file;
+ // can't enable exception now because of gcc bug that raises ios_base::failure with useless message
+ if (append) {
+ file.open(filepath, std::ios::out | std::ios::app);
+ } else {
+ file.open(filepath, std::ios::out);
+ }
+ if (file.fail()) {
+ return -1;
+ }
+ try {
+ file << data << std::endl;
+ } catch (...) {
+ file.close();
+ std::cout << "Failed to write data in file " << filepath << std::endl;
+ return -1;
+ }
+ file.close();
+ return 0;
+}
+
+int createDir(const std::string &filepath, uint16_t user, uint16_t group)
+{
+ std::vector<std::string> pathVector = utils::splitStr(filepath, DIR_SEPARATOR);
+ std::string path;
+ for (std::string dir : pathVector) {
+ path += SYSTEM_ROOT;
+ path += dir;
+ if (!utils::fileExists(path)) {
+#if __linux__ || __APPLE__ || __MACH__
+ if (mkdir(path.c_str(), 0777) != 0) {
+ return -1;
+ }
+ chown(path.c_str(), user, group);
+#else
+
+ printf("WARNING: Unimplemented: createDir() for Windows\n");
+#endif
+ }
+ }
+ return 0;
+}
+
+int readFile(std::string &str, const std::string &filepath)
+{
+ std::ifstream file;
+ std::stringstream ss;
+
+ file.open(filepath, std::ios::in);
+ if (file.is_open()) {
+ std::string line;
+ while (getline(file, line)) {
+ ss << line;
+ }
+ file.close();
+ } else {
+ return -1;
+ }
+ str = ss.str();
+ return 0;
+}
+
+bool fileExists(const std::string &name)
+{
+#if __linux__ || __APPLE__ || __MACH__
+ struct stat buffer;
+ return (stat (name.c_str(), &buffer) == 0);
+#else
+ if (_access(name.c_str(), 0) == -1) {
+ std::cout << "File " << name << " doesn't exist\n";
+ return false; // not accessible
+ }
+ return true;
+#endif
+}
+
+std::string getFileOwnerName(const std::string &filename)
+{
+ std::string retVal;
+#if __linux__ || __APPLE__ || __MACH__
+ struct stat info;
+ stat(filename.c_str(), &info); // Error check omitted
+ struct passwd *pw = getpwuid(info.st_uid);
+ if (pw != 0) retVal = pw->pw_name; // contains the user name
+
+#else
+ printf("WARNING! Uniplemented: Win version of getFileOwnerName()\n");
+ retVal = "NULL";
+#endif
+ return retVal;
+}
+
+int getFileOwner(const std::string &filename, uint16_t &owner, uint16_t &group)
+{
+#if __linux__ || __APPLE__ || __MACH__
+ struct stat info;
+ stat(filename.c_str(), &info); // Error check omitted
+ std::string name = getFileOwnerName(filename);
+ owner = info.st_uid;
+ group = info.st_gid;
+#else
+ printf("WARNING! Uniplemented: Win version of getFileOwner()\n");
+#endif
+ return 0;
+}
+
+std::vector<std::string> getDirListing(const std::string &directory, const std::string &filter)
+{
+ /* Open directory stream */
+ DIR *dir = opendir(directory.c_str());
+ if (!dir) {
+ /* Could not open directory */
+ std::cout << "Cannot open directory" << directory << std::endl;;
+ }
+ /* Gather files and directories within the directory */
+ std::vector<std::string> files;
+ struct dirent *ent;
+ while ((ent = readdir(dir)) != NULL) {
+ if (ent->d_type == DT_REG) {
+ std::string name = ent->d_name;
+ if (name.substr(0, filter.length()) == filter || filter.empty()) {
+ files.push_back(name);
+ }
+ }
+ }
+ closedir(dir);
+ return files;
+}
+
+int deleteFile(const std::string &filepath)
+{
+ std::remove(filepath.c_str()); // delete file
+ bool failed = !std::ifstream("file1.txt");
+ if(failed) {
+ std::perror("Error deleting file");
+ return 1;
+ }
+ return 0;
+}
+
+std::string getOsName()
+{
+#if _WIN32
+ return "Windows";
+#elif __APPLE__ || __MACH__
+ return "macOS";
+#elif __linux__
+ return "Linux";
+#elif __FreeBSD__
+ return "FreeBSD";
+#elif __unix || __unix__
+ return "Unix";
+#else
+ return "Unknown OS";
+#endif
+}
+
+#if _WIN32
+/*
+ * Windows implementation of missing POSIX strptime()
+*/
+char* strptime(const char* s,
+ const char* f,
+ struct tm* tm) {
+ std::istringstream input(s);
+ input.imbue(std::locale(setlocale(LC_ALL, nullptr)));
+ input >> std::get_time(tm, f);
+ if (input.fail()) {
+ return nullptr;
+ }
+ return (char*)(s + input.tellg());
+}
+#endif
+
+std::string epochToString(time_t epochTime, const char* format)
+{
+ char timestamp[64] = {0};
+ strftime(timestamp, sizeof(timestamp), format, localtime(&epochTime));
+ return timestamp;
+}
+
+time_t stringToEpoch(const char* theTime, const char* format)
+{
+ std::tm tmTime;
+ memset(&tmTime, 0, sizeof(tmTime));
+ strptime(theTime, format, &tmTime);
+ return mktime(&tmTime);
+}
+
+uint64_t getTimestampNow()
+{
+ // Get current time
+ struct timeval tp;
+ gettimeofday(&tp, NULL);
+ return (uint64_t)tp.tv_sec;
+}
+
+/*
+* App-specific utils here (not generic)
+*/
+
+
+} // namespace utils