File: wipedir.cpp

package info (click to toggle)
recoll 1.43.7-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 16,512 kB
  • sloc: cpp: 104,170; python: 9,500; xml: 7,248; ansic: 6,447; sh: 1,212; perl: 130; makefile: 72
file content (84 lines) | stat: -rw-r--r-- 2,257 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
/* Copyright (C) 2004-2019 J.F.Dockes
 *
 *   This program is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation; either version 2 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program; if not, write to the
 *   Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */
#include "autoconfig.h"

#include "wipedir.h"

#include <string>

#include "log.h"
#include "pathut.h"


int wipedir(const std::string& dir, bool selfalso, bool recurse)
{
    int ret = -1;

    if (!path_isdir(dir)) {
        LOGERR("wipedir: " << dir << " not a directory\n");
        return -1;
    }

    if (!path_access(dir, R_OK|W_OK|X_OK)) {
        LOGSYSERR("wipedir", "access", dir);
        return -1;
    }

    PathDirContents dc(dir);
    if (!dc.opendir()) {
        LOGSYSERR("wipedir", "opendir", dir);
        return -1;
    }
    int remaining = 0;
    const struct PathDirContents::Entry *ent;
    while ((ent = dc.readdir()) != nullptr) {
        const std::string& dname{ent->d_name};
        if (dname == "." || dname == "..")
            continue;

        std::string fn = path_cat(dir, dname);

        if (path_isdir(fn)) {
            if (recurse) {
                int rr = wipedir(fn, true, true);
                if (rr == -1) 
                    goto out;
                else 
                    remaining += rr;
            } else {
                remaining++;
            }
        } else {
            if (!path_unlink(fn)) {
                LOGSYSERR("wipedir", "unlink", fn);
                goto out;
            }
        }
    }

    ret = remaining;
    if (selfalso && ret == 0) {
        if (!path_rmdir(dir)) {
            LOGSYSERR("wipedir", "rmdir", dir);
            ret = -1;
        }
    }

out:
    return ret;
}