File: parallel.go

package info (click to toggle)
gdu 5.34.1-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 1,288 kB
  • sloc: makefile: 145
file content (62 lines) | stat: -rw-r--r-- 1,143 bytes parent folder | download | duplicates (4)
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
package remove

import (
	"os"
	"runtime"
	"sync"

	"github.com/dundee/gdu/v5/pkg/fs"
)

var concurrencyLimit = make(chan struct{}, 3*runtime.GOMAXPROCS(0))

// ItemFromDirParallel removes item from dir
func ItemFromDirParallel(dir, item fs.Item) error {
	if !item.IsDir() {
		return ItemFromDir(dir, item)
	}
	errChan := make(chan error, 1) // we show only first error
	var wait sync.WaitGroup

	// remove all files in the directory in parallel
	for file := range item.GetFilesLocked(fs.SortBySize, fs.SortDesc) {
		if !file.IsDir() {
			continue
		}

		wait.Add(1)
		go func(itemPath string) {
			concurrencyLimit <- struct{}{}
			defer func() { <-concurrencyLimit }()

			err := os.RemoveAll(itemPath)
			if err != nil {
				select {
				// write error to channel if it's empty
				case errChan <- err:
				default:
				}
			}
			wait.Done()
		}(file.GetPath())
	}

	wait.Wait()

	// check if there was an error
	select {
	case err := <-errChan:
		return err
	default:
	}

	// remove the directory itself
	err := os.RemoveAll(item.GetPath())
	if err != nil {
		return err
	}

	// update parent directory
	dir.RemoveFile(item)
	return nil
}