rapid-delete-lib 0.3.1

A high-performance file deletion library
Documentation
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
/*
  Copyright 2025 Adam Sweeney

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/

// NOTICE
// Modified from turbo-delete (https://github.com/suptejas/turbo-delete)
// Licensed under Apache-2.0
// Changes: refactored for library use

/*
  Copyright 2022 Tejas Ravishankar

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/

//! A library for fast, parallel directory deletion with permission handling.
//!
//! This library provides functionality to recursively delete directories,
//! automatically handling read-only files and permission issues that might
//! prevent deletion.

#[cfg(feature = "progressbar")]
use indicatif::ProgressBar;
use jwalk::DirEntry;
use rayon::iter::{IntoParallelRefIterator, ParallelBridge, ParallelIterator};
use rusty_pool::ThreadPool;
use std::{
    collections::BTreeMap,
    path::{Path, PathBuf},
};
use thiserror::Error;

#[derive(Error, Debug)]
pub enum RdError {
    #[error("Failed to read metadata for {0}: {1}")]
    MetadataError(PathBuf, std::io::Error),

    #[error("Failed to set permissions for: {0}: {1}")]
    PermissionError(PathBuf, std::io::Error),

    #[error("Failed to remove item {0}: {1}")]
    RemoveError(PathBuf, std::io::Error),

    #[error("Failed to walk directory: {0}: {1}")]
    WalkdirError(PathBuf, String),

    #[error("IO error: {0}")]
    Io(#[from] std::io::Error),
}

impl From<RdError> for std::io::Error {
    fn from(err: RdError) -> Self {
        match err {
            RdError::Io(e) => e,
            RdError::MetadataError(_, e) => e,
            RdError::PermissionError(_, e) => e,
            RdError::RemoveError(_, e) => e,
            RdError::WalkdirError(path, msg) => std::io::Error::new(
                std::io::ErrorKind::Other,
                format!("Failed to walk directory {}: {}", path.display(), msg),
            ),
        }
    }
}

/// Makes a file or directory writable by removing the read-only flag.
///
/// # Arguments
///
/// * `path` - The path to the file or directory to make writable
///
/// # Errors
///
/// Returns an error if:
/// * The metadata cannot be read
/// * The permissions cannot be set
fn set_writable(path: &Path) -> Result<(), RdError> {
    let mut perms = std::fs::metadata(path)
        .map_err(|err| RdError::MetadataError(path.to_path_buf(), err))?
        .permissions();

    perms.set_readonly(false);
    std::fs::set_permissions(path, perms)
        .map_err(|err| RdError::PermissionError(path.to_path_buf(), err))?;

    Ok(())
}

/// Recursively makes all files in a directory writable.
///
/// This function walks through all files in the given directory (following symlinks)
/// and removes the read-only flag from each file in parallel.
///
/// # Arguments
///
/// * `path` - The root directory path to process
///
/// # Errors
///
/// Returns an error if:
/// * The directory walk fails
/// * Any file's permissions cannot be modified
fn set_folder_writable(path: &Path) -> Result<(), RdError> {
    let entries: Vec<DirEntry<((), ())>> = jwalk::WalkDir::new(&path)
        .skip_hidden(false)
        .into_iter()
        .filter_map(|i| match i {
            Ok(entry) if entry.file_type().is_file() => Some(Ok(entry)),
            Ok(_) => None,
            Err(e) => Some(Err(e)),
        })
        .collect::<Result<Vec<_>, _>>()
        .map_err(|err| RdError::WalkdirError(path.to_path_buf(), err.to_string()))?;

    let errors: Vec<_> = entries
        .par_iter()
        .filter_map(|entry| set_writable(&entry.path()).err())
        .collect();

    if let Some(err) = errors.into_iter().next() {
        return Err(err);
    }

    Ok(())
}

/// Deletes a directory and all its contents in parallel.
///
/// This function performs a fast, parallel deletion of a directory by:
/// 1. Walking the directory tree to catalog all subdirectories by depth
/// 2. Deleting directories in parallel, starting from the deepest level
/// 3. If deletion fails, attempting to fix permission issues and retrying
///
/// The parallel approach significantly speeds up deletion of large directory trees.
///
/// # Arguments
///
/// * `dpath` - The path to the directory to delete
///
/// # Errors
///
/// Returns an error if:
/// * The directory walk fails
/// * Permissions cannot be fixed
/// * The final deletion attempt fails
///
/// # Examples
///
/// ```no_run
/// use std::path::PathBuf;
/// # use rapid_delete::delete_folder;
///
/// let path = PathBuf::from("/tmp/test_dir");
/// delete_folder(&path)?;
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub fn delete_folder(dpath: &Path) -> Result<(), RdError> {
    let mut tree: BTreeMap<u64, Vec<PathBuf>> = BTreeMap::new();

    let entries: Vec<DirEntry<((), ())>> = jwalk::WalkDir::new(&dpath)
        .skip_hidden(false)
        .into_iter()
        .par_bridge()
        .filter_map(|i| match i {
            Ok(entry) if entry.path().is_dir() => Some(Ok(entry)),
            Ok(_) => None,
            Err(e) => Some(Err(e)),
        })
        .collect::<Result<Vec<_>, _>>()
        .map_err(|err| RdError::WalkdirError(dpath.to_path_buf(), err.to_string()))?;

    #[cfg(feature = "progressbar")]
    let pb = ProgressBar::new(entries.len() as u64);

    for entry in entries {
        tree.entry(entry.depth as u64)
            .or_insert_with(Vec::new)
            .push(entry.path());
    }

    let pool = ThreadPool::default();

    let mut handles = vec![];

    for (_, entries) in tree.into_iter().rev() {
        #[cfg(feature = "progressbar")]
        let pb = pb.clone();
        handles.push(pool.evaluate(move || {
            entries.par_iter().for_each(|entry| {
                let _ = std::fs::remove_dir_all(entry);
                #[cfg(feature = "progressbar")]
                pb.inc(1);
            });
        }));
    }

    for handle in handles {
        handle.await_complete();
    }

    if dpath.exists() {
        // Try to fix permisssion issues and delete again
        set_folder_writable(&dpath)?;

        std::fs::remove_dir_all(dpath)
            .map_err(|err| RdError::RemoveError(dpath.to_path_buf(), err))?;
    }

    #[cfg(feature = "progressbar")]
    pb.finish();

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use tempfile::TempDir;

    /// Helper to create a test directory structure
    fn create_test_structure(base: &Path) -> std::io::Result<()> {
        // Create nested directories
        fs::create_dir_all(base.join("dir1/subdir1"))?;
        fs::create_dir_all(base.join("dir1/subdir2"))?;
        fs::create_dir_all(base.join("dir2"))?;

        // Create some files
        fs::write(base.join("file1.txt"), "content1")?;
        fs::write(base.join("dir1/file2.txt"), "content2")?;
        fs::write(base.join("dir1/subdir1/file3.txt"), "content3")?;
        fs::write(base.join("dir2/file4.txt"), "content4")?;

        Ok(())
    }

    /// Helper to make files read-only
    fn make_readonly(path: &Path) -> std::io::Result<()> {
        let mut perms = fs::metadata(path)?.permissions();
        perms.set_readonly(true);
        fs::set_permissions(path, perms)?;
        Ok(())
    }

    #[test]
    fn test_delete_empty_directory() {
        let temp_dir = TempDir::new().unwrap();
        let test_path = temp_dir.path().join("empty_dir");
        fs::create_dir(&test_path).unwrap();

        assert!(test_path.exists());
        delete_folder(&test_path).unwrap();
        assert!(!test_path.exists());
    }

    #[test]
    fn test_delete_directory_with_files() {
        let temp_dir = TempDir::new().unwrap();
        let test_path = temp_dir.path().join("dir_with_files");
        fs::create_dir(&test_path).unwrap();
        fs::write(test_path.join("file1.txt"), "content").unwrap();
        fs::write(test_path.join("file2.txt"), "content").unwrap();

        assert!(test_path.exists());
        delete_folder(&test_path).unwrap();
        assert!(!test_path.exists());
    }

    #[test]
    fn test_delete_nested_directory_structure() {
        let temp_dir = TempDir::new().unwrap();
        let test_path = temp_dir.path().join("nested");
        create_test_structure(&test_path).unwrap();

        assert!(test_path.exists());
        assert!(test_path.join("dir1/subdir1/file3.txt").exists());

        delete_folder(&test_path).unwrap();

        assert!(!test_path.exists());
        assert!(!test_path.join("dir1").exists());
    }

    #[test]
    fn test_delete_directory_with_readonly_files() {
        let temp_dir = TempDir::new().unwrap();
        let test_path = temp_dir.path().join("readonly_test");
        create_test_structure(&test_path).unwrap();

        // Make some files read-only
        make_readonly(&test_path.join("file1.txt")).unwrap();
        make_readonly(&test_path.join("dir1/file2.txt")).unwrap();

        assert!(test_path.exists());
        delete_folder(&test_path).unwrap();
        assert!(!test_path.exists());
    }

    #[test]
    fn test_delete_nonexistent_directory() {
        let temp_dir = TempDir::new().unwrap();
        let test_path = temp_dir.path().join("does_not_exist");

        // Should handle gracefully - directory doesn't exist
        let result = delete_folder(&test_path);

        // This might succeed (nothing to delete) or fail with WalkdirError
        // depending on jwalk's behavior
        match result {
            Ok(_) => assert!(!test_path.exists()),
            Err(RdError::WalkdirError(_, _)) => {}
            Err(e) => panic!("Unexpected error: {:?}", e),
        }
    }

    #[test]
    fn test_delete_directory_with_symlinks() {
        let temp_dir = TempDir::new().unwrap();

        // Create a directory outside the target
        let external_dir = temp_dir.path().join("external");
        fs::create_dir(&external_dir).unwrap();
        fs::write(external_dir.join("important.txt"), "don't delete me").unwrap();

        // Create target directory with symlink
        let test_path = temp_dir.path().join("with_symlink");
        fs::create_dir(&test_path).unwrap();

        #[cfg(unix)]
        {
            use std::os::unix::fs::symlink;
            symlink(&external_dir, test_path.join("link_to_external")).unwrap();
        }

        #[cfg(windows)]
        {
            use std::os::windows::fs::symlink_dir;
            symlink_dir(&external_dir, test_path.join("link_to_external")).unwrap();
        }

        // Delete target directory
        delete_folder(&test_path).unwrap();

        // Target should be gone
        assert!(!test_path.exists());

        // External directory should still exist (wasn't followed)
        assert!(external_dir.exists());
        assert!(external_dir.join("important.txt").exists());
    }

    #[test]
    fn test_set_writable_on_readonly_file() {
        let temp_dir = TempDir::new().unwrap();
        let file_path = temp_dir.path().join("readonly_file.txt");
        fs::write(&file_path, "content").unwrap();

        // Make it read-only
        make_readonly(&file_path).unwrap();
        let perms = fs::metadata(&file_path).unwrap().permissions();
        assert!(perms.readonly());

        // Make it writable using our function
        set_writable(&file_path).unwrap();

        let perms = fs::metadata(&file_path).unwrap().permissions();
        assert!(!perms.readonly());
    }

    #[test]
    fn test_delete_large_directory_structure() {
        let temp_dir = TempDir::new().unwrap();
        let test_path = temp_dir.path().join("large_structure");
        fs::create_dir(&test_path).unwrap();

        // Create many nested directories and files
        for i in 0..10 {
            let dir = test_path.join(format!("dir_{}", i));
            fs::create_dir(&dir).unwrap();

            for j in 0..5 {
                fs::write(dir.join(format!("file_{}.txt", j)), "content").unwrap();
            }

            // Create a subdirectory
            let subdir = dir.join("subdir");
            fs::create_dir(&subdir).unwrap();
            for k in 0..3 {
                fs::write(subdir.join(format!("subfile_{}.txt", k)), "content").unwrap();
            }
        }

        assert!(test_path.exists());
        delete_folder(&test_path).unwrap();
        assert!(!test_path.exists());
    }

    #[test]
    fn test_error_on_invalid_path() {
        // Test with a path that can't be walked (e.g., a file instead of directory)
        let temp_dir = TempDir::new().unwrap();
        let file_path = temp_dir.path().join("not_a_dir.txt");
        fs::write(&file_path, "content").unwrap();

        let result = delete_folder(&file_path);

        // Should succeed (remove_dir_all works on files too) or error gracefully
        // Behavior depends on the implementation
        match result {
            Ok(_) => assert!(!file_path.exists()),
            Err(_) => {} // Acceptable to error on non-directory
        }
    }
}