1 // Copyright 2022` The Android Open Source Project
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 #pragma once
16 
17 #include <stddef.h>       // for size_t
18 #include <functional>     // for function
19 #include <memory>         // for unique_ptr
20 #include <string>         // for std::string
21 #include <unordered_set>  // for unordered_set
22 
23 namespace android {
24 namespace base {
25 
26 // Listens to the file system change notifications and raises events when a
27 // directory, or file in a directory, changes.
28 //
29 // Note: Each observer consumes one thread.
30 // Note: It is very expensive on mac os, so do not observe large directory
31 // structures with this.
32 class FileSystemWatcher {
33 public:
34     // On one day we will have std::filesystem everywhere..
35     using Path = std::string;
36 
37     enum class WatcherChangeType {
38         Created,  // The creation of a file or folder.
39         Deleted,  // The deletion of a file or folder.
40         Changed,  // The change of a file or folder. The types of changes
41                   // include: changes to size, attributes, security
42                   // settings, last write, and last access time.
43     };
44 
45     // Change type, and file that was created, deleted or changed.
46     using FileSystemWatcherCallback =
47             std::function<void(WatcherChangeType, const Path&)>;
48 
FileSystemWatcher(FileSystemWatcherCallback callback)49     FileSystemWatcher(FileSystemWatcherCallback callback)
50         : mChangeCallback(callback) {}
51     virtual ~FileSystemWatcher() = default;
52 
53     virtual bool start() = 0;
54     virtual void stop() = 0;
55 
56     // Watches for changes in the given directory.
57     // Returns nullptr if path is not a directory.
58     static std::unique_ptr<FileSystemWatcher> getFileSystemWatcher(
59             Path path,
60             FileSystemWatcherCallback onChangeCallback);
61 
62     FileSystemWatcherCallback mChangeCallback;
63 };
64 }  // namespace base
65 }  // namespace android
66