fork/gdu

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

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

master
8.9 KiB346 linesraw
1//go:build !windows
2
3package remove
4
5import (
6	"errors"
7	"io"
8	"os"
9	"path/filepath"
10	"strings"
11	"testing"
12
13	"github.com/stretchr/testify/assert"
14	"github.com/stretchr/testify/require"
15
16	"github.com/dundee/gdu/v5/internal/testdir"
17	"github.com/dundee/gdu/v5/pkg/analyze"
18	"github.com/dundee/gdu/v5/pkg/fs"
19)
20
21func mockTrashCommandOS(t *testing.T, configure func(*trashCommandOSOps)) {
22	t.Helper()
23	original := trashCommandOS
24	t.Cleanup(func() { trashCommandOS = original })
25	configure(&trashCommandOS)
26}
27
28// createTestTree builds the in-memory counterpart of the directory created by
29// testdir.CreateTestDir and returns the dir holding file2 together with the file.
30func createTestTree() (*analyze.Dir, *analyze.File) {
31	dir := &analyze.Dir{
32		File: &analyze.File{
33			Name:  "test_dir",
34			Size:  5,
35			Usage: 12,
36		},
37		ItemCount: 3,
38		BasePath:  ".",
39	}
40	subdir := &analyze.Dir{
41		File: &analyze.File{
42			Name:   "nested",
43			Size:   4,
44			Usage:  8,
45			Parent: dir,
46		},
47		ItemCount: 2,
48	}
49	file := &analyze.File{
50		Name:   "file2",
51		Size:   3,
52		Usage:  4,
53		Parent: subdir,
54	}
55	dir.Files = fs.Files{subdir}
56	subdir.Files = fs.Files{file}
57
58	return subdir, file
59}
60
61func TestTrashCommand(t *testing.T) {
62	fin := testdir.CreateTestDir()
63	defer fin()
64
65	subdir, file := createTestTree()
66
67	err := TrashCommand("rm -rf")(subdir, file)
68	require.NoError(t, err)
69
70	_, err = os.Stat("test_dir/nested/file2")
71	assert.True(t, os.IsNotExist(err))
72
73	assert.Equal(t, 0, len(subdir.Files))
74	assert.Equal(t, int64(1), subdir.ItemCount)
75}
76
77func TestTrashCommandOnDir(t *testing.T) {
78	fin := testdir.CreateTestDir()
79	defer fin()
80
81	dir := &analyze.Dir{
82		File: &analyze.File{
83			Name:  "test_dir",
84			Size:  5,
85			Usage: 12,
86		},
87		ItemCount: 3,
88		BasePath:  ".",
89	}
90	subdir := &analyze.Dir{
91		File: &analyze.File{
92			Name:   "nested",
93			Size:   4,
94			Usage:  8,
95			Parent: dir,
96		},
97		ItemCount: 2,
98	}
99	dir.Files = fs.Files{subdir}
100
101	err := TrashCommand("rm -rf")(dir, subdir)
102	require.NoError(t, err)
103
104	_, err = os.Stat("test_dir/nested")
105	assert.True(t, os.IsNotExist(err))
106	assert.Equal(t, 0, len(dir.Files))
107}
108
109func TestShellScript(t *testing.T) {
110	tests := []struct {
111		name    string
112		command string
113		want    string
114	}{
115		{
116			name:    "path appended",
117			command: "trash-put",
118			want:    `trash-put "$@"`,
119		},
120		{
121			name:    "path appended after arguments",
122			command: "trash-put --trash-dir ~/mytrash",
123			want:    `trash-put --trash-dir ~/mytrash "$@"`,
124		},
125		{
126			name:    "env var is not a placeholder",
127			command: "trash-put --trash-dir $HOME/mytrash",
128			want:    `trash-put --trash-dir $HOME/mytrash "$@"`,
129		},
130		{
131			name:    "quoted first parameter",
132			command: `mv -f "$1" ~/mytrash/`,
133			want:    `mv -f "$1" ~/mytrash/`,
134		},
135		{
136			name:    "braced first parameter",
137			command: `mv -f "${1}" ~/mytrash/`,
138			want:    `mv -f "${1}" ~/mytrash/`,
139		},
140		{
141			name:    "all parameters",
142			command: `mv -f "$@" ~/mytrash/`,
143			want:    `mv -f "$@" ~/mytrash/`,
144		},
145		{
146			name:    "all parameters as single word",
147			command: `mv -f "$*" ~/mytrash/`,
148			want:    `mv -f "$*" ~/mytrash/`,
149		},
150	}
151
152	for _, tt := range tests {
153		t.Run(tt.name, func(t *testing.T) {
154			assert.Equal(t, tt.want, shellScript(tt.command))
155		})
156	}
157}
158
159// writeScript creates a shell script with the given body and returns a command
160// running it, so tests can use commands carrying their own arguments.
161func writeScript(t *testing.T, body string) string {
162	t.Helper()
163	path := filepath.Join(t.TempDir(), "script.sh")
164	require.NoError(t, os.WriteFile(path, []byte(body), 0o600))
165	return "/bin/sh " + path
166}
167
168// TestTrashCommandWithArguments checks that the path is appended to a command
169// which already carries arguments of its own.
170func TestTrashCommandWithArguments(t *testing.T) {
171	fin := testdir.CreateTestDir()
172	defer fin()
173
174	target := t.TempDir()
175	subdir, file := createTestTree()
176
177	// $1 is the argument given in the command, $2 the appended item path.
178	command := writeScript(t, `mv -f "$2" "$1"`) + " " + target
179
180	err := TrashCommand(command)(subdir, file)
181	require.NoError(t, err)
182
183	assert.FileExists(t, filepath.Join(target, "file2"))
184	assert.NoFileExists(t, "test_dir/nested/file2")
185	assert.Equal(t, 0, len(subdir.Files))
186}
187
188// TestTrashCommandWithMv covers the mv recipe from the documentation. mv takes
189// its destination last, so the command places the item path itself instead of
190// having it appended. It also checks that the command is evaluated by a shell,
191// so a trash dir given in the config file can use ~.
192func TestTrashCommandWithMv(t *testing.T) {
193	fin := testdir.CreateTestDir()
194	defer fin()
195
196	home := t.TempDir()
197	t.Setenv("HOME", home)
198	require.NoError(t, os.Mkdir(filepath.Join(home, "mytrash"), 0o700))
199
200	subdir, file := createTestTree()
201
202	err := TrashCommand(`mv -f "$1" ~/mytrash/`)(subdir, file)
203	require.NoError(t, err)
204
205	assert.FileExists(t, filepath.Join(home, "mytrash", "file2"))
206	assert.NoFileExists(t, "test_dir/nested/file2")
207	assert.Equal(t, 0, len(subdir.Files))
208}
209
210// TestTrashCommandWithMvToMissingDir makes sure the trailing slash in the
211// documented mv recipe turns a missing trash dir into an error instead of
212// renaming the item onto the destination path.
213func TestTrashCommandWithMvToMissingDir(t *testing.T) {
214	fin := testdir.CreateTestDir()
215	defer fin()
216
217	home := t.TempDir()
218	t.Setenv("HOME", home)
219
220	subdir, file := createTestTree()
221
222	err := TrashCommand(`mv -f "$1" ~/mytrash/`)(subdir, file)
223	require.Error(t, err)
224
225	assert.NoFileExists(t, filepath.Join(home, "mytrash"))
226	assert.FileExists(t, "test_dir/nested/file2")
227	assert.Equal(t, 1, len(subdir.Files))
228}
229
230func TestTrashCommandPassesPathAsArgumentAndEnvVar(t *testing.T) {
231	fin := testdir.CreateTestDir()
232	defer fin()
233
234	out := filepath.Join(t.TempDir(), "args")
235	subdir, file := createTestTree()
236
237	command := writeScript(t, `printf '%s\n' "$#" "$1" "$GDU_TRASH_PATH" > "`+out+`"`)
238
239	err := TrashCommand(command)(subdir, file)
240	require.NoError(t, err)
241
242	wantPath, err := filepath.Abs("test_dir/nested/file2")
243	require.NoError(t, err)
244
245	data, err := os.ReadFile(out)
246	require.NoError(t, err)
247	assert.Equal(t, []string{"1", wantPath, wantPath}, strings.Fields(string(data)))
248}
249
250// TestTrashCommandWithSpecialCharsInName makes sure item names are never
251// interpreted as shell syntax.
252func TestTrashCommandWithSpecialCharsInName(t *testing.T) {
253	base := t.TempDir()
254	name := "; touch pwned; echo 'x'"
255	path := filepath.Join(base, name)
256	require.NoError(t, os.WriteFile(path, []byte("x"), 0o600))
257
258	dir := &analyze.Dir{
259		File:      &analyze.File{Name: filepath.Base(base)},
260		ItemCount: 2,
261		BasePath:  filepath.Dir(base),
262	}
263	file := &analyze.File{Name: name, Size: 1, Usage: 1, Parent: dir}
264	dir.Files = fs.Files{file}
265
266	err := TrashCommand("rm -f")(dir, file)
267	require.NoError(t, err)
268
269	assert.NoFileExists(t, path)
270	assert.NoFileExists(t, filepath.Join(base, "pwned"))
271	assert.NoFileExists(t, "pwned")
272	assert.Equal(t, 0, len(dir.Files))
273}
274
275func TestTrashCommandFailing(t *testing.T) {
276	fin := testdir.CreateTestDir()
277	defer fin()
278
279	subdir, file := createTestTree()
280
281	err := TrashCommand(writeScript(t, "exit 3"))(subdir, file)
282	require.Error(t, err)
283	assert.Contains(t, err.Error(), "running trash command")
284	assert.Contains(t, err.Error(), "exit status 3")
285
286	assert.FileExists(t, "test_dir/nested/file2")
287	assert.Equal(t, 1, len(subdir.Files))
288}
289
290func TestTrashCommandFailingWithStderr(t *testing.T) {
291	fin := testdir.CreateTestDir()
292	defer fin()
293
294	subdir, file := createTestTree()
295
296	err := TrashCommand(writeScript(t, "echo 'trash dir is missing' >&2\nexit 1"))(subdir, file)
297	require.Error(t, err)
298	assert.Contains(t, err.Error(), "trash dir is missing")
299	assert.Equal(t, 1, len(subdir.Files))
300}
301
302// TestTrashCommandLeavingItemInPlace covers a command which succeeds without
303// removing the item, e.g. an interactive command answered with "no".
304func TestTrashCommandLeavingItemInPlace(t *testing.T) {
305	fin := testdir.CreateTestDir()
306	defer fin()
307
308	subdir, file := createTestTree()
309
310	err := TrashCommand("true")(subdir, file)
311	require.NoError(t, err)
312
313	assert.FileExists(t, "test_dir/nested/file2")
314	assert.Equal(t, 1, len(subdir.Files))
315	assert.Equal(t, int64(2), subdir.ItemCount)
316}
317
318func TestTrashCommandAbsError(t *testing.T) {
319	sentinel := errors.New("abs failed")
320	mockTrashCommandOS(t, func(ops *trashCommandOSOps) {
321		ops.abs = func(string) (string, error) { return "", sentinel }
322	})
323
324	subdir, file := createTestTree()
325
326	err := TrashCommand("rm -rf")(subdir, file)
327	require.ErrorIs(t, err, sentinel)
328	assert.Equal(t, 1, len(subdir.Files))
329}
330
331func TestTrashCommandStderrTruncated(t *testing.T) {
332	mockTrashCommandOS(t, func(ops *trashCommandOSOps) {
333		ops.run = func(_ string, _, _ []string, stderr io.Writer) error {
334			_, err := stderr.Write([]byte(strings.Repeat("x", maxStderrLen+10)))
335			require.NoError(t, err)
336			return errors.New("failed")
337		}
338	})
339
340	subdir, file := createTestTree()
341
342	err := TrashCommand("rm -rf")(subdir, file)
343	require.Error(t, err)
344	assert.True(t, strings.HasSuffix(err.Error(), "..."))
345	assert.Less(t, len(err.Error()), maxStderrLen+100)
346}