Remove dynamic exceptions
[anna.git] / source / io / Directory.cpp
1 // ANNA - Anna is Not Nothingness Anymore                                                         //
2 //                                                                                                //
3 // (c) Copyright 2005-2015 Eduardo Ramos Testillano & Francisco Ruiz Rayo                         //
4 //                                                                                                //
5 // See project site at http://redmine.teslayout.com/projects/anna-suite                           //
6 // See accompanying file LICENSE or copy at http://www.teslayout.com/projects/public/anna.LICENSE //
7
8
9 #include <string.h>
10 #include <limits.h>
11 #include <dirent.h>
12 #include <sys/types.h>
13 #include <stdio.h>
14
15 #include <algorithm>
16
17 #include <anna/config/defines.hpp>
18
19 #include <anna/io/Directory.hpp>
20 #include <anna/io/internal/sccs.hpp>
21
22 using namespace std;
23 using namespace anna;
24
25 io::Directory::Directory() :
26   a_hasPattern(false) {
27   io::sccs::activate();
28 }
29
30 void io::Directory::setPattern(const char* expression)
31 noexcept(false) {
32   if(a_hasPattern == true) {
33     regfree(&a_regex);
34     a_hasPattern = false;
35   }
36
37   if(expression == NULL)
38     return;
39
40   int ret;
41
42   if((ret = regcomp(&a_regex, expression, REG_EXTENDED)) != 0) {
43     char err[256];
44     string msg("io::Directory | Pattern: ");
45     msg += expression;
46     msg += " | Error: ";
47
48     if(regerror(ret, &a_regex, err, sizeof(err)))
49       msg += err;
50     else
51       msg += "Invalid pattern";
52
53     throw RuntimeException(msg, ANNA_FILE_LOCATION);
54   }
55
56   a_hasPattern = true;
57 }
58
59 void io::Directory:: read(const char* dirName, const Mode::_v mode)
60 noexcept(false) {
61   DIR* handle;
62   dirent* entry;
63   string file;
64
65   if((handle = opendir(dirName)) == NULL) {
66     const int aux_errno(errno);
67     throw RuntimeException(string(dirName), aux_errno, ANNA_FILE_LOCATION);
68   }
69
70   a_files.clear();
71
72   while((entry = readdir(handle)) != NULL) {
73     if(!anna_strcmp(entry->d_name, ".") || !anna_strcmp(entry->d_name, ".."))
74       continue;
75
76     if(a_hasPattern == true)
77       if(regexec(&a_regex, entry->d_name, 0, NULL, 0) != 0)
78         continue;
79
80     if(mode == Mode::FullPath) {
81       file = dirName;
82       file += "/";
83       file += entry->d_name;
84     } else
85       file = entry->d_name;
86
87     a_files.push_back(file);
88   }
89
90   closedir(handle);
91 }
92
93 io::Directory::const_iterator io::Directory::find(const std::string& file) const
94 {
95   return std::find(begin(), end(), file);
96 }
97