fork/gdu

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

yurenchen000Feat: Show symlink target #260 (#612)1eaa266

ignore
8.2 KiB370 linesraw
1package report
2
3import (
4	"bytes"
5	"errors"
6	"fmt"
7	"io"
8	"math"
9	"os"
10	"strconv"
11	"sync"
12	"time"
13
14	"github.com/dundee/gdu/v5/build"
15	"github.com/dundee/gdu/v5/internal/common"
16	"github.com/dundee/gdu/v5/pkg/analyze"
17	"github.com/dundee/gdu/v5/pkg/device"
18	"github.com/dundee/gdu/v5/pkg/fs"
19	"github.com/fatih/color"
20)
21
22// UI struct
23type UI struct {
24	*common.UI
25	output           io.Writer
26	exportOutput     io.Writer
27	red              *color.Color
28	orange           *color.Color
29	writtenChan      chan struct{}
30	outputAttributes fs.JSONAttributes
31	top              int
32	depth            int
33	summarize        bool
34}
35
36// CreateExportUI creates UI for stdout
37func CreateExportUI(
38	output io.Writer,
39	exportOutput io.Writer,
40	useColors bool,
41	showProgress bool,
42	useSIPrefix bool,
43	top int,
44	depth int,
45	summarize bool,
46	outputAttributes fs.JSONAttributes,
47) *UI {
48	ui := &UI{
49		UI: &common.UI{
50			ShowProgress: showProgress,
51			Analyzer:     analyze.CreateAnalyzer(),
52			UseSIPrefix:  useSIPrefix,
53		},
54		output:           output,
55		exportOutput:     exportOutput,
56		writtenChan:      make(chan struct{}),
57		outputAttributes: outputAttributes,
58		top:              top,
59		depth:            depth,
60		summarize:        summarize,
61	}
62	if !useSIPrefix {
63		ui.SetBlockSizeFromEnvironment()
64	}
65	ui.red = color.New(color.FgRed).Add(color.Bold)
66	ui.orange = color.New(color.FgYellow).Add(color.Bold)
67
68	if !useColors {
69		color.NoColor = true
70	}
71
72	return ui
73}
74
75// StartUILoop stub
76func (ui *UI) StartUILoop() error {
77	return nil
78}
79
80// SetCollapsePath sets the flag to collapse paths
81func (ui *UI) SetCollapsePath(value bool) {
82}
83
84// SetShowSymlinkTarget is a no-op for the export UI (no rendered file list)
85func (ui *UI) SetShowSymlinkTarget(value bool) {
86}
87
88// ListDevices lists mounted devices and shows their disk usage
89func (ui *UI) ListDevices(getter device.DevicesInfoGetter) error {
90	return errors.New("exporting devices list is not supported")
91}
92
93// ReadAnalysis reads analysis report from JSON file
94func (ui *UI) ReadAnalysis(input io.Reader) error {
95	return errors.New("reading analysis is not possible while exporting")
96}
97
98// ReadFromStorage reads analysis data from persistent key-value storage
99func (ui *UI) ReadFromStorage(storagePath, path string) error {
100	storage := analyze.NewStorage(storagePath, path)
101	closeFn := storage.Open()
102	defer closeFn()
103
104	dir, err := storage.GetDirForPath(path)
105	if err != nil {
106		return err
107	}
108
109	var waitWritten sync.WaitGroup
110	if ui.ShowProgress {
111		waitWritten.Add(1)
112		go func() {
113			defer waitWritten.Done()
114			ui.updateProgress()
115		}()
116	}
117
118	return ui.exportDir(dir, &waitWritten)
119}
120
121// AnalyzePath analyzes recursively disk usage in given path
122func (ui *UI) AnalyzePath(path string, _ fs.Item) error {
123	var (
124		dir         fs.Item
125		wait        sync.WaitGroup
126		waitWritten sync.WaitGroup
127	)
128
129	if ui.ShowProgress {
130		waitWritten.Add(1)
131		go func() {
132			defer waitWritten.Done()
133			ui.updateProgress()
134		}()
135	}
136
137	wait.Add(1)
138	go func() {
139		defer wait.Done()
140		dir = ui.Analyzer.AnalyzeDir(path, ui.CreateIgnoreFunc(), ui.CreateFileTypeFilter())
141		if ui.IsFilteringFiles() {
142			dir.UpdateStatsWithFileFiltering(make(fs.HardLinkedItems, 10))
143		} else {
144			dir.UpdateStats(make(fs.HardLinkedItems, 10))
145		}
146	}()
147
148	wait.Wait()
149
150	return ui.exportDir(dir, &waitWritten)
151}
152
153func (ui *UI) topDir(dir fs.Item) fs.Item {
154	files := analyze.CollectTopFiles(dir, ui.top)
155
156	topDir := &analyze.Dir{
157		File: &analyze.File{
158			Name:  dir.GetName(),
159			Mtime: dir.GetMtime(),
160		},
161	}
162	if d, ok := dir.(*analyze.Dir); ok {
163		topDir.BasePath = d.BasePath
164	}
165	for _, f := range files {
166		file := *f.(*analyze.File)
167		file.Parent = topDir
168		topDir.AddFile(&file)
169	}
170	topDir.UpdateStats(make(fs.HardLinkedItems, 10))
171	return topDir
172}
173
174func (ui *UI) limitDirByDepth(dir fs.Item, currentDepth int) fs.Item {
175	if d, ok := dir.(*analyze.Dir); ok {
176		limited := &analyze.Dir{
177			File: &analyze.File{
178				Name:   d.GetName(),
179				Mtime:  d.GetMtime(),
180				Parent: d.GetParent(),
181				Size:   d.GetSize(),
182				Usage:  d.GetUsage(),
183			},
184			BasePath:  d.BasePath,
185			ItemCount: d.ItemCount,
186		}
187		if currentDepth == ui.depth {
188			return limited
189		}
190		for f := range d.GetFiles(fs.SortBySize, fs.SortDesc) {
191			if f.IsDir() {
192				child := ui.limitDirByDepth(f, currentDepth+1)
193				if child != nil {
194					child.SetParent(limited)
195					limited.AddFile(child)
196				}
197			} else if currentDepth+1 <= ui.depth {
198				file := *f.(*analyze.File)
199				file.Parent = limited
200				limited.AddFile(&file)
201			}
202		}
203		return limited
204	}
205
206	return dir
207}
208
209func (ui *UI) summarizeDir(dir fs.Item) fs.Item {
210	summary := &analyze.Dir{
211		File: &analyze.File{
212			Name:  dir.GetName(),
213			Mtime: dir.GetMtime(),
214		},
215	}
216	if d, ok := dir.(*analyze.Dir); ok {
217		summary.BasePath = d.BasePath
218		summary.ItemCount = d.ItemCount
219		summary.Size = d.GetSize()
220		summary.Usage = d.GetUsage()
221	}
222	return summary
223}
224
225func (ui *UI) exportDir(dir fs.Item, waitWritten *sync.WaitGroup) error {
226	// Sorting is now handled by GetFiles with sort parameters
227
228	var (
229		buff bytes.Buffer
230		err  error
231	)
232
233	buff.Write([]byte(`[1,2,{"progname":"gdu","progver":"`))
234	buff.Write([]byte(build.Version))
235	buff.Write([]byte(`","timestamp":`))
236	buff.Write([]byte(strconv.FormatInt(time.Now().Unix(), 10)))
237	buff.Write([]byte("},\n"))
238
239	switch {
240	case ui.summarize:
241		dir = ui.summarizeDir(dir)
242	case ui.top > 0:
243		dir = ui.topDir(dir)
244	case ui.depth > 0:
245		dir = ui.limitDirByDepth(dir, 0)
246	}
247
248	if err := dir.EncodeJSON(&buff, true, ui.outputAttributes); err != nil {
249		return err
250	}
251	if _, err = buff.Write([]byte("]\n")); err != nil {
252		return err
253	}
254	if _, err = buff.WriteTo(ui.exportOutput); err != nil {
255		return err
256	}
257
258	if f, ok := ui.exportOutput.(*os.File); ok {
259		err = f.Close()
260		if err != nil {
261			return err
262		}
263	}
264
265	if ui.ShowProgress {
266		ui.writtenChan <- struct{}{}
267		waitWritten.Wait()
268	}
269
270	return nil
271}
272
273func (ui *UI) updateProgress() {
274	waitingForWrite := false
275
276	emptyRow := "\r"
277	for j := 0; j < 100; j++ {
278		emptyRow += " "
279	}
280
281	progressRunes := []rune(`⠇⠏⠋⠙⠹⠸⠼⠴⠦⠧`)
282
283	doneChan := ui.Analyzer.GetDone()
284
285	i := 0
286	for {
287		fmt.Fprint(ui.output, emptyRow)
288
289		progress := ui.Analyzer.GetProgress()
290
291		select {
292		case <-doneChan:
293			fmt.Fprint(ui.output, "\r")
294			waitingForWrite = true
295		case <-ui.writtenChan:
296			fmt.Fprint(ui.output, "\r")
297			return
298		default:
299		}
300
301		fmt.Fprintf(ui.output, "\r %s ", string(progressRunes[i]))
302
303		if waitingForWrite {
304			fmt.Fprint(ui.output, "Writing output file...")
305		} else {
306			fmt.Fprint(ui.output, "Scanning... Total items: "+
307				ui.red.Sprint(common.FormatNumber(int64(progress.ItemCount)))+
308				" size: "+
309				ui.formatSize(progress.TotalUsage))
310		}
311
312		time.Sleep(100 * time.Millisecond)
313		i++
314		i %= 10
315	}
316}
317
318func (ui *UI) formatSize(size int64) string {
319	if formatted, ok := ui.FormatBlockSize(size); ok {
320		return ui.orange.Sprint(formatted)
321	}
322	if ui.UseSIPrefix {
323		return ui.formatWithDecPrefix(size)
324	}
325	return ui.formatWithBinPrefix(size)
326}
327
328func (ui *UI) formatWithBinPrefix(size int64) string {
329	fsize := float64(size)
330	asize := math.Abs(fsize)
331
332	switch {
333	case asize >= common.Ei:
334		return ui.orange.Sprintf("%.1f", fsize/common.Ei) + " EiB"
335	case asize >= common.Pi:
336		return ui.orange.Sprintf("%.1f", fsize/common.Pi) + " PiB"
337	case asize >= common.Ti:
338		return ui.orange.Sprintf("%.1f", fsize/common.Ti) + " TiB"
339	case asize >= common.Gi:
340		return ui.orange.Sprintf("%.1f", fsize/common.Gi) + " GiB"
341	case asize >= common.Mi:
342		return ui.orange.Sprintf("%.1f", fsize/common.Mi) + " MiB"
343	case asize >= common.Ki:
344		return ui.orange.Sprintf("%.1f", fsize/common.Ki) + " KiB"
345	default:
346		return ui.orange.Sprintf("%d", size) + " B"
347	}
348}
349
350func (ui *UI) formatWithDecPrefix(size int64) string {
351	fsize := float64(size)
352	asize := math.Abs(fsize)
353
354	switch {
355	case asize >= common.E:
356		return ui.orange.Sprintf("%.1f", fsize/common.E) + " EB"
357	case asize >= common.P:
358		return ui.orange.Sprintf("%.1f", fsize/common.P) + " PB"
359	case asize >= common.T:
360		return ui.orange.Sprintf("%.1f", fsize/common.T) + " TB"
361	case asize >= common.G:
362		return ui.orange.Sprintf("%.1f", fsize/common.G) + " GB"
363	case asize >= common.M:
364		return ui.orange.Sprintf("%.1f", fsize/common.M) + " MB"
365	case asize >= common.K:
366		return ui.orange.Sprintf("%.1f", fsize/common.K) + " kB"
367	default:
368		return ui.orange.Sprintf("%d", size) + " B"
369	}
370}