fork/gdu

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

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

master
5.0 KiB188 linesraw
1package webui
2
3import (
4	"errors"
5	"os"
6	"path/filepath"
7	"strings"
8
9	"github.com/dundee/gdu/v5/pkg/analyze"
10	"github.com/dundee/gdu/v5/pkg/fs"
11)
12
13// errNotFound is returned when a requested path is not present in the tree.
14var errNotFound = errors.New("node not found")
15
16// errOutsideRoot is returned when a requested path escapes the scanned root.
17var errOutsideRoot = errors.New("path is outside the scanned root")
18
19// nodeJSON is the wire representation of a single tree item. Sizes are raw
20// byte counts; the browser is responsible for human-readable formatting.
21type nodeJSON struct {
22	Name      string `json:"name"`
23	Path      string `json:"path"`
24	IsDir     bool   `json:"isDir"`
25	Size      int64  `json:"size"`
26	Usage     int64  `json:"usage"`
27	ItemCount int64  `json:"itemCount"`
28	Mtime     int64  `json:"mtime"`
29	Flag      string `json:"flag,omitempty"`
30}
31
32// nodeResponse is the payload of GET /api/v1/nodes: the node itself, its
33// breadcrumb ancestry, and only its immediate children.
34type nodeResponse struct {
35	Node        nodeJSON   `json:"node"`
36	Breadcrumbs []nodeJSON `json:"breadcrumbs"`
37	Children    []nodeJSON `json:"children"`
38}
39
40func toNodeJSON(it fs.Item) nodeJSON {
41	flag := ""
42	if f := it.GetFlag(); f != ' ' && f != 0 {
43		flag = string(f)
44	}
45	return nodeJSON{
46		// scanned roots are labelled with their absolute path, since their base
47		// names collide when the roots come from different parent directories
48		Name:      analyze.ItemDisplayName(it.GetParent(), it),
49		Path:      it.GetPath(),
50		IsDir:     it.IsDir(),
51		Size:      it.GetSize(),
52		Usage:     it.GetUsage(),
53		ItemCount: fs.DisplayedItemCount(it),
54		Mtime:     it.GetMtime().Unix(),
55		Flag:      flag,
56	}
57}
58
59// findNode locates an item by absolute path, descending from the scanned root.
60// It guards against path traversal outside the root.
61func (ui *UI) findNode(path string) (fs.Item, error) {
62	ui.mu.RLock()
63	root := ui.topDir
64	rootPath := ui.topDirPath
65	ui.mu.RUnlock()
66
67	if root == nil {
68		return nil, errNotFound
69	}
70	if rootPath == "" {
71		rootPath = root.GetPath()
72	}
73
74	cleanRoot := filepath.Clean(rootPath)
75	if path == "" {
76		return root, nil
77	}
78	cleanPath := filepath.Clean(path)
79	if cleanPath == cleanRoot {
80		return root, nil
81	}
82
83	// The virtual top level dir has no path of its own, so paths are resolved
84	// against each of the scanned roots it holds instead.
85	if analyze.IsVirtualRootDir(root) {
86		for child := range root.GetFiles(fs.SortByName, fs.SortAsc) {
87			if node, err := descendFrom(child, child.GetPath(), cleanPath); err == nil {
88				return node, nil
89			}
90		}
91		return nil, errOutsideRoot
92	}
93
94	return descendFrom(root, cleanRoot, cleanPath)
95}
96
97// descendFrom walks from root, which lives at cleanRoot, down to cleanPath.
98// It guards against path traversal outside the root.
99func descendFrom(root fs.Item, cleanRoot, cleanPath string) (fs.Item, error) {
100	if cleanPath == cleanRoot {
101		return root, nil
102	}
103
104	rel, err := filepath.Rel(cleanRoot, cleanPath)
105	if err != nil {
106		return nil, errOutsideRoot
107	}
108	if rel == ".." || strings.HasPrefix(rel, ".."+string(os.PathSeparator)) {
109		return nil, errOutsideRoot
110	}
111
112	current := root
113	for _, segment := range strings.Split(rel, string(os.PathSeparator)) {
114		if segment == "" || segment == "." {
115			continue
116		}
117		next, found := childByName(current, segment)
118		if !found {
119			return nil, errNotFound
120		}
121		current = next
122	}
123	return current, nil
124}
125
126func childByName(parent fs.Item, name string) (fs.Item, bool) {
127	if !parent.IsDir() {
128		return nil, false
129	}
130	for child := range parent.GetFilesLocked(fs.SortByName, fs.SortAsc) {
131		if child.GetName() == name {
132			return child, true
133		}
134	}
135	return nil, false
136}
137
138// buildNodeResponse assembles a node, its breadcrumbs, and immediate children,
139// sorted as requested.
140func buildNodeResponse(it fs.Item, sortBy fs.SortBy, order fs.SortOrder) nodeResponse {
141	resp := nodeResponse{
142		Node:        toNodeJSON(it),
143		Breadcrumbs: breadcrumbs(it),
144		Children:    []nodeJSON{},
145	}
146	if it.IsDir() {
147		for child := range it.GetFilesLocked(sortBy, order) {
148			resp.Children = append(resp.Children, toNodeJSON(child))
149		}
150	}
151	return resp
152}
153
154// breadcrumbs walks parents from the item up to the root and returns them
155// root-first.
156func breadcrumbs(it fs.Item) []nodeJSON {
157	var chain []nodeJSON
158	for cur := it; cur != nil; cur = cur.GetParent() {
159		chain = append(chain, toNodeJSON(cur))
160	}
161	// reverse so the root comes first
162	for i, j := 0, len(chain)-1; i < j; i, j = i+1, j-1 {
163		chain[i], chain[j] = chain[j], chain[i]
164	}
165	return chain
166}
167
168// parseSort maps query parameters to fs sort enums, defaulting to size
169// descending (largest first), which matches Gdu's usual presentation.
170func parseSort(sortParam, orderParam string) (fs.SortBy, fs.SortOrder) {
171	sortBy := fs.SortBySize
172	switch sortParam {
173	case "name":
174		sortBy = fs.SortByName
175	case "itemCount", "itemcount":
176		sortBy = fs.SortByItemCount
177	case "mtime":
178		sortBy = fs.SortByMtime
179	case "size", "":
180		sortBy = fs.SortBySize
181	}
182
183	order := fs.SortDesc
184	if orderParam == "asc" {
185		order = fs.SortAsc
186	}
187	return sortBy, order
188}