fork/gdu

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

Daniel Mildefeat: add --trash-command option (#652)b279b41

master
4.2 KiB127 linesraw
1//go:build !windows
2
3package remove
4
5import (
6	"bytes"
7	"fmt"
8	"io"
9	"os"
10	"os/exec"
11	"path/filepath"
12	"regexp"
13	"strings"
14
15	log "github.com/sirupsen/logrus"
16
17	"github.com/dundee/gdu/v5/pkg/fs"
18)
19
20const (
21	// shellBin is the shell used to evaluate the trash command. A POSIX shell is
22	// used deliberately instead of $SHELL, because the command is assembled with
23	// "$@" and not every interactive shell handles it the same way.
24	shellBin = "/bin/sh"
25
26	// trashPathEnvVar holds the absolute path of the item handed to the command.
27	trashPathEnvVar = "GDU_TRASH_PATH"
28
29	// maxStderrLen caps how much of the command output ends up in the error
30	// message, so a chatty command cannot flood the error modal.
31	maxStderrLen = 1024
32)
33
34// itemPathPlaceholder matches the shell parameters expanding to the item path.
35// A command using any of them decides itself where the path goes, so gdu does
36// not append it.
37var itemPathPlaceholder = regexp.MustCompile(`\$(?:[1@*]|\{1\})`)
38
39type trashCommandOSOps struct {
40	abs     func(string) (string, error)
41	lstat   func(string) (os.FileInfo, error)
42	environ func() []string
43	run     func(argv0 string, argv, envv []string, stderr io.Writer) error
44}
45
46var trashCommandOS = trashCommandOSOps{
47	abs:     filepath.Abs,
48	lstat:   os.Lstat,
49	environ: os.Environ,
50	run:     runTrashCommand,
51}
52
53// TrashCommand returns a remove function which hands the item over to an
54// external command instead of moving it into the built-in XDG trash.
55//
56// The command is evaluated by a POSIX shell with the absolute path of the item
57// passed as a positional parameter, so shell features such as variable
58// expansion work while item names can never be interpreted as shell syntax.
59// The path is appended to the command unless the command refers to it itself
60// via $1, $@ or $*, which commands taking their destination last need. The
61// GDU_TRASH_PATH environment variable is set to the same absolute path.
62//
63// The item is removed from the in-memory tree only once the command succeeded
64// and the path is really gone; a command which leaves the item in place (an
65// interactive command answered with "no", for example) is not an error and
66// leaves the tree untouched.
67func TrashCommand(command string) func(dir, item fs.Item) error {
68	return func(dir, item fs.Item) error {
69		absPath, err := trashCommandOS.abs(item.GetPath())
70		if err != nil {
71			return err
72		}
73
74		var stderr bytes.Buffer
75		argv := []string{"-c", shellScript(command), "gdu", absPath}
76		envv := append(trashCommandOS.environ(), trashPathEnvVar+"="+absPath)
77
78		if err := trashCommandOS.run(shellBin, argv, envv, &stderr); err != nil {
79			return commandError(command, err, stderr.String())
80		}
81
82		if _, err := trashCommandOS.lstat(absPath); err == nil {
83			// The command reported success but the item is still there. Keep the
84			// tree in sync with the filesystem and leave the item listed.
85			return nil
86		}
87
88		dir.RemoveFile(item)
89		return nil
90	}
91}
92
93// shellScript turns the configured command into the script handed to the
94// shell. The item path is always available as $1; it is appended to the command
95// only when the command does not place it somewhere itself.
96func shellScript(command string) string {
97	if itemPathPlaceholder.MatchString(command) {
98		return command
99	}
100	return command + ` "$@"`
101}
102
103// runTrashCommand runs the trash command without attaching the terminal. The
104// command must not be interactive, because gdu keeps rendering the UI (and may
105// even run the command from a background worker) while it executes.
106func runTrashCommand(argv0 string, argv, envv []string, stderr io.Writer) error {
107	log.Printf("Running trash command: %s %v", argv0, argv)
108
109	cmd := exec.Command(argv0, argv...) //nolint:gosec // Running a user supplied command is the point.
110	cmd.Env = envv
111	cmd.Stdout = io.Discard
112	cmd.Stderr = stderr
113	return cmd.Run()
114}
115
116// commandError describes a failed trash command, including whatever the command
117// wrote to its standard error output.
118func commandError(command string, err error, stderr string) error {
119	msg := strings.TrimSpace(stderr)
120	if len(msg) > maxStderrLen {
121		msg = msg[:maxStderrLen] + "..."
122	}
123	if msg == "" {
124		return fmt.Errorf("running trash command %q: %w", command, err)
125	}
126	return fmt.Errorf("running trash command %q: %w: %s", command, err, msg)
127}