fork/gdu

git clone https://git.julia.blue/fork/gdu

Quet Zalfeat(analyze): add SQLite analyzer and some assorted changes (#484)da638da

ignore
1.1 KiB62 linesraw
1package remove
2
3import (
4	"os"
5	"runtime"
6	"sync"
7
8	"github.com/dundee/gdu/v5/pkg/fs"
9)
10
11var concurrencyLimit = make(chan struct{}, 3*runtime.GOMAXPROCS(0))
12
13// ItemFromDirParallel removes item from dir
14func ItemFromDirParallel(dir, item fs.Item) error {
15	if !item.IsDir() {
16		return ItemFromDir(dir, item)
17	}
18	errChan := make(chan error, 1) // we show only first error
19	var wait sync.WaitGroup
20
21	// remove all files in the directory in parallel
22	for file := range item.GetFilesLocked(fs.SortBySize, fs.SortDesc) {
23		if !file.IsDir() {
24			continue
25		}
26
27		wait.Add(1)
28		go func(itemPath string) {
29			concurrencyLimit <- struct{}{}
30			defer func() { <-concurrencyLimit }()
31
32			err := os.RemoveAll(itemPath)
33			if err != nil {
34				select {
35				// write error to channel if it's empty
36				case errChan <- err:
37				default:
38				}
39			}
40			wait.Done()
41		}(file.GetPath())
42	}
43
44	wait.Wait()
45
46	// check if there was an error
47	select {
48	case err := <-errChan:
49		return err
50	default:
51	}
52
53	// remove the directory itself
54	err := os.RemoveAll(item.GetPath())
55	if err != nil {
56		return err
57	}
58
59	// update parent directory
60	dir.RemoveFile(item)
61	return nil
62}