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
|
// *****************************************************************************
// * This file is part of the FreeFileSync project. It is distributed under *
// * GNU General Public License: https://www.gnu.org/licenses/gpl-3.0 *
// * Copyright (C) Zenju (zenju AT freefilesync DOT org) - All Rights Reserved *
// *****************************************************************************
#include "resolve_path.h"
#include "time.h"
#include "thread.h"
#include "file_access.h"
#include "file_path.h"
#include <stdlib.h> //getenv()
#include <unistd.h> //getcwd()
using namespace zen;
namespace
{
std::optional<Zstring> getEnvironmentVar(const Zstring& name)
{
assert(runningOnMainThread()); //getenv() is not thread-safe!
const char* buffer = ::getenv(name.c_str()); //no extended error reporting
if (!buffer)
return {};
Zstring value(buffer);
//some postprocessing:
trim(value); //remove leading, trailing blanks
//remove leading, trailing double-quotes
if (startsWith(value, Zstr('"')) &&
endsWith (value, Zstr('"')) &&
value.length() >= 2)
value = Zstring(value.c_str() + 1, value.length() - 2);
return value;
}
Zstring resolveRelativePath(const Zstring& relativePath)
{
assert(runningOnMainThread());
/* MSDN: "Multithreaded applications and shared library code should not use the GetFullPathName function
and should avoid using relative path names. The current directory state written by the
SetCurrentDirectory function is stored as a global variable in each process,
therefore multithreaded applications cannot reliably use this value without possible data corruption from other threads, [...]"
=> Just plain wrong, there is no data corruption. What MSDN really means: GetFullPathName() is *perfectly* thread-safe, but depends
on the current directory, which is a process-scope global: https://devblogs.microsoft.com/oldnewthing/20210816-00/?p=105562 */
if (relativePath.empty())
return relativePath;
Zstring pathTmp = relativePath;
//https://linux.die.net/man/2/path_resolution
if (!startsWith(pathTmp, FILE_NAME_SEPARATOR)) //absolute names are exactly those starting with a '/'
{
/* basic support for '~': strictly speaking this is a shell-layer feature, so "realpath()" won't handle it
https://www.gnu.org/software/bash/manual/html_node/Tilde-Expansion.html
https://linux.die.net/man/3/getpwuid: An application that wants to determine its user's home directory
should inspect the value of HOME (rather than the value getpwuid(getuid())->pw_dir) since this allows
the user to modify their notion of "the home directory" during a login session. */
if (startsWith(pathTmp, "~/") || pathTmp == "~")
{
if (const std::optional<Zstring> homeDir = getEnvironmentVar("HOME"))
{
if (startsWith(pathTmp, "~/"))
pathTmp = appendSeparator(*homeDir) + afterFirst(pathTmp, '/', IfNotFoundReturn::none);
else //pathTmp == "~"
pathTmp = *homeDir;
}
//else: error! no further processing!
}
else
{
//we cannot use ::realpath() which only resolves *existing* relative paths!
if (char* dirPath = ::getcwd(nullptr, 0))
{
ZEN_ON_SCOPE_EXIT(::free(dirPath));
pathTmp = appendSeparator(dirPath) + pathTmp;
}
}
}
//get rid of some cruft (just like GetFullPathName())
replace(pathTmp, "/./", '/');
if (endsWith(pathTmp, "/."))
pathTmp.pop_back(); //keep the "/" => consider pathTmp == "/."
//what about "/../"? might be relative to symlinks => preserve!
return pathTmp;
}
//returns value if resolved
std::optional<Zstring> tryResolveMacro(const Zstring& macro) //macro without %-characters
{
Zstring timeStr;
auto resolveTimePhrase = [&](const Zchar* phrase, const Zchar* format) -> bool
{
if (!equalAsciiNoCase(macro, phrase))
return false;
timeStr = formatTime(format);
return true;
};
//https://en.cppreference.com/w/cpp/chrono/c/strftime
//there exist environment variables named %TIME%, %DATE% so check for our internal macros first!
if (resolveTimePhrase(Zstr("Date"), Zstr("%Y-%m-%d"))) return timeStr;
if (resolveTimePhrase(Zstr("Time"), Zstr("%H%M%S"))) return timeStr;
if (resolveTimePhrase(Zstr("TimeStamp"), Zstr("%Y-%m-%d %H%M%S"))) return timeStr; //e.g. "2012-05-15 131513"
if (resolveTimePhrase(Zstr("Year"), Zstr("%Y"))) return timeStr;
if (resolveTimePhrase(Zstr("Month"), Zstr("%m"))) return timeStr;
if (resolveTimePhrase(Zstr("MonthName"), Zstr("%b"))) return timeStr; //e.g. "Jan"
if (resolveTimePhrase(Zstr("Day"), Zstr("%d"))) return timeStr;
if (resolveTimePhrase(Zstr("Hour"), Zstr("%H"))) return timeStr;
if (resolveTimePhrase(Zstr("Min"), Zstr("%M"))) return timeStr;
if (resolveTimePhrase(Zstr("Sec"), Zstr("%S"))) return timeStr;
if (resolveTimePhrase(Zstr("WeekDayName"), Zstr("%a"))) return timeStr; //e.g. "Mon"
if (resolveTimePhrase(Zstr("Week"), Zstr("%V"))) return timeStr; //ISO 8601 week of the year
if (equalAsciiNoCase(macro, Zstr("WeekDay")))
{
const int weekDayStartSunday = stringTo<int>(formatTime(Zstr("%w"))); //[0 (Sunday), 6 (Saturday)] => not localized!
//alternative 1: use "%u": ISO 8601 weekday as number with Monday as 1 (1-7) => newer standard than %w
//alternative 2: ::mktime() + std::tm::tm_wday
const int weekDayStartMonday = (weekDayStartSunday + 6) % 7; //+6 == -1 in Z_7
// [0-Monday, 6-Sunday]
const int weekDayStartLocal = ((weekDayStartMonday + 7 - static_cast<int>(getFirstDayOfWeek())) % 7) + 1;
//[1 (local first day of week), 7 (local last day of week)]
return numberTo<Zstring>(weekDayStartLocal);
}
//try to resolve as environment variables
if (std::optional<Zstring> value = getEnvironmentVar(macro))
return *value;
return {};
}
const Zchar MACRO_SEP = Zstr('%');
}
//returns expanded or original string
Zstring zen::expandMacros(const Zstring& text)
{
if (contains(text, MACRO_SEP))
{
Zstring prefix = beforeFirst(text, MACRO_SEP, IfNotFoundReturn::none);
Zstring rest = afterFirst (text, MACRO_SEP, IfNotFoundReturn::none);
if (contains(rest, MACRO_SEP))
{
Zstring potentialMacro = beforeFirst(rest, MACRO_SEP, IfNotFoundReturn::none);
Zstring postfix = afterFirst (rest, MACRO_SEP, IfNotFoundReturn::none); //text == prefix + MACRO_SEP + potentialMacro + MACRO_SEP + postfix
if (std::optional<Zstring> value = tryResolveMacro(potentialMacro))
return prefix + *value + expandMacros(postfix);
else
return prefix + MACRO_SEP + potentialMacro + expandMacros(MACRO_SEP + postfix);
}
}
return text;
}
namespace
{
//expand volume name if possible, return original input otherwise
Zstring expandVolumeName(Zstring pathPhrase) // [volname]:\folder [volname]\folder [volname]folder -> C:\folder
{
//we only expect the [.*] pattern at the beginning => do not touch dir names like "C:\somedir\[stuff]"
trim(pathPhrase, true, false);
if (startsWith(pathPhrase, Zstr('[')))
{
return "/.../" + pathPhrase;
}
return pathPhrase;
}
void getFolderAliasesRecursive(const Zstring& pathPhrase, std::set<Zstring, LessNativePath>& output)
{
//3. environment variables: C:\Users\<user> -> %UserProfile%
{
std::vector<std::pair<Zstring, Zstring>> macroList;
//get list of useful variables
auto addEnvVar = [&](const Zstring& envName)
{
if (std::optional<Zstring> value = getEnvironmentVar(envName))
macroList.emplace_back(envName, *value);
};
addEnvVar("HOME"); //Linux: /home/<user> Mac: /Users/<user>
//addEnvVar("USER"); -> any benefit?
//substitute paths by symbolic names
for (const auto& [macroName, macroPath] : macroList)
{
//should use a replaceCpy() that considers "local path" case-sensitivity (if only we had one...)
const Zstring pathSubst = replaceCpyAsciiNoCase(pathPhrase, macroPath, MACRO_SEP + macroName + MACRO_SEP);
if (pathSubst != pathPhrase)
output.insert(pathSubst);
}
}
//4. replace (all) macros: %UserProfile% -> C:\Users\<user>
{
const Zstring pathExp = expandMacros(pathPhrase);
if (pathExp != pathPhrase)
if (output.insert(pathExp).second)
getFolderAliasesRecursive(pathExp, output); //recurse!
}
}
}
std::vector<Zstring> zen::getFolderPathAliases(const Zstring& folderPathPhrase)
{
const Zstring dirPath = trimCpy(folderPathPhrase);
if (dirPath.empty())
return {};
std::set<Zstring, LessNativePath> tmp;
getFolderAliasesRecursive(dirPath, tmp);
tmp.erase(dirPath);
tmp.erase(Zstring());
return {tmp.begin(), tmp.end()};
}
//coordinate changes with acceptsFolderPathPhraseNative()!
Zstring zen::getResolvedFilePath(const Zstring& pathPhrase) //noexcept
{
Zstring path = pathPhrase;
path = expandMacros(path); //expand before trimming!
//remove leading/trailing whitespace before allowing misinterpretation in applyLongPathPrefix()
trim(path); //attention: don't remove all whitespace from right, e.g. 0xa0 may be used as part of a folder name
path = expandVolumeName(path); //may block for slow USB sticks and idle HDDs!
/* need to resolve relative paths:
WINDOWS:
- \\?\-prefix requires absolute names
- Volume Shadow Copy: volume name needs to be part of each file path
- file icon buffer (at least for extensions that are actually read from disk, like "exe")
WINDOWS/LINUX:
- detection of dependent directories, e.g. "\" and "C:\test" */
path = resolveRelativePath(path);
//remove trailing slash, unless volume root:
if (std::optional<PathComponents> pc = parsePathComponents(path))
{
if (pc->relPath.empty())
path = pc->rootPath;
else
path = appendSeparator(pc->rootPath) + pc->relPath;
} //keep this brace for GCC: -Wparentheses
return path;
}
|