fork/gdu

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

Daniel Mildefeat: allow scanning multiple directories (#653)34f3996

master
2.3 KiB67 linesraw
1package analyze
2
3import (
4	"github.com/dundee/gdu/v5/pkg/fs"
5)
6
7// VirtualRootName is the display name of the synthetic directory that groups
8// several independently scanned roots.
9//
10// It is deliberately not a valid absolute path. Every consumer that resolves a
11// path back to the filesystem (rescan, delete, spawn shell, change cwd) keys off
12// the item's path, so a name that cannot be mistaken for a real directory keeps
13// those operations from ever targeting the virtual root itself.
14const VirtualRootName = "(multiple)"
15
16// CreateVirtualRootDir groups several independently scanned roots under one
17// synthetic parent directory, so that scanning N directories can be presented
18// through the same single-rooted tree the rest of gdu expects.
19//
20// The roots keep their own BasePath, so Dir.GetPath still reports their real
21// absolute path even though they now have a parent. The virtual root has
22// neither a parent nor a BasePath, which is what IsVirtualRootDir detects and
23// what makes GetPath fall back to VirtualRootName.
24//
25// Stats are not aggregated here; call UpdateStats on the returned dir once the
26// roots have been scanned.
27func CreateVirtualRootDir(roots ...fs.Item) *Dir {
28	dir := &Dir{
29		File: &File{
30			Name: VirtualRootName,
31			Flag: getDirFlag(nil, len(roots)),
32		},
33		ItemCount: 1,
34		Files:     make(fs.Files, 0, len(roots)),
35	}
36
37	for _, root := range roots {
38		root.SetParent(dir)
39		dir.AddFile(root)
40	}
41
42	return dir
43}
44
45// ItemDisplayName returns the label to show for item when it is listed directly
46// under parent.
47//
48// Scanned roots grouped under the virtual top level dir are labelled with their
49// absolute path rather than their base name: base names collide as soon as two
50// roots come from different parent directories, and the absolute path is what
51// the user asked for on the command line.
52func ItemDisplayName(parent, item fs.Item) string {
53	if IsVirtualRootDir(parent) {
54		return item.GetPath()
55	}
56	return item.GetName()
57}
58
59// IsVirtualRootDir reports whether item is the synthetic dir created by
60// CreateVirtualRootDir, i.e. a node with no counterpart on the filesystem.
61func IsVirtualRootDir(item fs.Item) bool {
62	dir, ok := item.(*Dir)
63	if !ok || dir.File == nil {
64		return false
65	}
66	return dir.Parent == nil && dir.BasePath == "" && dir.Name == VirtualRootName
67}