#include "DirectoryScanner.h"
#include "clang/DirectoryWatcher/DirectoryWatcher.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/Error.h"
#include "llvm/Support/Path.h"
#include <CoreServices/CoreServices.h>
#include <TargetConditionals.h>
using namespace llvm;
using namespace clang;
#if TARGET_OS_OSX
static void stopFSEventStream(FSEventStreamRef);
namespace {
class DirectoryWatcherMac : public clang::DirectoryWatcher {
public:
DirectoryWatcherMac(
dispatch_queue_t Queue, FSEventStreamRef EventStream,
std::function<void(llvm::ArrayRef<DirectoryWatcher::Event>, bool)>
Receiver,
llvm::StringRef WatchedDirPath)
: Queue(Queue), EventStream(EventStream), Receiver(Receiver),
WatchedDirPath(WatchedDirPath) {}
~DirectoryWatcherMac() override {
dispatch_sync(Queue, ^{
stopFSEventStream(EventStream);
EventStream = nullptr;
Receiver(
DirectoryWatcher::Event(
DirectoryWatcher::Event::EventKind::WatcherGotInvalidated, ""),
false);
});
dispatch_release(Queue);
}
private:
dispatch_queue_t Queue;
FSEventStreamRef EventStream;
std::function<void(llvm::ArrayRef<Event>, bool)> Receiver;
const std::string WatchedDirPath;
};
struct EventStreamContextData {
std::string WatchedPath;
std::function<void(llvm::ArrayRef<DirectoryWatcher::Event>, bool)> Receiver;
EventStreamContextData(
std::string &&WatchedPath,
std::function<void(llvm::ArrayRef<DirectoryWatcher::Event>, bool)>
Receiver)
: WatchedPath(std::move(WatchedPath)), Receiver(Receiver) {}
static void dispose(const void *ctx) {
delete static_cast<const EventStreamContextData *>(ctx);
}
};
}
constexpr const FSEventStreamEventFlags StreamInvalidatingFlags =
kFSEventStreamEventFlagUserDropped | kFSEventStreamEventFlagKernelDropped |
kFSEventStreamEventFlagMustScanSubDirs;
constexpr const FSEventStreamEventFlags ModifyingFileEvents =
kFSEventStreamEventFlagItemCreated | kFSEventStreamEventFlagItemRenamed |
kFSEventStreamEventFlagItemModified;
static void eventStreamCallback(ConstFSEventStreamRef Stream,
void *ClientCallBackInfo, size_t NumEvents,
void *EventPaths,
const FSEventStreamEventFlags EventFlags[],
const FSEventStreamEventId EventIds[]) {
auto *ctx = static_cast<EventStreamContextData *>(ClientCallBackInfo);
std::vector<DirectoryWatcher::Event> Events;
for (size_t i = 0; i < NumEvents; ++i) {
StringRef Path = ((const char **)EventPaths)[i];
const FSEventStreamEventFlags Flags = EventFlags[i];
if (Flags & StreamInvalidatingFlags) {
Events.emplace_back(DirectoryWatcher::Event{
DirectoryWatcher::Event::EventKind::WatcherGotInvalidated, ""});
break;
} else if (!(Flags & kFSEventStreamEventFlagItemIsFile)) {
if ((Flags & kFSEventStreamEventFlagItemRemoved) &&
Path == ctx->WatchedPath) {
Events.emplace_back(DirectoryWatcher::Event{
DirectoryWatcher::Event::EventKind::WatchedDirRemoved, ""});
Events.emplace_back(DirectoryWatcher::Event{
DirectoryWatcher::Event::EventKind::WatcherGotInvalidated, ""});
break;
}
continue;
} else if (Flags & kFSEventStreamEventFlagItemRemoved) {
Events.emplace_back(DirectoryWatcher::Event::EventKind::Removed,
llvm::sys::path::filename(Path));
continue;
} else if (Flags & ModifyingFileEvents) {
if (!getFileStatus(Path).hasValue()) {
Events.emplace_back(DirectoryWatcher::Event::EventKind::Removed,
llvm::sys::path::filename(Path));
} else {
Events.emplace_back(DirectoryWatcher::Event::EventKind::Modified,
llvm::sys::path::filename(Path));
}
continue;
}
Events.emplace_back(DirectoryWatcher::Event{
DirectoryWatcher::Event::EventKind::WatcherGotInvalidated, ""});
llvm_unreachable("Unknown FSEvent type.");
}
if (!Events.empty()) {
ctx->Receiver(Events, false);
}
}
FSEventStreamRef createFSEventStream(
StringRef Path,
std::function<void(llvm::ArrayRef<DirectoryWatcher::Event>, bool)> Receiver,
dispatch_queue_t Queue) {
if (Path.empty())
return nullptr;
CFMutableArrayRef PathsToWatch = [&]() {
CFMutableArrayRef PathsToWatch =
CFArrayCreateMutable(nullptr, 0, &kCFTypeArrayCallBacks);
CFStringRef CfPathStr =
CFStringCreateWithBytes(nullptr, (const UInt8 *)Path.data(),
Path.size(), kCFStringEncodingUTF8, false);
CFArrayAppendValue(PathsToWatch, CfPathStr);
CFRelease(CfPathStr);
return PathsToWatch;
}();
FSEventStreamContext Context = [&]() {
std::string RealPath;
{
SmallString<128> Storage;
StringRef P = llvm::Twine(Path).toNullTerminatedStringRef(Storage);
char Buffer[PATH_MAX];
if (::realpath(P.begin(), Buffer) != nullptr)
RealPath = Buffer;
else
RealPath = Path.str();
}
FSEventStreamContext Context;
Context.version = 0;
Context.info = new EventStreamContextData(std::move(RealPath), Receiver);
Context.retain = nullptr;
Context.release = EventStreamContextData::dispose;
Context.copyDescription = nullptr;
return Context;
}();
FSEventStreamRef Result = FSEventStreamCreate(
nullptr, eventStreamCallback, &Context, PathsToWatch,
kFSEventStreamEventIdSinceNow, 0.0,
kFSEventStreamCreateFlagFileEvents | kFSEventStreamCreateFlagNoDefer);
CFRelease(PathsToWatch);
return Result;
}
void stopFSEventStream(FSEventStreamRef EventStream) {
if (!EventStream)
return;
FSEventStreamStop(EventStream);
FSEventStreamInvalidate(EventStream);
FSEventStreamRelease(EventStream);
}
llvm::Expected<std::unique_ptr<DirectoryWatcher>> clang::DirectoryWatcher::create(
StringRef Path,
std::function<void(llvm::ArrayRef<DirectoryWatcher::Event>, bool)> Receiver,
bool WaitForInitialSync) {
dispatch_queue_t Queue =
dispatch_queue_create("DirectoryWatcher", DISPATCH_QUEUE_SERIAL);
if (Path.empty())
llvm::report_fatal_error(
"DirectoryWatcher::create can not accept an empty Path.");
auto EventStream = createFSEventStream(Path, Receiver, Queue);
assert(EventStream && "EventStream expected to be non-null");
std::unique_ptr<DirectoryWatcher> Result =
std::make_unique<DirectoryWatcherMac>(Queue, EventStream, Receiver, Path);
const std::string CopiedPath = Path.str();
auto InitWork = ^{
FSEventStreamSetDispatchQueue(EventStream, Queue);
FSEventStreamStart(EventStream);
Receiver(getAsFileEvents(scanDirectory(CopiedPath)), true);
};
if (WaitForInitialSync) {
dispatch_sync(Queue, InitWork);
} else {
dispatch_async(Queue, InitWork);
}
return Result;
}
#else
llvm::Expected<std::unique_ptr<DirectoryWatcher>>
clang::DirectoryWatcher::create(
StringRef Path,
std::function<void(llvm::ArrayRef<DirectoryWatcher::Event>, bool)> Receiver,
bool WaitForInitialSync) {
return llvm::make_error<llvm::StringError>(
"DirectoryWatcher is not implemented for this platform!",
llvm::inconvertibleErrorCode());
}
#endif