| 212 | } |
| 213 | |
| 214 | static QString expandVariable(const QString &key, const QString &value, |
| 215 | QMap<QString, QString> &output, |
| 216 | const QMap<QString, QString> &input, |
| 217 | const QProcessEnvironment &environment) |
| 218 | { |
| 219 | if (value.isEmpty()) |
| 220 | return QString(); |
| 221 | |
| 222 | auto it = output.constFind(key); |
| 223 | if (it != output.constEnd()) { |
| 224 | // nothing to do, value was expanded already |
| 225 | return *it; |
| 226 | } |
| 227 | |
| 228 | // not yet expanded, do that now |
| 229 | |
| 230 | auto variableValue = [&](const QString &variable) { |
| 231 | if (environment.contains(variable)) { |
| 232 | return environment.value(variable); |
| 233 | } else if (variable == key) { |
| 234 | // This must be a reference to a system environment variable of the |
| 235 | // same name, which happens to be unset. Treat it as empty. |
| 236 | return QString(); |
| 237 | } else if (input.contains(variable)) { |
| 238 | return expandVariable(variable, input.value(variable), output, input, environment); |
| 239 | } else { |
| 240 | qCWarning(UTIL) << "Couldn't find replacement for" << variable; |
| 241 | return QString(); |
| 242 | } |
| 243 | }; |
| 244 | |
| 245 | constexpr ushort escapeChar{'\\'}; |
| 246 | constexpr ushort variableStartChar{'$'}; |
| 247 | const auto isSpecialSymbol = [=](QChar c) { |
| 248 | return c.unicode() == escapeChar || c.unicode() == variableStartChar; |
| 249 | }; |
| 250 | |
| 251 | auto& expanded = output[key]; |
| 252 | expanded.reserve(value.size()); |
| 253 | const int lastIndex = value.size() - 1; |
| 254 | int i = 0; |
| 255 | // Never treat value.back() as a special symbol (nothing to escape or start). |
| 256 | while (i < lastIndex) { |
| 257 | const auto currentChar = value[i]; |
| 258 | switch (currentChar.unicode()) { |
| 259 | case escapeChar: { |
| 260 | const auto nextChar = value[i+1]; |
| 261 | if (!isSpecialSymbol(nextChar)) { |
| 262 | expanded += currentChar; // Nothing to escape => keep the escapeChar. |
| 263 | } |
| 264 | expanded += nextChar; |
| 265 | i += 2; |
| 266 | break; |
| 267 | } |
| 268 | case variableStartChar: { |
| 269 | ++i; |
| 270 | const auto match = matchPossiblyBracedAsciiVariable(QStringView{value}.sliced(i)); |
| 271 | if (match.length == 0) { |