catch assert()
[ardour.git] / libs / pbd / clear_dir.cc
1 /*
2     Copyright (C) 2012 Paul Davis 
3
4     This program is free software; you can redistribute it and/or modify
5     it under the terms of the GNU General Public License as published by
6     the Free Software Foundation; either version 2 of the License, or
7     (at your option) any later version.
8
9     This program is distributed in the hope that it will be useful,
10     but WITHOUT ANY WARRANTY; without even the implied warranty of
11     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12     GNU General Public License for more details.
13
14     You should have received a copy of the GNU General Public License
15     along with this program; if not, write to the Free Software
16     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17
18 */
19
20 #include <string>
21 #include <dirent.h>
22 #include <unistd.h>
23 #include <sys/stat.h>
24 #include <errno.h>
25 #include <string.h>
26
27 #include <glibmm/miscutils.h>
28
29 #include "pbd/error.h"
30 #include "pbd/compose.h"
31 #include "pbd/clear_dir.h"
32
33 #include "i18n.h"
34
35 using namespace PBD;
36 using namespace std;
37
38 int
39 PBD::clear_directory (const string& dir, size_t* size, vector<string>* paths)
40 {
41         struct dirent* dentry;
42         struct stat statbuf;
43         DIR* dead;
44         int ret = 0;
45
46         if ((dead = ::opendir (dir.c_str())) == 0) {
47                 return -1;
48         }
49         
50         while ((dentry = ::readdir (dead)) != 0) {
51                 
52                 /* avoid '.' and '..' */
53                 
54                 if ((dentry->d_name[0] == '.' && dentry->d_name[1] == '\0') ||
55                     (dentry->d_name[2] == '\0' && dentry->d_name[0] == '.' && dentry->d_name[1] == '.')) {
56                         continue;
57                 }
58                 
59                 string fullpath = Glib::build_filename (dir, dentry->d_name);
60
61                 if (::stat (fullpath.c_str(), &statbuf)) {
62                         continue;
63                 }
64                 
65                 if (!S_ISREG (statbuf.st_mode)) {
66                         continue;
67                 }
68                 
69                 if (::unlink (fullpath.c_str())) {
70                         error << string_compose (_("cannot remove file %1 (%2)"), fullpath, strerror (errno))
71                               << endmsg;
72                         ret = 1;
73                 }
74
75                 if (paths) {
76                         paths->push_back (dentry->d_name);
77                 }
78
79                 if (size) {
80                         *size += statbuf.st_size;
81                 }
82         }
83         
84         ::closedir (dead);
85
86         return ret;
87 }