Add remove_directory_internal function and use it in PBD::clear_directory and PBD...
[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 #ifdef COMPILER_MSVC
21 #include <io.h>      // Microsoft's nearest equivalent to <unistd.h>
22 using PBD::readdir;
23 using PBD::opendir;
24 using PBD::closedir;
25 #else
26 #include <dirent.h>
27 #include <unistd.h>
28 #endif
29
30 #include <string>
31 #include <sys/stat.h>
32 #include <errno.h>
33 #include <string.h>
34
35 #include <glib.h>
36 #include <glib/gstdio.h>
37 #include <glibmm/miscutils.h>
38
39 #include "pbd/error.h"
40 #include "pbd/compose.h"
41 #include "pbd/clear_dir.h"
42 #include "pbd/file_utils.h"
43
44 #include "i18n.h"
45
46 using namespace PBD;
47 using namespace std;
48
49 int
50 remove_directory_internal (const string& dir, size_t* size, vector<string>* paths,
51                            bool just_remove_files)
52 {
53         vector<string> tmp_paths;
54         struct stat statbuf;
55         int ret = 0;
56
57         get_directory_contents (dir, tmp_paths, just_remove_files, true);
58
59         for (vector<string>::const_iterator i = tmp_paths.begin();
60              i != tmp_paths.end(); ++i) {
61
62                 if (g_stat (i->c_str(), &statbuf)) {
63                         continue;
64                 }
65
66                 if (::g_remove (i->c_str())) {
67                         error << string_compose (_("cannot remove path %1 (%2)"), *i, strerror (errno))
68                               << endmsg;
69                         ret = 1;
70                 }
71
72                 if (paths) {
73                         paths->push_back (Glib::path_get_basename(*i));
74                 }
75
76                 if (size) {
77                         *size += statbuf.st_size;
78                 }
79
80         }
81
82         return ret;
83 }
84
85 int
86 PBD::clear_directory (const string& dir, size_t* size, vector<string>* paths)
87 {
88         return remove_directory_internal (dir, size, paths, true);
89 }
90
91 // rm -rf <dir> -- used to remove saved plugin state
92 void
93 PBD::remove_directory (const std::string& dir)
94 {
95         remove_directory_internal (dir, 0, 0, false);
96 }