* French manpage translation update
[ntk/apt.git] / apt-pkg / contrib / fileutl.cc
index 4240d9f..cce8a45 100644 (file)
 #include <sys/types.h>
 #include <sys/time.h>
 #include <sys/wait.h>
+#include <dirent.h>
 #include <signal.h>
 #include <errno.h>
 #include <set>
+#include <algorithm>
                                                                        /*}}}*/
 
 using namespace std;
@@ -195,6 +197,54 @@ bool FileExists(string File)
    return true;
 }
                                                                        /*}}}*/
+// GetListOfFilesInDir - returns a vector of files in the given dir    /*{{{*/
+// ---------------------------------------------------------------------
+/* If an extension is given only files with this extension are included
+   in the returned vector, otherwise every "normal" file is included. */
+std::vector<string> GetListOfFilesInDir(string const &Dir, string const &Ext,
+                                       bool const &SortList) 
+{
+   std::vector<string> List;
+   DIR *D = opendir(Dir.c_str());
+   if (D == 0) 
+   {
+      _error->Errno("opendir",_("Unable to read %s"),Dir.c_str());
+      return List;
+   }
+
+   for (struct dirent *Ent = readdir(D); Ent != 0; Ent = readdir(D)) 
+   {
+      if (Ent->d_name[0] == '.')
+        continue;
+
+      if (Ext.empty() == false && flExtension(Ent->d_name) != Ext)
+        continue;
+
+      // Skip bad file names ala run-parts
+      const char *C = Ent->d_name;
+      for (; *C != 0; ++C)
+        if (isalpha(*C) == 0 && isdigit(*C) == 0
+            && *C != '_' && *C != '-' && *C != '.')
+           break;
+
+      if (*C != 0)
+        continue;
+
+      // Make sure it is a file and not something else
+      string const File = flCombine(Dir,Ent->d_name);
+      struct stat St;
+      if (stat(File.c_str(),&St) != 0 || S_ISREG(St.st_mode) == 0)
+        continue;
+
+      List.push_back(File);
+   }
+   closedir(D);
+
+   if (SortList == true)
+      std::sort(List.begin(),List.end());
+   return List;
+}
+                                                                       /*}}}*/
 // SafeGetCWD - This is a safer getcwd that returns a dynamic string   /*{{{*/
 // ---------------------------------------------------------------------
 /* We return / on failure. */