moved function remove_unlisted_files from intranator/generate to libi2ncommon because...
[libi2ncommon] / src / filefunc.cpp
index c427634..2de5a93 100644 (file)
@@ -41,6 +41,7 @@ on this file might be covered by the GNU General Public License.
 #include <string.h>
 
 #include <boost/scoped_array.hpp>
+#include <boost/foreach.hpp>
 #include "filefunc.hxx"
 #include "stringfunc.hxx"
 
@@ -875,4 +876,42 @@ mode_t umask(mode_t mask)
     return ::umask(mask);
 }
 
+
+/**
+ * @brief Remove unlisted files
+ *
+ * @param directory Direcotry to look for files
+ * @param keep_files List of files or directories to keep
+ * @param prefix Filename prefix to match. Empty prefix matches all.
+ *
+ * @return bool True if the directory was scanned, false on error (directory not found, permission denied)
+ **/
+bool remove_unlisted_files(const std::string &directory,
+                           const std::set<std::string> &keep_files,
+                           const std::string &prefix)
+{
+    std::vector<std::string> content;
+    if (!get_dir(directory, content, false))
+        return false;
+
+    bool all_fine = true;
+    BOOST_FOREACH(const std::string &file, content)
+    {
+        // Check for filename prefix (if any)
+        if (!prefix.empty() && file.find(prefix) != 0)
+            continue;
+
+        // Check if file is whitelisted
+        if (keep_files.find(file) != keep_files.end())
+            continue;
+
+        // Try to unlink file. (Continue on error)
+        if (!unlink(directory + "/" + file))
+            all_fine = false;
+    }
+
+    return all_fine;
+}
+
+
 } // eo namespace I2n