-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathutil.cpp
More file actions
545 lines (445 loc) · 16.5 KB
/
Copy pathutil.cpp
File metadata and controls
545 lines (445 loc) · 16.5 KB
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
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
/*
* Copyright 2025 Toni500git
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
* following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following
* disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
* following disclaimer in the documentation and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote
* products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS “AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include "util.hpp"
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <unistd.h>
#include <algorithm>
#include <array>
#include <cstdint>
#include <cstring>
#include <filesystem>
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <string_view>
#include <vector>
#include "fmt/color.h"
#include "fmt/ranges.h"
#include "pci.ids.hpp"
#include "platform.hpp"
#include "tiny-process-library/process.hpp"
bool hasEnding(const std::string_view fullString, const std::string_view ending)
{
if (ending.length() > fullString.length())
return false;
return (0 == fullString.compare(fullString.length() - ending.length(), ending.length(), ending));
}
bool hasStart(const std::string_view fullString, const std::string_view start)
{
if (start.length() > fullString.length())
return false;
return (fullString.substr(0, start.size()) == start);
}
std::vector<std::string> split(const std::string_view text, const char delim)
{
std::string line;
std::vector<std::string> vec;
std::stringstream ss(text.data());
while (std::getline(ss, line, delim))
{
vec.push_back(line);
}
return vec;
}
void ctrl_d_handler(const std::istream& cin)
{
if (cin.eof())
die(_("Exiting due to CTRL-D or EOF"));
}
std::string expandVar(std::string ret, bool dont)
{
if (ret.empty() || dont)
return ret;
const char* env;
if (ret.front() == '~')
{
env = std::getenv("HOME");
if (env == nullptr)
die(_("FATAL: $HOME enviroment variable is not set (how?)"));
ret.replace(0, 1, env); // replace ~ with the $HOME value
}
else if (ret.front() == '$')
{
ret.erase(0, 1);
std::string temp;
const size_t& pos = ret.find('/');
if (pos != std::string::npos)
{
temp = ret.substr(pos);
ret.erase(pos);
}
env = std::getenv(ret.c_str());
if (env == nullptr)
die(_("No such enviroment variable: {}"), ret);
ret = env;
ret += temp;
}
return ret;
}
std::string read_by_syspath(const std::string_view path, bool report_error)
{
std::ifstream f(path.data());
if (!f.is_open())
{
if (report_error)
error(_("Failed to open {}"), path);
return UNKNOWN;
}
std::string result;
std::getline(f, result);
if (!result.empty() && result.back() == '\n')
result.pop_back();
return result;
}
byte_units_t auto_divide_bytes(const double num, const std::uint16_t base, const std::string_view maxprefix)
{
double size = num;
std::array<std::string_view, 9> prefixes;
if (base == 1024)
prefixes = { "B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB" };
else if (base == 1000)
prefixes = { "B", "kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB" };
else
prefixes = { "B" };
size_t counter = 0;
const auto& max_it = !maxprefix.empty()
? std::find(prefixes.begin(), prefixes.end(), maxprefix)
: prefixes.end();
while (counter + 1 < prefixes.size() && size >= base)
{
if (max_it != prefixes.end() && prefixes[counter] == maxprefix)
break;
size /= base;
++counter;
}
return { prefixes[counter].data(), size };
}
byte_units_t divide_bytes(const double num, const std::string_view prefix)
{
if (prefix == "B")
return { "B", num };
// GiB
// 012
const std::uint16_t base = (prefix.size() == 3 && prefix[1] == 'i') ? 1024 : 1000;
std::array<std::string_view, 9> prefixes;
if (base == 1024)
prefixes = { "B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB" };
else if (base == 1000)
prefixes = { "B", "kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB" };
const auto& it = std::find(prefixes.begin(), prefixes.end(), prefix);
if (it == prefixes.end())
return { "B", num };
const size_t index = std::distance(prefixes.begin(), it);
const double value = num / std::pow(static_cast<double>(base), index);
return { prefix.data(), value };
}
bool is_file_image(const unsigned char* bytes)
{
// clang-format off
// https://stackoverflow.com/a/49683945
constexpr std::array<unsigned char, 3> jpeg = { 0xff, 0xd8, 0xff };
constexpr std::array<unsigned char, 8> png = { 0x89, 0x50, 0x4e, 0x47, 0x0D, 0x0A, 0x1A, 0x0A };
constexpr std::array<unsigned char, 6> gif89a = { 0x47, 0x49, 0x46, 0x38, 0x39, 0x61 };
constexpr std::array<unsigned char, 6> gif87a = { 0x47, 0x49, 0x46, 0x38, 0x37, 0x61 };
constexpr std::array<unsigned char, 2> bmp = { 0x42, 0x4D };
constexpr std::array<unsigned char, 4> tiffI = { 0x49, 0x49, 0x2A, 0x00 };
constexpr std::array<unsigned char, 4> tiffM = { 0x4D, 0x4D, 0x00, 0x2A };
if (std::memcmp(bytes, png.data(), png.size()) == 0 ||
std::memcmp(bytes, jpeg.data(), jpeg.size()) == 0 ||
std::memcmp(bytes, gif89a.data(), gif89a.size()) == 0 ||
std::memcmp(bytes, gif87a.data(), gif87a.size()) == 0 ||
std::memcmp(bytes, tiffM.data(), tiffM.size()) == 0 ||
std::memcmp(bytes, tiffI.data(), tiffI.size()) == 0 ||
std::memcmp(bytes, bmp.data(), bmp.size()) == 0)
return true;
return false;
// clang-format on
}
void strip(std::string& input, bool padding_only)
{
if (input.empty())
return;
if (padding_only)
{
const char* ws = " \t\n\r\f\v";
input.erase(input.find_last_not_of(ws) + 1);
input.erase(0, input.find_first_not_of(ws));
}
else
{
input.erase(std::remove_if(input.begin(), input.end(), [](unsigned char c) { return std::isspace(c); }),
input.end());
}
}
void getFileValue(u_short& iterIndex, const std::string_view line, std::string& str, const size_t& amount)
{
str = line.substr(amount);
str.erase(std::remove(str.begin(), str.end(), '\"'), str.end());
str.erase(std::remove(str.begin(), str.end(), '\''), str.end());
iterIndex++;
}
std::string shorten_vendor_name(std::string vendor)
{
if (vendor.find("AMD") != vendor.npos || vendor.find("Advanced Micro") != vendor.npos)
vendor = "AMD";
size_t pos = 0;
if ((pos = vendor.rfind("Corporation")) != vendor.npos)
vendor.erase(pos - 1);
return vendor;
}
fmt::rgb hexStringToColor(const std::string_view hexstr)
{
std::stringstream ss;
ss << std::hex << ((hexstr[0] == '#') ? hexstr.substr(1).data() : hexstr.data());
uint value;
ss >> value;
return fmt::rgb(value);
}
bool read_binary_file(std::ifstream& f, std::string& ret)
{
if (!f.is_open())
return false;
std::string buffer;
char c;
const size_t min_string_length = 4;
while (f.get(c))
{
if (isprint(static_cast<unsigned char>(c)))
{
buffer += c;
}
else
{
if (buffer.length() >= min_string_length)
ret = buffer;
return true;
}
}
return false;
}
std::string get_relative_path(const std::string_view relative_path, const std::string_view env, const long long mode)
{
const char* c_env = std::getenv(env.data());
if (!c_env)
return UNKNOWN;
struct stat sb;
std::string fullPath;
fullPath.reserve(1024);
for (const std::string& dir : split(c_env, ':'))
{
// -300ns for not creating a string. stonks
fullPath += dir;
fullPath += '/';
fullPath += relative_path.data();
if ((stat(fullPath.c_str(), &sb) == 0) && sb.st_mode & mode)
return fullPath.c_str();
fullPath.clear();
}
return UNKNOWN; // not found
}
std::string which(const std::string_view command)
{
return get_relative_path(command, "PATH", S_IXUSR);
}
std::string get_data_path(const std::string_view file)
{
return get_relative_path(file, "XDG_DATA_DIRS", S_IFREG);
}
std::string get_data_dir(const std::string_view dir)
{
return get_relative_path(dir, "XDG_DATA_DIRS", S_IFDIR);
}
#if CF_ANDROID
#include <sys/system_properties.h>
std::string get_android_property(const std::string_view name)
{
char ret[PROP_VALUE_MAX];
const int len = __system_property_get(name.data(), ret);
if (len <= 0)
return "";
return ret;
}
#endif
void replace_str(std::string& str, const std::string_view from, const std::string_view to)
{
size_t start_pos = 0;
while ((start_pos = str.find(from, start_pos)) != std::string::npos)
{
str.replace(start_pos, from.length(), to);
start_pos += to.length(); // Handles case where 'to' is a substring of 'from'
}
}
bool read_exec(std::vector<std::string> cmd, std::string& output, bool useStdErr, bool noerror_print)
{
debug("{} cmd = {}", __func__, cmd);
TinyProcessLib::Process proc(
cmd, "",
[&](const char* bytes, size_t n) {
if (!useStdErr)
output += std::string(bytes, n);
},
[&](const char* bytes, size_t n) {
if (useStdErr)
output += std::string(bytes, n);
else if (!noerror_print)
error(_("Failed to execute the command: {}"), fmt::join(cmd, " "));
});
if (!output.empty() && output.back() == '\n')
output.pop_back();
return proc.get_exit_status() == 0;
}
std::string str_tolower(std::string str)
{
for (char& x : str)
x = std::tolower(x);
return str;
}
std::string str_toupper(std::string str)
{
for (char& x : str)
x = std::toupper(x);
return str;
}
std::string binarySearchPCIArray(const std::string_view vendor_id_s, const std::string_view pci_id_s)
{
const std::string_view vendor_id = hasStart(vendor_id_s, "0x") ? vendor_id_s.substr(2) : vendor_id_s;
const std::string_view pci_id = hasStart(pci_id_s, "0x") ? pci_id_s.substr(2) : pci_id_s;
size_t left = 0, right = pci_vendors_array.size(), mid;
while (right >= left)
{
mid = left + (right - left) / 2;
// If the element is present at the middle
// itself
if (pci_vendors_array.at(mid) == vendor_id)
break;
// If element is smaller than mid, then
// it can only be present in left subarray
if (pci_vendors_array.at(mid) > vendor_id)
right = mid - 1;
// Else the element can only be present
// in right subarray
if (pci_vendors_array.at(mid) < vendor_id)
left = mid + 1;
}
size_t approx_vendors_location = pci_vendors_location_array.at(mid);
size_t vendor_location = all_ids.find(vendor_id, approx_vendors_location);
size_t device_location = all_ids.find(pci_id, vendor_location);
if (vendor_location == std::string::npos || device_location == std::string::npos)
return UNKNOWN;
// Here we use find from vendors_location because as it turns out, lower_bound doesn't return WHERE it is, but where
// "val" can be placed without affecting the order of the string (binary search stuff) so we have to find from the
// point onwards to find the actual line, it is still a shortcut, better than searching from 0.
return name_from_entry(device_location);
}
std::string binarySearchPCIArray(const std::string_view vendor_id_s)
{
const std::string_view vendor_id = hasStart(vendor_id_s, "0x") ? vendor_id_s.substr(2) : vendor_id_s;
size_t left = 0, right = pci_vendors_array.size(), mid;
while (right >= left)
{
mid = left + (right - left) / 2;
// If the element is present at the middle
// itself
if (pci_vendors_array.at(mid) == vendor_id)
break;
// If element is smaller than mid, then
// it can only be present in left subarray
if (pci_vendors_array.at(mid) > vendor_id)
right = mid - 1;
// Else the element can only be present
// in right subarray
if (pci_vendors_array.at(mid) < vendor_id)
left = mid + 1;
}
const size_t approximate_vendors_location = pci_vendors_location_array.at(mid);
const size_t vendors_location = all_ids.find(vendor_id, approximate_vendors_location);
if (vendors_location == std::string::npos)
return UNKNOWN;
// Here we use find from vendors_location because as it turns out, lower_bound doesn't return WHERE it is, but where
// "val" can be placed without affecting the order of the string (binary search stuff) so we have to find from the
// point onwards to find the actual line, it is still a shortcut, better than searching from 0.
return vendor_from_entry(vendors_location, vendor_id);
}
std::string name_from_entry(size_t dev_entry_pos)
{
dev_entry_pos += 6; // Offset from the first character to the actual name that we want (xxxx <device name>)
std::string name = std::string(all_ids.substr(dev_entry_pos, all_ids.find('\n', dev_entry_pos) - dev_entry_pos));
const size_t bracket_open_pos = name.find('[');
const size_t bracket_close_pos = name.find(']');
if (bracket_open_pos != std::string::npos && bracket_close_pos != std::string::npos)
name = name.substr(bracket_open_pos + 1, bracket_close_pos - bracket_open_pos - 1);
return name;
}
std::string vendor_from_entry(const size_t vendor_entry_pos, const std::string_view vendor_id_s)
{
size_t end_line_pos = all_ids.find('\n', vendor_entry_pos);
if (end_line_pos == std::string::npos)
end_line_pos = all_ids.length(); // If no newline is found, set to end of string
const std::string& line = std::string(all_ids.substr(vendor_entry_pos, end_line_pos - vendor_entry_pos));
const size_t after_id_pos = line.find(vendor_id_s) + 4;
const std::string& description = line.substr(after_id_pos);
const size_t first = description.find_first_not_of(' ');
if (first == std::string::npos)
return UNKNOWN;
const size_t last = description.find_last_not_of(' ');
return description.substr(first, (last - first + 1));
}
std::filesystem::path getHomeConfigDir()
{
const char* dir = std::getenv("XDG_CONFIG_HOME");
if (dir != NULL && dir[0] != '\0' && std::filesystem::exists(dir))
{
return std::filesystem::path(dir);
}
else
{
const char* home = std::getenv("HOME");
if (home == nullptr)
die(_("Failed to find $HOME, set it to your home directory!"));
return std::filesystem::path(home) / ".config";
}
}
std::filesystem::path getConfigDir()
{ return getHomeConfigDir() / "customfetch"; }
std::filesystem::path getHomeCacheDir()
{
const char* dir = std::getenv("XDG_CACHE_HOME");
if (dir != NULL && dir[0] != '\0' && std::filesystem::exists(dir))
{
return std::filesystem::path(dir);
}
else
{
const char* home = std::getenv("HOME");
if (home == nullptr)
die(_("Failed to find $HOME, set it to your home directory!"));
return std::filesystem::path(home) / ".cache";
}
}
std::filesystem::path getCacheDir()
{ return getHomeCacheDir() / "customfetch"; }