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

ossia / score / 40987115292

30 Oct 2026 01:27AM UTC coverage: 51.229% (+2.1%) from 49.178%
40987115292

push

github

jcelerier
avendish: main

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

179452 of 350293 relevant lines covered (51.23%)

175809.48 hits per line

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

80.39
/src/lib/score/tools/RecursiveWatch.cpp
1
#include <score/tools/RecursiveWatch.hpp>
2
#include <score/tools/ThreadPool.hpp>
3

4
#include <QCoreApplication>
5
#include <QDebug>
6
#include <QMetaObject>
7
#include <QPointer>
8
#include <Qt>
9

10
#include <atomic>
11
#include <cstddef>
12
#include <mutex>
13
#include <iostream>
14
#include <set>
15

16
#if __has_include(<version>)
17
#include <version>
18
#endif
19

20
// https://github.com/ned14/llfio/issues/144
21
#if __has_include(<llfio.hpp>) && !defined(__EMSCRIPTEN__)
22
#define SCORE_HAS_LLFIO 1
23
#elif defined(__APPLE__)
24
#if __MAC_OS_X_VERSION_MIN_REQUIRED >= __MAC_10_15
25
#if __cpp_lib_filesystem >= 201703
26
#define SCORE_HAS_STD_FILESYSTEM 1
27
#endif
28
#endif
29
#else
30
#if __cpp_lib_filesystem >= 201703
31
#define SCORE_HAS_STD_FILESYSTEM 1
32
#endif
33
#endif
34

35
#if SCORE_HAS_LLFIO
36
#define LLFIO_HEADERS_ONLY 1
37
//#define LLFIO_EXPERIMENTAL_STATUS_CODE 1
38
#define LLFIO_DISABLE_OPENSSL 1
39
#define QUICKCPPLIB_USE_STD_SPAN 1
40
// #define OUTCOME_USE_SYSTEM_STATUS_CODE 0
41

42
#if defined(__MINGW32__)
43
#define LLFIO_DISABLE_SIGNAL_GUARD 1
44
#endif
45

46
#if !defined(__has_feature)
47
#define __has_feature(T) 0
48
#endif
49
#if !defined(__has_extension)
50
#define __has_extension(T) 0
51
#endif
52

53
#include <llfio.hpp>
54
#elif SCORE_HAS_STD_FILESYSTEM
55
#include <filesystem>
56
#elif __has_include(<fts.h>)
57
#include <fts.h>
58

59
#include <cstring>
60
#define SCORE_HAS_FTS 1
61
#else
62
#error Platform missing a simple way to iterate directories.
63
#endif
64

65
namespace score
66
{
67
#if SCORE_HAS_LLFIO
68
static QString to_qstring(const std::filesystem::path& p)
×
69
{
70
#if !defined(_WIN32)
71
  return QString::fromStdString(p.native());
×
72
#else
73
  return QString::fromStdWString(p.native());
74
#endif
75
}
76

77
// root is a std::filesystem::path rather than a string so that recursing into a
78
// symlink keeps the native (wide, on Windows) path llfio handed us: a narrow
79
// round-trip would be read back as UTF-8 by llfio but as the ANSI code page by
80
// std::filesystem.
81
static void for_all_files(
2,954 ✔
82
    const std::filesystem::path& root, std::function<void(std::string_view)>& f,
83
    std::set<std::filesystem::path>& visited)
84
{
85
  using namespace LLFIO_V2_NAMESPACE;
86
  {
87
    std::error_code ec;
2,954 ✔
88
    if(!std::filesystem::is_directory(root, ec) || ec)
2,954 ✔
89
      return;
1 ✔
90

91
    // llfio never descends into symlinks (nor, on Windows, junctions): we follow
92
    // them ourselves below, so a link pointing back up the tree must not send us
93
    // around forever. Windows profiles ship such junctions, e.g.
94
    // AppData/Local/Application Data -> AppData/Local.
95
    auto canonical = std::filesystem::canonical(root, ec);
2,953 ✔
96
    if(ec || !visited.insert(std::move(canonical)).second)
2,953 ✔
97
      return;
1 ✔
98
  }
2,953 ✔
99

100
  auto pp = path_handle::path(root);
2,952 ✔
101
  if(!pp)
2,952 ✔
102
    return;
×
103

104
#if defined(_WIN32)
105
  // llfio gives the entries directly in root as root's own path, in NT form
106
  // ("\!!\Device\HarddiskVolume3\..."), plus their name, and the deeper ones
107
  // relative to root: bring both back under root. Joined as-is, the former
108
  // would come out as "C:\!!\Device\...", which does not exist.
109
  std::filesystem::path root_nt;
110
  if(auto cp = pp.value().current_path())
111
    root_nt = std::move(cp).value();
112
  const auto under_root = [&](const std::filesystem::path& e) {
113
    const auto& rn = root_nt.native();
114
    const auto& en = e.native();
115
    if(!rn.empty() && en.size() > rn.size() && en.starts_with(rn)
116
       && (en[rn.size()] == L'\\' || en[rn.size()] == L'/'))
117
      return root / std::wstring_view{en}.substr(rn.size() + 1);
118
    return root / e;
119
  };
120
#else
121
  // llfio gives absolute paths, which replace root when joined.
122
  const auto under_root = [&](const std::filesystem::path& e) { return root / e; };
11,699 ✔
123
#endif
124

125
  algorithm::contents_visitor vis;
2,952 ✔
126
  vis.contents_include_symlinks = true;
2,952 ✔
127
  try
128
  {
129
    // permit_racy_reads: on Windows NtQueryDirectoryFile() returns at most ~64Kb of
130
    // entries per call however large a buffer it is given, so a directory holding more
131
    // than that (~600 files with short names) cannot be enumerated as an atomic
132
    // snapshot, and the strict default fails the whole traversal rather than returning
133
    // the entries. The library is user content: it routinely has such directories, and
134
    // a best-effort listing of one is worth far more to us than a snapshot of nothing.
135
    if(auto res = algorithm::contents(
5,904 ✔
136
           pp.value(), &vis, 0, false, directory_handle::flags::permit_racy_reads))
2,952 ✔
137
    {
138
      try
139
      {
140
      for(auto& p : res.value())
29,055 ✔
141
      {
142
        try {
143
        switch(p.second.st_type)
26,103 ✔
144
        {
145
          case std::filesystem::file_type::symlink:
146
            for_all_files(under_root(p.first), f, visited);
2 ✔
147
            break;
2 ✔
148
          case std::filesystem::file_type::regular: {
149
            const std::filesystem::path r = under_root(p.first);
8,745 ✔
150

151
#if !defined(_WIN32)
152
            f(r.native());
8,745 ✔
153
#else
154
            try {
155
              // UTF-8 whatever the process code page: generic_string() would
156
              // be in the ANSI one, which only the app's manifest makes UTF-8.
157
              const auto s = r.generic_u8string();
158
              f(std::string_view{reinterpret_cast<const char*>(s.data()), s.size()});
159
            }
160
            catch(...)
161
            {
162
              // Very inefficient but the conversion sometimes throws
163
              // filesystem error: in __wide_to_char: Illegal byte sequence
164
              // on windows
165
              auto s = QString::fromStdWString(r.native()).toStdString();
166
              std::replace(s.begin(), s.end(), '\\', '/');
167
              f(s);
168
            }
169
#endif
170
            break;
171
          }
8,745 ✔
172
          default:
173
            break;
17,356 ✔
174
        }
175
        }
26,103 ✔
176
        catch(const std::exception& e)
177
        {
178
        }
×
179
        catch(...)
180
        {
181
        }
×
182
      }
183
      }
2,952 ✔
184
      catch(const std::exception& e)
185
      {
186
      }
×
187
      catch(...)
188
      {
189
      }
×
190
    }
2,952 ✔
191
    else
192
    {
193
      // A failure here yields no files at all, which is indistinguishable from an empty
194
      // library unless we say so.
195
      qWarning() << "for_all_files: could not enumerate" << to_qstring(root) << ':'
×
196
                 << QString::fromStdString(make_error_code(res.error()).message());
×
197
    }
198
  }
2,952 ✔
199
  catch(const std::exception& e)
200
  {
201
  }
×
202
  catch(...)
203
  {
204
  }
×
205
}
2,954 ✔
206

207
void for_all_files(std::string_view root, std::function<void(std::string_view)> f)
2,952 ✔
208
try
209
{
210
  // root is UTF-8: spell it out, as a narrow string is otherwise read with the
211
  // ANSI code page on Windows.
212
  const std::filesystem::path rootp{std::u8string_view{
2,952 ✔
213
      reinterpret_cast<const char8_t*>(root.data()), root.size()}};
2,952 ✔
214
  std::set<std::filesystem::path> visited;
2,952 ✔
215
  for_all_files(rootp, f, visited);
2,952 ✔
216
}
2,952 ✔
217
catch(...)
218
{
219
}
2,952 ✔
220
#endif
221

222
#if SCORE_HAS_STD_FILESYSTEM
223
void for_all_files(std::string_view root, std::function<void(std::string_view)> f)
224
try
225
{
226
  namespace fs = std::filesystem;
227
  using iterator = fs::recursive_directory_iterator;
228
#if defined(_WIN32)
229
  constexpr auto options = fs::directory_options::skip_permission_denied;
230
#else
231
  constexpr auto options = fs::directory_options::follow_directory_symlink
232
                           | fs::directory_options::skip_permission_denied;
233
#endif
234
  for(auto it = iterator{root, options}, end = iterator{}; it != end; ++it)
235
  {
236
    try
237
    {
238
      const auto& path = it->path();
239
#if defined(_WIN32)
240
      std::string path_str = path.generic_string();
241
#else
242
      std::string_view path_str = path.native();
243
#endif
244
      if(path_str.empty())
245
        continue;
246
      auto last_slash = path_str.find_last_of('/');
247
      if(last_slash == path_str.npos || last_slash == path_str.length() - 1)
248
        continue;
249
      if(path_str[last_slash + 1] == '.')
250
      {
251
        it.disable_recursion_pending();
252
        continue;
253
      }
254

255
      f(path_str);
256
    }
257
    catch(...)
258
    {
259
      continue;
260
    }
261
  }
262
}
263
catch(...)
264
{
265
}
266
#elif SCORE_HAS_FTS
267
static void
268
process_file(FTS* fts, FTSENT* curr, std::function<void(std::string_view)>& f)
269
{
270
  switch(curr->fts_info)
271
  {
272
    case FTS_NS:
273
    case FTS_DNR:
274
    case FTS_ERR:
275
      std::cerr << "for_all_files: " << curr->fts_accpath << ":"
276
                << strerror(curr->fts_errno) << std::endl;
277
      break;
278

279
    case FTS_DC:
280
    case FTS_DOT:
281
      break;
282

283
    // Skip unwanted folders (.git, etc)
284
    case FTS_D: {
285
      if(curr->fts_name[0] == '.')
286
      {
287
        fts_set(fts, curr, FTS_SKIP);
288
      }
289

290
      break;
291
    }
292

293
    // Process our file
294
    case FTS_NSOK:
295
    case FTS_F: {
296
      f(curr->fts_path);
297
      break;
298
    }
299
    case FTS_DP:
300
    case FTS_SL:
301
    case FTS_SLNONE:
302
    case FTS_DEFAULT:
303
      break;
304
  }
305
}
306

307
void for_all_files(std::string_view root, std::function<void(std::string_view)> f)
308
{
309
  char* files[] = {(char*)root.data(), nullptr};
310
  auto fts = fts_open(files, FTS_NOCHDIR | FTS_LOGICAL | FTS_NOSTAT, nullptr);
311
  if(!fts)
312
  {
313
    return;
314
  }
315

316
  while(auto curr = fts_read(fts))
317
  {
318
    process_file(fts, curr, f);
319
  }
320

321
  fts_close(fts);
322
}
323
#endif
324

325
}
326

327
namespace score
328
{
329
struct RecursiveWatch::AsyncScan
2,943 ✔
330
{
331
  std::atomic_bool cancelled{false};
2,943 ✔
332
  std::mutex handler_mutex;
333
};
334

335
namespace
336
{
337
// Mitigation for same bug as https://github.com/microsoft/STL/issues/165
338
struct AsyncScanState
339
{
340
  using Map = ossia::string_map<std::vector<RecursiveWatch::AsyncCallbacks>>;
341

342
  Map watched;
343
  std::string root;
344
  QPointer<QObject> ctx;
345
  std::shared_ptr<RecursiveWatch::AsyncScan> scan;
346

347
  AsyncScanState(
2,943 ✔
348
      Map&& w, std::string r, QObject* c, std::shared_ptr<RecursiveWatch::AsyncScan> s)
349
      : watched{std::move(w)}
2,943 ✔
350
      , root{std::move(r)}
2,943 ✔
351
      , ctx{c}
2,943 ✔
352
      , scan{std::move(s)}
2,943 ✔
353
  {
354
  }
2,943 ✔
355

356
  AsyncScanState(AsyncScanState&& other) noexcept
8,829 ✔
357
      : watched{std::move(other.watched)}
8,829 ✔
358
      , root{std::move(other.root)}
8,829 ✔
359
      , ctx{std::move(other.ctx)}
8,829 ✔
360
      , scan{std::move(other.scan)}
8,829 ✔
361
  {
362
  }
8,829 ✔
363

364
  AsyncScanState(const AsyncScanState&) = delete;
365
  AsyncScanState& operator=(AsyncScanState&&) = delete;
366
  AsyncScanState& operator=(const AsyncScanState&) = delete;
367
};
368
}
369

370
void RecursiveWatch::scan() const
×
371
{
372
#if !defined(SCORE_DEPLOYMENT_BUILD)
373
  static const bool disable_library = qEnvironmentVariableIsSet("SCORE_DISABLE_LIBRARY");
×
374
  if(Q_UNLIKELY(disable_library))
×
375
    return;
×
376
#endif
377

378
  for_all_files(m_root, [this](std::string_view path) {
×
379
    if(path.empty())
×
380
      return;
×
381
    if(auto last_dot = path.find_last_of('.'); last_dot < path.size() - 1)
×
382
    {
383
      std::string_view suffix = path.substr(last_dot + 1);
×
384
      if(auto it = m_watched.find(suffix); it != m_watched.end())
×
385
      {
386
        for(auto& handler : it->second)
×
387
        {
388
          handler.added(path);
×
389
        }
390
      }
×
391
    }
×
392
  });
×
393
}
×
394

395
void RecursiveWatch::scanAsync(QObject* context)
2,943 ✔
396
{
397
#if !defined(SCORE_DEPLOYMENT_BUILD)
398
  static const bool disable_library = qEnvironmentVariableIsSet("SCORE_DISABLE_LIBRARY");
2,943 ✔
399
  if(Q_UNLIKELY(disable_library))
2,943 ✔
400
    return;
×
401
#endif
402

403
  // Note that callers should always set a new set of watched things
404
  // before calling scanAsync.
405
  cancelAsync();
2,943 ✔
406
  m_scan = std::make_shared<AsyncScan>();
2,943 ✔
407
  score::TaskPool::instance().post(
2,943 ✔
408
      [state = AsyncScanState{std::move(m_asyncWatched), m_root, context, m_scan}] {
5,886 ✔
409
    std::vector<std::function<void()>> actions;
2,943 ✔
410

411
    auto send_to_main_thread = [pctx = state.ctx, scan = state.scan, &actions] {
5,867 ✔
412
      // Batch-deliver all commit actions to the GUI thread
413
      QMetaObject::invokeMethod(
2,924 ✔
414
          QCoreApplication::instance(),
2,924 ✔
415
          [pctx = pctx, scan = scan, actions = std::move(actions)] {
5,845 ✔
416
        if(!pctx || scan->cancelled)
2,921 ✔
417
          return;
2 ✔
418
        for(auto& action : actions)
5,775 ✔
419
          action();
2,856 ✔
420
      }, Qt::QueuedConnection);
2,921 ✔
421

422
      actions.clear();
2,924 ✔
423
    };
2,924 ✔
424

425
    for_all_files(state.root, [&](std::string_view path) {
11,458 ✔
426
      // The handlers were handed over by the object that asked for the scan and
427
      // are free to reach back into it. Once it is gone there is nothing left
428
      // for them to reach, and the walk has nobody to report to either.
429
      std::lock_guard handler_lock{state.scan->handler_mutex};
8,515 ✔
430
      if(!state.ctx || state.scan->cancelled)
8,515 ✔
431
        return;
3,176 ✔
432
      if(path.empty())
5,339 ✔
433
        return;
×
434
      auto last_dot = path.find_last_of('.');
5,339 ✔
435
      if(last_dot >= path.size() - 1)
5,339 ✔
436
        return;
×
437

438
      std::string_view suffix = path.substr(last_dot + 1);
5,339 ✔
439
      auto it = state.watched.find(suffix);
5,339 ✔
440
      if(it == state.watched.end())
5,339 ✔
441
        return;
2,448 ✔
442
      for(auto& handler : it->second)
5,782 ✔
443
      {
444
        if(auto action = handler.filter(path))
5,781 ✔
445
        {
446
          actions.push_back(std::move(action));
2,890 ✔
447
          if(actions.size() >= 255)
2,890 ✔
448
            send_to_main_thread();
1 ✔
449
        }
2,890 ✔
450
      }
451
    });
8,515 ✔
452

453
    if(!state.scan->cancelled)
2,943 ✔
454
      send_to_main_thread();
2,923 ✔
455
  });
2,943 ✔
456
}
2,943 ✔
457

458
void RecursiveWatch::cancelAsync() noexcept
11,784 ✔
459
{
460
  if(!m_scan)
11,784 ✔
461
    return;
8,842 ✔
462
  m_scan->cancelled = true;
2,942 ✔
463
  std::lock_guard handler_lock{m_scan->handler_mutex};
2,942 ✔
464
  m_scan.reset();
2,942 ✔
465
}
11,784 ✔
466

467
namespace
468
{
469
struct LiveWatches
470
{
471
  std::mutex mutex;
472
  std::vector<RecursiveWatch*> watches;
473
};
474
LiveWatches& liveWatches()
9,881 ✔
475
{
476
  static LiveWatches w;
9,881 ✔
477
  return w;
9,881 ✔
478
}
479
}
480

481
RecursiveWatch::RecursiveWatch()
2,953 ✔
482
{
483
  auto& live = liveWatches();
2,953 ✔
484
  std::lock_guard lock{live.mutex};
2,953 ✔
485
  live.watches.push_back(this);
2,953 ✔
486
}
2,953 ✔
487

488
RecursiveWatch::~RecursiveWatch()
2,952 ✔
489
{
490
  cancelAsync();
2,952 ✔
491
  auto& live = liveWatches();
2,952 ✔
492
  std::lock_guard lock{live.mutex};
2,952 ✔
493
  std::erase(live.watches, this);
2,952 ✔
494
}
2,952 ✔
495

496
void RecursiveWatch::cancelAll() noexcept
3,976 ✔
497
{
498
  auto& live = liveWatches();
3,976 ✔
499
  std::lock_guard lock{live.mutex};
3,976 ✔
500
  for(auto* w : live.watches)
6,896 ✔
501
    w->cancelAsync();
2,920 ✔
502
}
3,976 ✔
503

504
void RecursiveWatch::reset()
2,944 ✔
505
{
506
  cancelAsync();
2,944 ✔
507
  m_root.clear();
2,944 ✔
508
  m_watched.clear();
2,944 ✔
509
  m_asyncWatched.clear();
2,944 ✔
510
}
2,944 ✔
511
}
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