lfilesystem  0.0.1
C++ filesystem library
files_dir_listen.cpp
1 /*
2  * ======================================================================================
3  * __ ____ __ __ ____ ___
4  * ( ) (_ _)( \/ )( ___)/ __)
5  * )(__ _)(_ ) ( )__) \__ \
6  * (____)(____)(_/\/\_)(____)(___/
7  *
8  * This file is part of the Limes open source library and is licensed under the terms of the GNU Public License.
9  *
10  * Commercial licenses are available; contact the maintainers at ben.the.vining@gmail.com to inquire for details.
11  *
12  * ======================================================================================
13  */
14 
16 #include <vector>
17 
19 {
20  explicit JSONWatcher (const limes::files::Directory& dir)
21  : limes::files::FileWatcher (dir), directory (dir)
22  { }
23 
24  std::vector<limes::files::File> jsonFiles;
25  const limes::files::Directory directory;
26 
27  void fileCreated (const limes::files::FilesystemEntry& file) final
28  {
29  if (! directory.contains (file))
30  return;
31 
32  if (const auto fileObj = file.getFileObject())
33  {
34  if (fileObj->hasFileExtension (".json"))
35  jsonFiles.emplace_back (*fileObj);
36  }
37  }
38 
39  void fileDeleted (const limes::files::FilesystemEntry& file) final
40  {
41  jsonFiles.erase (std::find_if (jsonFiles.begin(), jsonFiles.end(),
42  [p = file.getAbsolutePath()] (limes::files::File& f)
43  {
44  return f.getAbsolutePath() == p;
45  }));
46  }
47 
48  void fileMoved (const limes::files::FilesystemEntry& file) final
49  {
50  if (! directory.contains (file))
51  {
52  fileDeleted (file);
53  return;
54  }
55 
56  if (const auto fileObj = file.getFileObject())
57  {
58  if (! fileObj->hasFileExtension (".json"))
59  return;
60 
61  const auto alreadyInList = (std::find (jsonFiles.begin(),
62  jsonFiles.end(),
63  *fileObj)
64  != jsonFiles.end());
65 
66  if (! alreadyInList)
67  jsonFiles.emplace_back (*fileObj);
68  }
69  }
70 };
71 
72 const limes::files::Directory dir { "/my/directory" };
73 
74 JSONWatcher watcher { dir };
This class represents a directory on the filesystem.
bool contains(const FilesystemEntry &entry, std::size_t depthLimit=50) const
Returns true if this directory contains the passed FilesystemEntry.
This class listens for changes to or operations on a certain file, and receives callbacks to be notif...
This class represents a file on the filesystem.
The base class for any kind of object on the filesystem.
The main header for the limes_files library.
void fileDeleted(const limes::files::FilesystemEntry &file) final
Called when a file is deleted.
void fileCreated(const limes::files::FilesystemEntry &file) final
Called when a file or subdirectory is created in a watched directory.
void fileMoved(const limes::files::FilesystemEntry &file) final
Called when a file is moved or renamed.