aboutsummaryrefslogtreecommitdiffstats
path: root/utils.cpp
blob: 95c5b66a8194c099d7019ba2483acb954fa7181d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
/* Copyright (C) 2022 The Qt Company Ltd.
 *
 * SPDX-License-Identifier: GPL-3.0-only WITH Qt-GPL-exception-1.0
*/

#include "utils.h"
#include "commonsetup.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;
}

#include <time.h>


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);
}

/*
*   App-specific utils here (not generic)
*/


} // namespace utils