• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

IJHack / QtPass / 25577476341

08 May 2026 08:18PM UTC coverage: 28.031% (-0.02%) from 28.048%
25577476341

Pull #1433

github

web-flow
Merge 831c4b171 into 804118787
Pull Request #1433: refactor(util): cleaner path construction + brace consistency

3 of 7 new or added lines in 1 file covered. (42.86%)

1854 of 6614 relevant lines covered (28.03%)

27.12 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

48.23
/src/util.cpp
1
// SPDX-FileCopyrightText: 2014 Anne Jan Brouwer
2
// SPDX-License-Identifier: GPL-3.0-or-later
3

4
/**
5
 * @class Util
6
 * @brief Static utility functions implementation.
7
 *
8
 * Implementation of utility functions for path handling, binary discovery,
9
 * and configuration validation.
10
 *
11
 * @see util.h
12
 */
13

14
#include "util.h"
15
#include "executor.h"
16
#include <QDebug>
17
#include <QDir>
18
#include <QFile>
19
#include <QFileInfo>
20
#include <QSaveFile>
21
#include <QTextStream>
22
#include <algorithm>
23
#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
24
#include <QStringConverter>
25
#endif
26
#ifdef Q_OS_WIN
27
#include <windows.h>
28
#else
29
#include <sys/time.h>
30
#endif
31
#include "qtpasssettings.h"
32

33
#ifdef QT_DEBUG
34
#include "debughelper.h"
35
#endif
36

37
QProcessEnvironment Util::_env;
38
bool Util::_envInitialised = false;
39

40
/**
41
 * @brief Initializes the process environment and augments PATH with
42
 * platform-specific GPG locations.
43
 * @example
44
 * Util::initialiseEnvironment();
45
 *
46
 * @note On macOS, appends common MacGPG2 and /usr/local/bin paths if available.
47
 * @note On Windows, appends common WinGPG and GnuPG installation paths if
48
 * available.
49
 */
50
void Util::initialiseEnvironment() {
17 ✔
51
  if (!_envInitialised) {
17 ✔
52
    _env = QProcessEnvironment::systemEnvironment();
1 ✔
53
#ifdef __APPLE__
54
    QString path = _env.value("PATH");
55
    if (!path.contains("/usr/local/MacGPG2/bin") &&
56
        QDir("/usr/local/MacGPG2/bin").exists())
57
      path += ":/usr/local/MacGPG2/bin";
58
    if (!path.contains("/usr/local/bin"))
59
      path += ":/usr/local/bin";
60
    _env.insert("PATH", path);
61
#endif
62
#ifdef Q_OS_WIN
63
    QString path = _env.value("PATH");
64
    if (!path.contains("C:\\Program Files\\WinGPG\\x86") &&
65
        QDir("C:\\Program Files\\WinGPG\\x86").exists())
66
      path += ";C:\\Program Files\\WinGPG\\x86";
67
    if (!path.contains("C:\\Program Files\\GnuPG\\bin") &&
68
        QDir("C:\\Program Files\\GnuPG\\bin").exists())
69
      path += ";C:\\Program Files\\GnuPG\\bin";
70
    _env.insert("PATH", path);
71
#endif
72
#ifdef QT_DEBUG
73
    dbg() << _env.value("PATH");
74
#endif
75
    _envInitialised = true;
1 ✔
76
  }
77
}
17 ✔
78

79
/**
80
 * @brief Resolves the path to the password store directory.
81
 * @details Initializes the environment, checks for the {@code
82
 * PASSWORD_STORE_DIR} variable, and falls back to a platform-specific default
83
 * location under the user's home directory.
84
 * @return QString - Normalized path to the password store folder.
85
 */
86
auto Util::findPasswordStore() -> QString {
2 ✔
87
  QString path;
2 ✔
88
  initialiseEnvironment();
2 ✔
89
  if (_env.contains("PASSWORD_STORE_DIR")) {
4 ✔
90
    path = _env.value("PASSWORD_STORE_DIR");
×
91
    // Expand a leading "~" — env vars set in non-shell contexts (systemd
92
    // units, .desktop entries, quoted shell assignments) skip the shell's
93
    // tilde expansion, leaving "~" as a literal directory component.
NEW
94
    if (path == "~") {
×
NEW
95
      path = QDir::homePath();
×
NEW
96
    } else if (path.startsWith("~/")) {
×
NEW
97
      path = QDir::homePath() + path.mid(1);
×
98
    }
99
  } else {
100
#ifdef Q_OS_WIN
101
    path = QDir(QDir::homePath()).filePath("password-store");
102
#else
103
    path = QDir(QDir::homePath()).filePath(".password-store");
6 ✔
104
#endif
105
  }
106
  return Util::normalizeFolderPath(QDir::cleanPath(path));
4 ✔
107
}
108

109
auto Util::normalizeFolderPath(const QString &path) -> QString {
13 ✔
110
  QString normalizedPath = path;
111
  if (!normalizedPath.endsWith("/") &&
35 ✔
112
      !normalizedPath.endsWith(QDir::separator())) {
9 ✔
113
    normalizedPath += QDir::separator();
9 ✔
114
  }
115
  return QDir::toNativeSeparators(normalizedPath);
26 ✔
116
}
117

118
/**
119
 * @brief Finds the absolute path of a binary by searching the PATH environment
120
 * variable.
121
 *
122
 * Iterates through each PATH entry, checks whether the binary exists and is
123
 * executable, and returns the first matching absolute file path. On Windows, if
124
 * no local match is found, it may fall back to a WSL invocation when the binary
125
 * name is valid and WSL appears to support it.
126
 *
127
 * @example
128
 * QString result = Util::findBinaryInPath("git");
129
 * // Expected output sample: "/usr/bin/git" or "wsl git"
130
 *
131
 * @param QString binary - The name of the binary to locate.
132
 * @return QString - The absolute path to the binary, or an empty string if not
133
 * found.
134
 */
135
auto Util::findBinaryInPath(const QString &binary) -> QString {
16 ✔
136
  if (binary.isEmpty()) {
16 ✔
137
    return {};
138
  }
139

140
  initialiseEnvironment();
15 ✔
141

142
  QString ret;
15 ✔
143

144
  const QString binaryWithSep = QDir::separator() + binary;
15 ✔
145

146
  if (_env.contains("PATH")) {
30 ✔
147
    QString path = _env.value("PATH");
30 ✔
148
    const QChar delimiter = QDir::separator() == '\\' ? ';' : ':';
149
    QStringList entries = path.split(delimiter);
15 ✔
150

151
    for (const QString &entryConst : entries) {
237 ✔
152
      QString fullPath = entryConst + binaryWithSep;
220 ✔
153
      QFileInfo qfi(fullPath);
220 ✔
154
#ifdef Q_OS_WIN
155
      if (!qfi.exists()) {
156
        QString fullPathExe = fullPath + ".exe";
157
        qfi = QFileInfo(fullPathExe);
158
      }
159
#endif
160
      if (!qfi.exists()) {
220 ✔
161
        continue;
207 ✔
162
      }
163
      if (!qfi.isExecutable()) {
13 ✔
164
        continue;
×
165
      }
166

167
      ret = qfi.absoluteFilePath();
13 ✔
168
      break;
169
    }
220 ✔
170
  }
171
#ifdef Q_OS_WIN
172
  if (ret.isEmpty()) {
173
    static const QRegularExpression whitespaceRegex(QStringLiteral("\\s"));
174
    const bool hasWhitespace = binary.contains(whitespaceRegex);
175
    if (!binary.isEmpty() && !hasWhitespace) {
176
      QString wslCommand = QStringLiteral("wsl ") + binary;
177
#ifdef QT_DEBUG
178
      dbg() << "Util::findBinaryInPath(): falling back to WSL for binary"
179
            << binary;
180
#endif
181
      QString out, err;
182
      if (Executor::executeBlocking(wslCommand, {"--version"}, &out, &err) ==
183
              0 &&
184
          !out.isEmpty() && err.isEmpty()) {
185
#ifdef QT_DEBUG
186
        dbg() << "Util::findBinaryInPath(): using WSL binary" << wslCommand;
187
#endif
188
        ret = wslCommand;
189
      }
190
    }
191
  }
192
#endif
193

194
  return ret;
195
}
196

197
/**
198
 * @brief Checks whether the current QtPass configuration is valid.
199
 * @example
200
 * bool result = Util::configIsValid();
201
 * std::cout << std::boolalpha << result << std::endl; // Expected output: true
202
 * or false
203
 *
204
 * @return bool - True if the configuration file exists and the required
205
 * executable is available; otherwise false.
206
 */
207
auto Util::configIsValid() -> bool {
3 ✔
208
  const QString configFilePath =
209
      QDir(QtPassSettings::getPassStore()).filePath(".gpg-id");
9 ✔
210
  if (!QFile(configFilePath).exists()) {
3 ✔
211
    return false;
212
  }
213

214
  const QString executable = QtPassSettings::isUsePass()
4 ✔
215
                                 ? QtPassSettings::getPassExecutable()
2 ✔
216
                                 : QtPassSettings::getGpgExecutable();
4 ✔
217

218
  if (executable.startsWith(QStringLiteral("wsl "))) {
4 ✔
219
    QString out;
×
220
    QString err;
×
221
    if (Executor::executeBlocking(QStringLiteral("wsl"),
×
222
                                  {QStringLiteral("--version")}, &out,
×
223
                                  &err) == 0 &&
×
224
        !out.isEmpty() && err.isEmpty()) {
×
225
      return true;
226
    }
227
  }
228
  return QFile(executable).exists();
2 ✔
229
}
230

231
/**
232
 * @brief Returns a directory path derived from a model index, optionally
233
 * relative to the pass store.
234
 * @example
235
 * QString result = Util::getDir(index, true, model, storeModel);
236
 * std::cout << result.toStdString() << std::endl; // Expected output: relative
237
 * directory path with trailing separator
238
 *
239
 * @param QModelIndex &index - Source index used to resolve the file or
240
 * directory path.
241
 * @param bool forPass - If true, returns a path relative to the pass store;
242
 * otherwise returns an absolute path.
243
 * @param QFileSystemModel &model - File system model used to obtain file
244
 * information.
245
 * @param StoreModel &storeModel - Proxy model used to map the provided index to
246
 * the source model.
247
 * @return QString - The resolved directory path, always ending with the
248
 * platform's directory separator.
249
 */
250
auto Util::getDir(const QModelIndex &index, bool forPass,
3 ✔
251
                  const QFileSystemModel &model, const StoreModel &storeModel)
252
    -> QString {
253
  QString abspath =
254
      QDir(QtPassSettings::getPassStore()).absolutePath() + QDir::separator();
9 ✔
255
  if (!index.isValid()) {
256
    return forPass ? "" : abspath;
2 ✔
257
  }
258
  QFileInfo info = model.fileInfo(storeModel.mapToSource(index));
1 ✔
259
  QString filePath =
260
      (info.isFile() ? info.absolutePath() : info.absoluteFilePath());
1 ✔
261
  if (forPass) {
1 ✔
262
    filePath = QDir(abspath).relativeFilePath(filePath);
×
263
  }
264
  filePath += QDir::separator();
1 ✔
265
  return filePath;
266
}
1 ✔
267

268
auto Util::endsWithGpg() -> const QRegularExpression & {
64 ✔
269
  static const QRegularExpression expr{"\\.gpg$"};
64 ✔
270
  return expr;
64 ✔
271
}
272

273
/**
274
 * @brief Returns a regex matching common remote/network protocol schemes.
275
 *
276
 * Matches http://, https://, ftp://, ftps://, ssh://, sftp://, webdav://,
277
 * webdavs://
278
 *
279
 * Note: Local file URLs (file:///) are intentionally excluded by design, as
280
 * they represent local paths rather than network protocols. If this behavior
281
 * needs to change, update both this function and the corresponding test.
282
 *
283
 * @return QRegularExpression reference
284
 */
285
auto Util::protocolRegex() -> const QRegularExpression & {
4 ✔
286
  static const QRegularExpression regex{
287
      R"(((?:https?|ftp|ssh|sftp|ftps|webdav|webdavs)://[^" <>\)\]\[]+))"};
4 ✔
288
  return regex;
4 ✔
289
}
290

291
auto Util::newLinesRegex() -> const QRegularExpression & {
13 ✔
292
  static const QRegularExpression regex{"[\r\n]"};
13 ✔
293
  return regex;
13 ✔
294
}
295

296
auto Util::isValidKeyId(const QString &keyId) -> bool {
50 ✔
297
  static const QRegularExpression hexPrefixRegex{"^0[xX]"};
50 ✔
298
  static const QRegularExpression specialPrefixRegex{"^[@/#&]"};
50 ✔
299
  static const QRegularExpression hexKeyIdRegex{"^[0-9A-Fa-f]{8,40}$"};
50 ✔
300

301
  if (keyId.isEmpty()) {
50 ✔
302
    return false;
303
  }
304

305
  QString normalized = keyId;
306
  if (normalized.startsWith('<') && normalized.endsWith('>')) {
49 ✔
307
    normalized = normalized.mid(1, normalized.length() - 2);
4 ✔
308
  }
309
  normalized.remove(hexPrefixRegex);
49 ✔
310

311
  if (specialPrefixRegex.match(normalized).hasMatch() ||
98 ✔
312
      normalized.contains('@')) {
46 ✔
313
    return true;
314
  }
315

316
  return hexKeyIdRegex.match(normalized).hasMatch();
42 ✔
317
}
318

319
/**
320
 * @brief Read templates from .templates file in password store.
321
 * @param storePath Path to password store root.
322
 * @return Hash of template name to field list.
323
 */
324
auto Util::readTemplates(const QString &storePath)
×
325
    -> QHash<QString, QStringList> {
326
  QHash<QString, QStringList> result;
×
327
  QFile file(QDir(storePath).filePath(".templates"));
×
328
  if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
×
329
    return result;
330
  }
331
  QTextStream in(&file);
×
332
#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
333
  in.setEncoding(QStringConverter::Utf8);
×
334
#else
335
  in.setCodec("UTF-8");
336
#endif
337
  QString currentSection;
×
338
  QStringList currentFields;
×
339
  bool skipInvalidSection = false;
340
  while (!in.atEnd()) {
×
341
    QString line = in.readLine().trimmed();
×
342
    if (line.startsWith('[') && line.endsWith(']')) {
×
343
      if (!currentSection.isEmpty() && !skipInvalidSection) {
×
344
        result.insert(currentSection, currentFields);
345
      }
346
      currentSection = line.mid(1, line.length() - 2).trimmed();
×
347
      if (currentSection.isEmpty()) {
×
348
        qWarning()
×
349
            << "Empty template section in .templates file, ignoring fields";
×
350
        skipInvalidSection = true;
351
        currentFields.clear();
×
352
      } else {
353
        skipInvalidSection = false;
354
        currentFields.clear();
×
355
      }
356
    } else if (!line.isEmpty() && !line.startsWith('#') &&
×
357
               !skipInvalidSection) {
358
      currentFields.append(line);
359
    }
360
  }
361
  if (!currentSection.isEmpty() && !skipInvalidSection) {
×
362
    result.insert(currentSection, currentFields);
363
  }
364
  return result;
365
}
×
366

367
/**
368
 * @brief Write templates to .templates file in password store.
369
 * @param storePath Path to password store root.
370
 * @param templates Hash of template name to field list.
371
 * @return true if write succeeded.
372
 */
373
auto Util::writeTemplates(const QString &storePath,
×
374
                          const QHash<QString, QStringList> &templates)
375
    -> bool {
376
  QSaveFile saveFile(QDir(storePath).filePath(".templates"));
×
377
  if (!saveFile.open(QIODevice::WriteOnly | QIODevice::Text)) {
×
378
    return false;
379
  }
380
  QTextStream out(&saveFile);
×
381
#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
382
  out.setEncoding(QStringConverter::Utf8);
×
383
#else
384
  out.setCodec("UTF-8");
385
#endif
386
  out << "# QtPass templates configuration\n";
×
387
  out << "# Format: INI-style with [template_name] sections,\n";
×
388
  out << "# followed by field names (one per line)\n\n";
×
389

390
  QStringList sortedKeys = templates.keys();
×
391
  std::sort(sortedKeys.begin(), sortedKeys.end());
×
392
  for (const QString &key : sortedKeys) {
×
393
    out << "[" << key << "]\n";
×
394
    for (const QString &field : templates.value(key)) {
×
395
      out << field << "\n";
×
396
    }
397
    out << "\n";
×
398
  }
399
  out.flush();
×
400
  if (out.status() != QTextStream::Ok) {
×
401
    return false;
402
  }
403
  return saveFile.commit();
×
404
}
×
405

406
/**
407
 * @brief Get default template for a folder.
408
 * Looks in folder, then parent folders up to root.
409
 * @param folderPath Path to folder.
410
 * @param storePath Path to password store root.
411
 * @return Template name or empty if none found.
412
 */
413
auto Util::getFolderTemplate(const QString &folderPath,
×
414
                             const QString &storePath) -> QString {
415
  QDir storeDir(storePath);
×
416
  QString cleanStoreAbs = QDir::cleanPath(storeDir.absolutePath());
×
417
  QString sep = QDir::separator();
×
418
  QDir dir(folderPath);
×
419
  while (true) {
420
    if (dir.exists(".default_template")) {
×
421
      QFile file(dir.filePath(".default_template"));
×
422
      if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
×
423
        QTextStream in(&file);
×
424
#if QT_VERSION >= QT_VERSION_CHECK(6, 0, 0)
425
        in.setEncoding(QStringConverter::Utf8);
×
426
#else
427
        in.setCodec("UTF-8");
428
#endif
429
        QString templateName = in.readLine().trimmed();
×
430
        file.close();
×
431
        if (!templateName.isEmpty() && !templateName.startsWith('#')) {
×
432
          return templateName;
433
        }
434
      }
×
435
    }
×
436
    QString currentPath = QDir::cleanPath(dir.absolutePath());
×
437
    if (currentPath == cleanStoreAbs) {
×
438
      break;
439
    }
440
    if (!currentPath.startsWith(cleanStoreAbs + sep)) {
×
441
      break;
442
    }
443
    if (!dir.cdUp()) {
×
444
      break;
445
    }
446
  }
447
  return {};
448
}
×
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc