moved function remove_unlisted_files from intranator/generate to libi2ncommon because...
authorChristian Herdtweck <christian.herdtweck@intra2net.com>
Tue, 25 Nov 2014 12:44:42 +0000 (13:44 +0100)
committerChristian Herdtweck <christian.herdtweck@intra2net.com>
Tue, 25 Nov 2014 12:44:42 +0000 (13:44 +0100)
src/filefunc.cpp
src/filefunc.hxx

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
index 8ea0e1b..6bab70b 100644 (file)
@@ -26,6 +26,7 @@ on this file might be covered by the GNU General Public License.
 #define __FILEFUNC_HXX
 
 #include "userfunc.hpp"
+#include <set>
 
 namespace I2n
 {
@@ -186,6 +187,13 @@ bool chdir(const std::string &path, std::string *error=NULL);
 
 mode_t umask(mode_t mask);
 
+
+/*
+** more specialized tool function(s)
+*/
+bool remove_unlisted_files(const std::string &directory, const std::set<std::string> &keep_files,
+                                            const std::string &prefix="");
+
 }
 
 #endif