fork/gdu

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

Julia RyanDan's preferred ignore behavior04c9958

ignore
11.4 KiB409 linesraw
1package tui
2
3import (
4	"fmt"
5	"strconv"
6	"strings"
7
8	"github.com/gdamore/tcell/v2"
9	"github.com/rivo/tview"
10	log "github.com/sirupsen/logrus"
11
12	"github.com/dundee/gdu/v5/build"
13	"github.com/dundee/gdu/v5/pkg/fs"
14)
15
16var (
17	helpDisabledSuffix = " (disabled)"
18
19	helpText = `     [::b]up/down, k/j    [white:black:-]Move cursor up/down
20  [::b]pgup/pgdn, g/G     [white:black:-]Move cursor top/bottom
21 [::b]enter, right, l     [white:black:-]Go to directory/device
22         [::b]left, h     [white:black:-]Go to parent directory
23
24               [::b]r     [white:black:-]Rescan current directory
25               [::b]E     [white:black:-]Export analysis data to file as JSON
26               [::b]/     [white:black:-]Search items by name
27               [::b]T     [white:black:-]Filter items by file type (extension)
28               [::b]a     [white:black:-]Toggle between showing disk usage and apparent size
29               [::b]B     [white:black:-]Toggle bar alignment to biggest file or directory
30               [::b]c     [white:black:-]Show/hide file count
31               [::b]m     [white:black:-]Show/hide latest mtime
32               [::b]b     [white:black:-]Spawn shell in current directory
33               [::b]q     [white:black:-]Quit gdu (asks to confirm after a long scan)
34               [::b]Q     [white:black:-]Quit gdu and print current directory path
35
36Item under cursor:
37               [::b]d     [white:black:-]Delete file or directory
38               [::b]e     [white:black:-]Empty file or directory
39               [::b]D     [white:black:-]Move file or directory to trash
40			   [::b]space [white:black:-]Mark file or directory for deletion
41			   [::b]p     [white:black:-]Print marked items paths to stdout after quitting
42			   [::b]I     [white:black:-]Ignore file or directory
43               [::b]v     [white:black:-]Show content of file
44               [::b]o     [white:black:-]Open file or directory in external program
45               [::b]i     [white:black:-]Show info about item
46
47Sort by (twice toggles asc/desc):
48               [::b]n     [white:black:-]Sort by name (asc/desc)
49               [::b]s     [white:black:-]Sort by size (asc/desc)
50               [::b]C     [white:black:-]Sort by file count (asc/desc)
51               [::b]M     [white:black:-]Sort by mtime (asc/desc)`
52)
53
54// currentDirLabelText builds the breadcrumb label shown above the table,
55// annotated when a mid-scan preview is being displayed.
56func (ui *UI) currentDirLabelText() string {
57	label := "[::b] --- " +
58		tview.Escape(
59			strings.TrimPrefix(ui.currentDirPath, build.RootPathPrefix),
60		) +
61		" ---"
62	if ui.previewing {
63		label += "  [::b][yellow]scanning… (preview, Tab to resume)[-]"
64	}
65	return label
66}
67
68// nolint: funlen // Why: complex function
69func (ui *UI) showDir() {
70	var (
71		totalUsage int64
72		totalSize  int64
73		maxUsage   int64
74		maxSize    int64
75		itemCount  int64
76	)
77
78	ui.currentDirPath = ui.currentDir.GetPath()
79
80	if ui.changeCwdFn != nil {
81		err := ui.changeCwdFn(ui.currentDirPath)
82		if err != nil {
83			log.Printf("error setting cwd: %s", err.Error())
84		}
85		log.Printf("changing cwd to %s", ui.currentDirPath)
86	}
87
88	ui.currentDirLabel.SetText(ui.currentDirLabelText()).SetDynamicColors(true)
89
90	ui.table.Clear()
91
92	rowIndex := 0
93	if ui.currentDirPath != ui.topDirPath {
94		prefix := "                         "
95		if len(ui.markedRows) > 0 {
96			prefix += "  "
97		}
98
99		cell := tview.NewTableCell(prefix + "[::b]/..")
100
101		// Use the collapsed parent logic to handle navigation back through collapsed paths
102		var collapsedParent fs.Item
103		if ui.collapsePath {
104			collapsedParent = findCollapsedParent(ui.currentDir)
105		} else {
106			collapsedParent = ui.currentDir.GetParent()
107		}
108		cell.SetReference(collapsedParent)
109		cell.SetStyle(tcell.Style{}.Foreground(tcell.ColorDefault))
110		ui.table.SetCell(0, 0, cell)
111		rowIndex++
112	}
113
114	sortBy, sortOrder := ui.getSortParams()
115
116	unlock := ui.currentDir.RLock()
117	defer unlock()
118
119	i := rowIndex
120	maxUsage = 0
121	maxSize = 0
122	for item := range ui.currentDir.GetFiles(sortBy, sortOrder) {
123		if ui.ShowRelativeSize {
124			if item.GetUsage() > maxUsage {
125				maxUsage = item.GetUsage()
126			}
127			if item.GetSize() > maxSize {
128				maxSize = item.GetSize()
129			}
130		} else {
131			maxSize += item.GetSize()
132			maxUsage += item.GetUsage()
133		}
134		i++
135	}
136
137	for item := range ui.currentDir.GetFiles(sortBy, sortOrder) {
138		if ui.filterValue != "" && !strings.Contains(
139			strings.ToLower(item.GetName()),
140			strings.ToLower(ui.filterValue),
141		) {
142			continue
143		}
144
145		if !ui.matchesTypeFilter(item.GetName(), item.IsDir()) {
146			continue
147		}
148
149		totalUsage += item.GetUsage()
150		totalSize += item.GetSize()
151		itemCount += item.GetItemCount()
152
153		_, marked := ui.markedRows[rowIndex]
154
155		var cell *tview.TableCell
156		var reference fs.Item
157
158		// Check if this directory can be collapsed
159		if item.IsDir() {
160			var collapsedPath *CollapsedPath
161			if ui.collapsePath {
162				collapsedPath = findCollapsiblePath(item)
163			}
164
165			if collapsedPath != nil {
166				// Format as collapsed path
167				cell = tview.NewTableCell(ui.formatCollapsedRow(collapsedPath, maxUsage, maxSize, marked))
168				// Reference should point to the deepest directory for navigation
169				reference = collapsedPath.DeepestDir
170			} else {
171				// Regular directory formatting
172				cell = tview.NewTableCell(ui.formatFileRow(item, maxUsage, maxSize, marked))
173				reference = item
174			}
175		} else {
176			// Regular file formatting
177			cell = tview.NewTableCell(ui.formatFileRow(item, maxUsage, maxSize, marked))
178			reference = item
179		}
180
181		cell.SetReference(reference)
182
183		switch {
184		case marked:
185			cell.SetStyle(tcell.Style{}.Foreground(ui.markedTextColor))
186			cell.SetBackgroundColor(ui.markedBackgroundColor)
187		default:
188			cell.SetStyle(tcell.Style{}.Foreground(tcell.ColorDefault))
189		}
190
191		ui.table.SetCell(rowIndex, 0, cell)
192		rowIndex++
193	}
194
195	var footerNumberColor, footerTextColor string
196	if ui.UseColors {
197		footerNumberColor = fmt.Sprintf(
198			"[%s:%s:b]",
199			ui.footerNumberColor,
200			ui.footerBackgroundColor,
201		)
202		footerTextColor = fmt.Sprintf(
203			"[%s:%s:-]",
204			ui.footerTextColor,
205			ui.footerBackgroundColor,
206		)
207	} else {
208		footerNumberColor = "[black:white:b]"
209		footerTextColor = blackOnWhite
210	}
211
212	selected := ""
213	if len(ui.markedRows) > 0 {
214		selected = " Selected items: " + footerNumberColor +
215			strconv.Itoa(len(ui.markedRows)) + footerTextColor
216	}
217
218	timeFilterText := ui.formatTimeFilterInfo()
219
220	typeFilterText := ui.formatTypeFilterInfo(footerNumberColor, footerTextColor)
221
222	ui.footerLabel.SetText(
223		selected + footerTextColor +
224			" Total disk usage: " +
225			footerNumberColor +
226			ui.formatSize(totalUsage, true, false) +
227			" Apparent size: " +
228			footerNumberColor +
229			ui.formatSize(totalSize, true, false) +
230			" Items: " + footerNumberColor + fmt.Sprintf("%d", itemCount) +
231			footerTextColor +
232			" Sorting by: " + ui.sortBy + " " + ui.sortOrder +
233			typeFilterText +
234			timeFilterText)
235
236	ui.table.Select(0, 0)
237	ui.table.ScrollToBeginning()
238
239	if !ui.filtering && !ui.typeFiltering {
240		ui.app.SetFocus(ui.table)
241	}
242}
243
244func (ui *UI) showDevices() {
245	var totalUsage int64
246
247	ui.table.Clear()
248	ui.table.SetCell(0, 0, tview.NewTableCell("Device name").SetSelectable(false))
249	ui.table.SetCell(0, 1, tview.NewTableCell("Size").SetSelectable(false))
250	ui.table.SetCell(0, 2, tview.NewTableCell("Used").SetSelectable(false))
251	ui.table.SetCell(0, 3, tview.NewTableCell("Used part").SetSelectable(false))
252	ui.table.SetCell(0, 4, tview.NewTableCell("Free").SetSelectable(false))
253	ui.table.SetCell(0, 5, tview.NewTableCell("Mount point").SetSelectable(false))
254
255	var textColor, sizeColor string
256	if ui.UseColors {
257		textColor = "[#3498db:-:b]"
258		sizeColor = "[#edb20a:-:b]"
259	} else {
260		textColor = "[white:-:b]"
261		sizeColor = "[white:-:b]"
262	}
263
264	ui.sortDevices()
265
266	for i, device := range ui.devices {
267		totalUsage += device.GetUsage()
268		ui.table.SetCell(i+1, 0, tview.NewTableCell(textColor+device.Name).SetReference(ui.devices[i]))
269		ui.table.SetCell(i+1, 1, tview.NewTableCell(ui.formatSize(device.Size, false, true)))
270		ui.table.SetCell(i+1, 2, tview.NewTableCell(sizeColor+ui.formatSize(device.Size-device.Free, false, true)))
271		ui.table.SetCell(i+1, 3, tview.NewTableCell(getDeviceUsagePart(device, ui.useOldSizeBar)))
272		ui.table.SetCell(i+1, 4, tview.NewTableCell(ui.formatSize(device.Free, false, true)))
273		ui.table.SetCell(i+1, 5, tview.NewTableCell(textColor+device.MountPoint).SetReference(ui.devices[i]))
274	}
275
276	var footerNumberColor, footerTextColor string
277	if ui.UseColors {
278		footerNumberColor = fmt.Sprintf(
279			"[%s:%s:b]",
280			ui.footerNumberColor,
281			ui.footerBackgroundColor,
282		)
283		footerTextColor = fmt.Sprintf(
284			"[%s:%s:-]",
285			ui.footerTextColor,
286			ui.footerBackgroundColor,
287		)
288	} else {
289		footerNumberColor = "[black:white:b]"
290		footerTextColor = blackOnWhite
291	}
292
293	ui.footerLabel.SetText(
294		" Total usage: " +
295			footerNumberColor +
296			ui.formatSize(totalUsage, true, false) +
297			footerTextColor +
298			" Sorting by: " + ui.sortBy + " " + ui.sortOrder)
299
300	ui.table.Select(1, 0)
301	ui.table.SetSelectedFunc(ui.deviceItemSelected)
302
303	if ui.topDirPath != "" {
304		for i, device := range ui.devices {
305			if device.MountPoint == ui.topDirPath {
306				ui.table.Select(i+1, 0)
307				break
308			}
309		}
310	}
311}
312
313func (ui *UI) showErr(msg string, err error) {
314	text := msg
315	if err != nil {
316		text += ": " + err.Error()
317	}
318
319	modal := tview.NewModal().
320		SetText(text).
321		AddButtons([]string{"ok"}).
322		SetDoneFunc(func(buttonIndex int, buttonLabel string) {
323			ui.pages.RemovePage("error")
324		})
325
326	if !ui.UseColors {
327		modal.SetBackgroundColor(tcell.ColorGray)
328	}
329
330	ui.pages.AddPage("error", modal, true, true)
331	ui.app.SetFocus(modal)
332}
333
334func (ui *UI) showErrFromGo(msg string, err error) {
335	ui.app.QueueUpdateDraw(func() {
336		ui.showErr(msg, err)
337	})
338}
339
340func (ui *UI) showHelp() {
341	text := tview.NewTextView().SetDynamicColors(true)
342	text.SetBorder(true).SetBorderPadding(2, 2, 2, 2)
343	text.SetBorderColor(tcell.ColorDefault)
344	text.SetTitle(" gdu help ")
345	text.SetScrollable(true)
346
347	formattedHelpText := ui.formatHelpTextFor()
348	text.SetText(formattedHelpText)
349
350	maxHeight := strings.Count(formattedHelpText, "\n") + 7
351	_, height := ui.screen.Size()
352	if height > maxHeight {
353		height = maxHeight
354	}
355
356	flex := tview.NewFlex().
357		AddItem(nil, 0, 1, false).
358		AddItem(tview.NewFlex().SetDirection(tview.FlexRow).
359			AddItem(nil, 0, 1, false).
360			AddItem(text, height, 1, false).
361			AddItem(nil, 0, 1, false), 80, 1, false).
362		AddItem(nil, 0, 1, false)
363
364	ui.help = flex
365	ui.pages.AddPage("help", flex, true, true)
366	ui.app.SetFocus(text)
367}
368
369func (ui *UI) formatHelpTextFor() string {
370	lines := strings.Split(helpText, "\n")
371
372	for i, line := range lines {
373		if ui.UseColors {
374			lines[i] = strings.ReplaceAll(
375				strings.ReplaceAll(line, defaultColorBold, "[red]"),
376				whiteOnBlack,
377				"[white]",
378			)
379		}
380
381		isFound := (strings.Contains(line, "Empty file or directory") ||
382			strings.Contains(line, "Delete file or directory") ||
383			strings.Contains(line, "Move file or directory to trash"))
384
385		if ui.noDelete && isFound {
386			lines[i] += helpDisabledSuffix
387		} else if ui.noDeleteWithFilter && isFound {
388			lines[i] += " (disabled/filter)"
389		}
390
391		if ui.noSpawnShell && (strings.Contains(line, "Spawn shell in current directory") ||
392			strings.Contains(line, "Open file or directory in external program")) {
393			lines[i] += helpDisabledSuffix
394		}
395
396		if ui.noViewFile && strings.Contains(line, "Show content of file") {
397			lines[i] += helpDisabledSuffix
398		}
399	}
400
401	return strings.Join(lines, "\n")
402}
403
404func (ui *UI) formatTypeFilterInfo(numberColor, textColor string) string {
405	if ui.typeFilterValue == "" {
406		return ""
407	}
408	return " Type filter: " + numberColor + ui.typeFilterValue + textColor
409}