fork/gdu

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

Daniel Mildefeat: add web UI (#617)d672bf4

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