-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathutil.cpp
77 lines (73 loc) · 2.09 KB
/
util.cpp
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
#include "util.h"
#include <QStringList>
#include <QRegularExpression>
#include <QLocale>
#include <math.h>
QString friendlySize(quint64 s) {
//const QVector<QChar> units{'B', 'K', 'M', 'G', 'T', 'P', 'E'};
const QString units("BKMGTPE");
double v = s;
int ui = 0;
for(; ui < units.size(); ui++) {
if(v < 10000) break;
v /= 1024;
}
if(ui)
return QLocale().toString(round(v*100) / 100, 'f', 2) + units.at(ui);
else
// bytes - no decimal needed
return QLocale().toString((int)v) + units.at(ui);
}
quint64 sizeToBytes(QString size) {
QLocale l;
if(size.isEmpty() || size == l.decimalPoint()) return 0;
// extract unit from text
auto cUnit = size.at(size.size()-1);
if(cUnit < '0' || cUnit > '9')
size = size.left(size.length()-1);
else
cUnit = 'B';
double val = l.toDouble(size);
switch(cUnit.toUpper().toLatin1()) {
case 'E':
val *= 1024;
// fallthrough
case 'P':
val *= 1024;
// fallthrough
case 'T':
val *= 1024;
// fallthrough
case 'G':
val *= 1024;
// fallthrough
case 'M':
val *= 1024;
// fallthrough
case 'K':
val *= 1024;
// fallthrough
case 'B':
break;
}
return val;
}
QString escapeShellArg(QString arg) {
#ifdef Q_OS_WINDOWS
QRegularExpression basic;
// we'll special case our recovery % option
if(arg.count('%') == 1) // % is only problematic if there's more than one of it
basic.setPattern("^[a-zA-Z0-9\\-_=.,:/\\\\%]+$");
else
basic.setPattern("^[a-zA-Z0-9\\-_=.,:/\\\\]+$");
if(basic.match(arg).hasMatch())
return arg;
// I think this is correct...
return QString("\"%1\"").arg(arg.replace("\"", "\"\"").replace("%", "\"^%\"").replace("!", "\"^!\"").replace("\\", "\\\\").replace("\n", "\"^\n\"").replace("\r", "\"^\r\""));
#else
QRegularExpression basic("^[a-zA-Z0-9\\-_=.,:/]+$");
if(basic.match(arg).hasMatch())
return arg;
return QString("'%1'").arg(arg.replace("'", "'\\''"));
#endif
}