fork/gdu

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

Julia RyanMake -x respect subvolumes4d478cf

subvolume
13.7 KiB657 linesraw
1package stdout
2
3import (
4	"fmt"
5	"io"
6	"math"
7	"os"
8	"path/filepath"
9	"runtime"
10	"sync"
11	"time"
12
13	"github.com/dundee/gdu/v5/internal/common"
14	"github.com/dundee/gdu/v5/pkg/analyze"
15	"github.com/dundee/gdu/v5/pkg/device"
16	"github.com/dundee/gdu/v5/pkg/fs"
17	"github.com/dundee/gdu/v5/report"
18	"github.com/fatih/color"
19)
20
21// UI struct
22type UI struct {
23	output io.Writer
24	*common.UI
25	red               *color.Color
26	orange            *color.Color
27	blue              *color.Color
28	cyan              *color.Color
29	showItemCnt       bool
30	showSymlinkTarget bool
31	top               int
32	depth             int
33	summarize         bool
34	noPrefix          bool
35	fixedBase         float64
36	fixedSuffix       string
37	reverseSort       bool
38}
39
40var (
41	progressRunes      = []rune(`⠇⠏⠋⠙⠹⠸⠼⠴⠦⠧`)
42	progressRunesOld   = []rune(`-\\|/`)
43	progressRunesCount = len(progressRunes)
44)
45
46// CreateStdoutUI creates UI for stdout
47func CreateStdoutUI(
48	output io.Writer,
49	useColors bool,
50	showProgress bool,
51	showApparentSize bool,
52	showRelativeSize bool,
53	summarize bool,
54	useSIPrefix bool,
55	noPrefix bool,
56	fixedUnit string,
57	top int,
58	reverseSort bool,
59	depth int,
60) *UI {
61	ui := &UI{
62		UI: &common.UI{
63			UseColors:        useColors,
64			ShowProgress:     showProgress,
65			ShowApparentSize: showApparentSize,
66			ShowRelativeSize: showRelativeSize,
67			Analyzer:         analyze.CreateTopDirAnalyzer(),
68			UseSIPrefix:      useSIPrefix,
69		},
70		output:      output,
71		summarize:   summarize,
72		noPrefix:    noPrefix,
73		top:         top,
74		reverseSort: reverseSort,
75		depth:       depth,
76	}
77	if fixedUnit != "" {
78		ui.SetFixedUnit(fixedUnit)
79	} else if !noPrefix && !useSIPrefix {
80		ui.SetBlockSizeFromEnvironment()
81	}
82	ui.red = color.New(color.FgRed).Add(color.Bold)
83	ui.orange = color.New(color.FgYellow).Add(color.Bold)
84	ui.blue = color.New(color.FgBlue).Add(color.Bold)
85	ui.cyan = color.New(color.FgCyan).Add(color.Bold)
86
87	if ui.top > 0 || ui.depth > 0 {
88		ui.Analyzer = analyze.CreateAnalyzer()
89	}
90
91	if !useColors {
92		color.NoColor = true
93	}
94
95	return ui
96}
97func (ui *UI) SetFixedUnit(unitChar string) {
98	k, m, g := common.Ki, common.Mi, common.Gi
99	suffixMap := map[string]string{"k": " KiB", "m": " MiB", "g": " GiB"}
100
101	if ui.UseSIPrefix {
102		k, m, g = common.K, common.M, common.G
103		suffixMap = map[string]string{"k": " kB", "m": " MB", "g": " GB"}
104	}
105
106	switch unitChar {
107	case "k":
108		ui.fixedBase = k
109		ui.fixedSuffix = suffixMap["k"]
110	case "m":
111		ui.fixedBase = m
112		ui.fixedSuffix = suffixMap["m"]
113	case "g":
114		ui.fixedBase = g
115		ui.fixedSuffix = suffixMap["g"]
116	}
117}
118
119func (ui *UI) SetShowItemCount() {
120	ui.showItemCnt = true
121}
122
123// SetShowSymlinkTarget enables displaying the symlink target (name -> target).
124func (ui *UI) SetShowSymlinkTarget(value bool) {
125	ui.showSymlinkTarget = value
126}
127
128func (ui *UI) UseOldProgressRunes() {
129	progressRunes = progressRunesOld
130	progressRunesCount = len(progressRunes)
131}
132
133// StartUILoop stub
134func (ui *UI) StartUILoop() error {
135	return nil
136}
137
138// SetCollapsePath sets the flag to collapse paths
139func (ui *UI) SetCollapsePath(value bool) {
140}
141
142// ListDevices lists mounted devices and shows their disk usage
143func (ui *UI) ListDevices(getter device.DevicesInfoGetter) error {
144	devices, err := getter.GetDevicesInfo()
145	if err != nil {
146		return err
147	}
148
149	maxDeviceNameLength := maxInt(maxLength(
150		devices,
151		func(device *device.Device) string { return device.Name },
152	), len("Devices"))
153
154	var sizeLength, percentLength int
155	if ui.UseColors {
156		sizeLength = 20
157		percentLength = 16
158	} else {
159		sizeLength = 9
160		percentLength = 5
161	}
162
163	lineFormat := fmt.Sprintf(
164		"%%%ds %%%ds %%%ds %%%ds %%%ds %%s\n",
165		maxDeviceNameLength,
166		sizeLength,
167		sizeLength,
168		sizeLength,
169		percentLength,
170	)
171
172	fmt.Fprintf(
173		ui.output,
174		fmt.Sprintf("%%%ds %%9s %%9s %%9s %%5s %%s\n", maxDeviceNameLength),
175		"Device",
176		"Size",
177		"Used",
178		"Free",
179		"Used%",
180		"Mount point",
181	)
182
183	for _, device := range devices {
184		usedPercent := math.Round(float64(device.Size-device.Free) / float64(device.Size) * 100)
185
186		fmt.Fprintf(
187			ui.output,
188			lineFormat,
189			device.Name,
190			ui.formatSize(device.Size),
191			ui.formatSize(device.Size-device.Free),
192			ui.formatSize(device.Free),
193			ui.red.Sprintf("%.f%%", usedPercent),
194			device.MountPoint)
195	}
196
197	return nil
198}
199
200// AnalyzePath analyzes recursively disk usage in given path
201func (ui *UI) AnalyzePath(path string, _ fs.Item) error {
202	// When path is a regular file, create a File item directly so that
203	// apparent-size (GetSize) and disk-usage (GetUsage) are both correct.
204	// Running a file through AnalyzeDir + UpdateStats would report the
205	// default 4096-byte directory overhead instead of the real values.
206	info, err := os.Stat(path)
207	if err == nil && info.Mode().IsRegular() {
208		file := analyze.CreateFileItem(filepath.Base(path), info)
209		ui.printTotalItem(file)
210		return nil
211	}
212
213	var (
214		dir             fs.Item
215		wait            sync.WaitGroup
216		updateStatsDone chan struct{}
217	)
218	updateStatsDone = make(chan struct{}, 1)
219
220	if ui.ShowProgress {
221		wait.Add(1)
222		go func() {
223			defer wait.Done()
224			ui.updateProgress(updateStatsDone)
225		}()
226	}
227
228	wait.Add(1)
229	go func() {
230		defer wait.Done()
231		dir = ui.Analyzer.AnalyzeDir(path, ui.ShouldIgnore, ui.CreateFileTypeFilter())
232		if ui.IsFilteringFiles() {
233			dir.UpdateStatsWithFileFiltering(make(fs.HardLinkedItems, 10))
234		} else {
235			dir.UpdateStats(make(fs.HardLinkedItems, 10))
236		}
237		updateStatsDone <- struct{}{}
238	}()
239
240	wait.Wait()
241
242	switch {
243	case ui.top > 0:
244		ui.printTopFiles(dir)
245	case ui.depth > 0:
246		ui.printDirWithDepth(dir, 0)
247	case ui.summarize:
248		ui.printTotalItem(dir)
249	default:
250		ui.showDir(dir)
251	}
252
253	return nil
254}
255
256// ReadFromStorage reads analysis data from persistent key-value storage
257func (ui *UI) ReadFromStorage(storagePath, path string) error {
258	storage := analyze.NewStorage(storagePath, path)
259	closeFn := storage.Open()
260	defer closeFn()
261
262	dir, err := storage.GetDirForPath(path)
263	if err != nil {
264		return err
265	}
266
267	switch {
268	case ui.top > 0:
269		ui.printTopFiles(dir)
270	case ui.summarize:
271		ui.printTotalItem(dir)
272	default:
273		ui.showDir(dir)
274	}
275	return nil
276}
277
278func (ui *UI) showDir(dir fs.Item) {
279	sortOrder := fs.SortDesc
280	if ui.reverseSort {
281		sortOrder = fs.SortAsc
282	}
283
284	sort := fs.SortBySize
285	if ui.ShowApparentSize {
286		sort = fs.SortByApparentSize
287	}
288
289	for file := range dir.GetFiles(sort, sortOrder) {
290		ui.printItem(file)
291	}
292}
293
294func (ui *UI) printTopFiles(file fs.Item) {
295	collected := analyze.CollectTopFiles(file, ui.top)
296	for _, file := range collected {
297		ui.printItemPath(file)
298	}
299}
300
301func (ui *UI) printTotalItem(file fs.Item) {
302	var lineFormat string
303	if ui.UseColors {
304		lineFormat = "%20s %s\n"
305	} else {
306		lineFormat = "%9s %s\n"
307	}
308
309	var size int64
310	if ui.ShowApparentSize {
311		size = file.GetSize()
312	} else {
313		size = file.GetUsage()
314	}
315
316	fmt.Fprintf(
317		ui.output,
318		lineFormat,
319		ui.formatSize(size),
320		file.GetName(),
321	)
322}
323
324func (ui *UI) printItem(file fs.Item) {
325	var lineFormat string
326	if ui.showItemCnt {
327		if ui.UseColors {
328			lineFormat = "%s %23s %25s %s\n"
329		} else {
330			lineFormat = "%s %9s %11s %s\n"
331		}
332	} else {
333		if ui.UseColors {
334			lineFormat = "%s %23s %s\n"
335		} else {
336			lineFormat = "%s %9s %s\n"
337		}
338	}
339
340	var size int64
341	if ui.ShowApparentSize {
342		size = file.GetSize()
343	} else {
344		size = file.GetUsage()
345	}
346
347	name := file.GetName()
348	if file.IsDir() {
349		name = ui.blue.Sprint("/" + file.GetName())
350	}
351
352	// Append symlink target with cyan name (like ls --color)
353	if ui.showSymlinkTarget {
354		if si, ok := file.(fs.SymlinkItem); ok {
355			if target := si.GetSymlinkTarget(); target != "" {
356				name = ui.cyan.Sprint(file.GetName()) + " -> " + target
357			}
358		}
359	}
360
361	if ui.showItemCnt {
362		fmt.Fprintf(
363			ui.output,
364			lineFormat,
365			string(file.GetFlag()),
366			ui.formatSize(size),
367			ui.formatCount(file.GetItemCount()),
368			name,
369		)
370		return
371	}
372
373	fmt.Fprintf(
374		ui.output,
375		lineFormat,
376		string(file.GetFlag()),
377		ui.formatSize(size),
378		name,
379	)
380}
381
382func (ui *UI) printItemPath(file fs.Item) {
383	var lineFormat string
384	if ui.UseColors {
385		lineFormat = "%20s %s\n"
386	} else {
387		lineFormat = "%9s %s\n"
388	}
389
390	var size int64
391	if ui.ShowApparentSize {
392		size = file.GetSize()
393	} else {
394		size = file.GetUsage()
395	}
396
397	if file.IsDir() {
398		fmt.Fprintf(ui.output,
399			lineFormat,
400			ui.formatSize(size),
401			ui.blue.Sprint(file.GetPath()))
402	} else {
403		fmt.Fprintf(ui.output,
404			lineFormat,
405			ui.formatSize(size),
406			file.GetPath())
407	}
408}
409
410func (ui *UI) printDirWithDepth(dir fs.Item, currentDepth int) {
411	// Print current directory
412	ui.printItemPath(dir)
413
414	// If we haven't reached the max depth, print contents
415	if currentDepth < ui.depth && dir.IsDir() {
416		sortOrder := fs.SortDesc
417		if ui.reverseSort {
418			sortOrder = fs.SortAsc
419		}
420
421		files := dir.GetFiles(fs.SortBySize, sortOrder)
422
423		// Print all files at this depth level
424		for file := range files {
425			if file.IsDir() {
426				// Recurse into subdirectories
427				ui.printDirWithDepth(file, currentDepth+1)
428			} else {
429				// Print regular files
430				ui.printItemPath(file)
431			}
432		}
433	}
434}
435
436// ReadAnalysis reads analysis report from JSON file
437func (ui *UI) ReadAnalysis(input io.Reader) error {
438	var (
439		dir      fs.Item
440		wait     sync.WaitGroup
441		err      error
442		doneChan chan struct{}
443	)
444
445	if ui.ShowProgress {
446		wait.Add(1)
447		doneChan = make(chan struct{})
448		go func() {
449			defer wait.Done()
450			ui.showReadingProgress(doneChan)
451		}()
452	}
453
454	wait.Add(1)
455	go func() {
456		defer wait.Done()
457		dir, err = report.ReadAnalysis(input)
458		if err != nil {
459			if ui.ShowProgress {
460				doneChan <- struct{}{}
461			}
462			return
463		}
464		runtime.GC()
465
466		if ui.IsFilteringFiles() {
467			dir.UpdateStatsWithFileFiltering(make(fs.HardLinkedItems, 10))
468		} else {
469			dir.UpdateStats(make(fs.HardLinkedItems, 10))
470		}
471
472		if ui.ShowProgress {
473			doneChan <- struct{}{}
474		}
475	}()
476
477	wait.Wait()
478
479	if err != nil {
480		return err
481	}
482
483	if ui.summarize {
484		ui.printTotalItem(dir)
485	} else {
486		ui.showDir(dir)
487	}
488
489	return nil
490}
491
492func (ui *UI) showReadingProgress(doneChan chan struct{}) {
493	emptyRow := "\r"
494	for j := 0; j < 40; j++ {
495		emptyRow += " "
496	}
497
498	i := 0
499	for {
500		fmt.Fprint(ui.output, emptyRow)
501
502		select {
503		case <-doneChan:
504			fmt.Fprint(ui.output, "\r")
505			return
506		default:
507		}
508
509		fmt.Fprintf(ui.output, "\r %s ", string(progressRunes[i]))
510		fmt.Fprint(ui.output, "Reading analysis from file...")
511
512		time.Sleep(100 * time.Millisecond)
513		i++
514		i %= progressRunesCount
515	}
516}
517
518func (ui *UI) updateProgress(updateStatsDone <-chan struct{}) {
519	emptyRow := "\r"
520	for j := 0; j < 100; j++ {
521		emptyRow += " "
522	}
523
524	analysisDoneChan := ui.Analyzer.GetDone()
525	ticker := time.NewTicker(100 * time.Millisecond)
526	defer ticker.Stop()
527
528	i := 0
529	for {
530		select {
531		case <-ticker.C:
532			progress := ui.Analyzer.GetProgress()
533			fmt.Fprint(ui.output, emptyRow)
534			fmt.Fprintf(ui.output, "\r %s ", string(progressRunes[i]))
535			fmt.Fprint(ui.output, "Scanning... Total items: "+
536				ui.red.Sprint(common.FormatNumber(int64(progress.ItemCount)))+
537				" size: "+
538				ui.formatSize(progress.TotalUsage))
539			i++
540			i %= progressRunesCount
541		case <-analysisDoneChan:
542			ticker.Stop()
543			fmt.Fprint(ui.output, emptyRow)
544			for {
545				fmt.Fprint(ui.output, emptyRow)
546				fmt.Fprintf(ui.output, "\r %s ", string(progressRunes[i]))
547				fmt.Fprint(ui.output, "Calculating disk usage...")
548				time.Sleep(100 * time.Millisecond)
549				i++
550				i %= progressRunesCount
551
552				select {
553				case <-updateStatsDone:
554					fmt.Fprint(ui.output, emptyRow)
555					fmt.Fprint(ui.output, "\r")
556					return
557				default:
558				}
559			}
560		}
561	}
562}
563
564func (ui *UI) formatCount(count int64) string {
565	count64 := float64(count)
566
567	switch {
568	case count64 >= common.G:
569		return ui.red.Sprintf("%.1f", float64(count)/float64(common.G)) + "G"
570	case count64 >= common.M:
571		return ui.red.Sprintf("%.1f", float64(count)/float64(common.M)) + "M"
572	case count64 >= common.K:
573		return ui.red.Sprintf("%.1f", float64(count)/float64(common.K)) + "k"
574	default:
575		return ui.red.Sprintf("%d", count)
576	}
577}
578
579func (ui *UI) formatSize(size int64) string {
580	if ui.noPrefix {
581		return ui.orange.Sprintf("%d", size)
582	}
583	if formatted, ok := ui.FormatBlockSize(size); ok {
584		return ui.orange.Sprint(formatted)
585	}
586	if ui.fixedBase > 0 {
587		val := float64(size) / ui.fixedBase
588		return ui.orange.Sprintf("%.1f", val) + ui.fixedSuffix
589	}
590	if ui.UseSIPrefix {
591		return ui.formatWithDecPrefix(size)
592	}
593	return ui.formatWithBinPrefix(size)
594}
595
596func (ui *UI) formatWithBinPrefix(size int64) string {
597	fsize := float64(size)
598	asize := math.Abs(fsize)
599
600	switch {
601	case asize >= common.Ei:
602		return ui.orange.Sprintf("%.1f", fsize/common.Ei) + " EiB"
603	case asize >= common.Pi:
604		return ui.orange.Sprintf("%.1f", fsize/common.Pi) + " PiB"
605	case asize >= common.Ti:
606		return ui.orange.Sprintf("%.1f", fsize/common.Ti) + " TiB"
607	case asize >= common.Gi:
608		return ui.orange.Sprintf("%.1f", fsize/common.Gi) + " GiB"
609	case asize >= common.Mi:
610		return ui.orange.Sprintf("%.1f", fsize/common.Mi) + " MiB"
611	case asize >= common.Ki:
612		return ui.orange.Sprintf("%.1f", fsize/common.Ki) + " KiB"
613	default:
614		return ui.orange.Sprintf("%d", size) + " B"
615	}
616}
617
618func (ui *UI) formatWithDecPrefix(size int64) string {
619	fsize := float64(size)
620	asize := math.Abs(fsize)
621
622	switch {
623	case asize >= common.E:
624		return ui.orange.Sprintf("%.1f", fsize/common.E) + " EB"
625	case asize >= common.P:
626		return ui.orange.Sprintf("%.1f", fsize/common.P) + " PB"
627	case asize >= common.T:
628		return ui.orange.Sprintf("%.1f", fsize/common.T) + " TB"
629	case asize >= common.G:
630		return ui.orange.Sprintf("%.1f", fsize/common.G) + " GB"
631	case asize >= common.M:
632		return ui.orange.Sprintf("%.1f", fsize/common.M) + " MB"
633	case asize >= common.K:
634		return ui.orange.Sprintf("%.1f", fsize/common.K) + " kB"
635	default:
636		return ui.orange.Sprintf("%d", size) + " B"
637	}
638}
639
640func maxLength(list []*device.Device, keyGetter func(*device.Device) string) int {
641	maxLen := 0
642	var s string
643	for _, item := range list {
644		s = keyGetter(item)
645		if len(s) > maxLen {
646			maxLen = len(s)
647		}
648	}
649	return maxLen
650}
651
652func maxInt(x, y int) int {
653	if x > y {
654		return x
655	}
656	return y
657}