emilib
dir_watcher.hpp
1 // By Emil Ernerfeldt 2014-2016
2 // LICENSE:
3 // This software is dual-licensed to the public domain and under the following
4 // license: you are granted a perpetual, irrevocable license to copy, modify,
5 // publish, and distribute this file as you see fit.
6 // HISTORY
7 // 2014 - Created for Ghostel
8 // 2016 - revived for PipeDreams
9 // 2016 - added to emilib
10 
11 #pragma once
12 
13 #include <ctime>
14 #include <set>
15 #include <string>
16 #include <vector>
17 
18 struct kevent;
19 
20 namespace emilib {
21 
24 {
25 public:
27  explicit DirWatcher(std::string dir);
28  ~DirWatcher();
29 
31  std::vector<std::string> poll_files();
32 
33 private:
34  DirWatcher(DirWatcher&) = delete;
35  DirWatcher(DirWatcher&&) = delete;
36  DirWatcher& operator=(DirWatcher&) = delete;
37  DirWatcher& operator=(DirWatcher&&) = delete;
38 
39  struct File
40  {
41  std::string path; // Full, absolute path.
42  std::string file_name;
43  time_t mtime;
44  bool is_dir;
45  std::vector<File> children;
46  int fd = -1; // File descriptor
47  };
48 
49  void create();
50  void add_dir(std::string dir);
51  void destroy();
52 
53  void add_dir(File& dir);
54  void poll_files_in(std::vector<std::string>& changes, File& dir);
55  void rescan(std::vector<std::string>& changes, File& dir);
56 
57  void add_kevent(File& file);
58 
59  void close_file(File& file);
60 
61 private:
62  const std::string _dir;
63  bool _recursive = true;
64  bool _check_files = true;
65  std::vector<File> _dirs;
66  std::vector<kevent> _events;
67  int _kqueue;
68 };
69 
70 // -------------------------------------------------------
71 
74 {
75 public:
77  DelayedDirWatcher(std::string dir, unsigned frame_delay = 6);
78 
79  std::vector<std::string> poll_files();
80 
81 private:
82  const unsigned _frame_delay;
83  DirWatcher _dir_watcher;
84  std::set<std::string> _dirty_files;
85  unsigned _frames_since_last_change = 0;
86 };
87 
88 } // namespace emilib
Acts like DirWatcher but with a delay of a few frames to let things &#39;settle&#39;.
Definition: dir_watcher.hpp:73
Watches for any changes in a directory (file changed, added, removed).
Definition: dir_watcher.hpp:23
std::vector< std::string > poll_files()
Returns a list of absolute paths to files that where added, removed or changed.
DirWatcher(std::string dir)
Feel free to end with a slash or not.
Definition: coroutine.hpp:18