fork/gdu

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

cosmolifeat: move items to XDG trash with D key (#12) (#608)9ca5c60

subvolume
6.4 KiB254 linesraw
1//go:build !windows && !darwin
2
3package remove
4
5import (
6	"fmt"
7	"io"
8	"os"
9	"path/filepath"
10	"strings"
11	"time"
12
13	"github.com/dundee/gdu/v5/pkg/fs"
14)
15
16type trashInfoFile interface {
17	WriteString(string) (int, error)
18	Close() error
19}
20
21type trashOSOps struct {
22	mkdirAll        func(string, os.FileMode) error
23	abs             func(string) (string, error)
24	userHomeDir     func() (string, error)
25	lstat           func(string) (os.FileInfo, error)
26	openTrashInfo   func(string, int, os.FileMode) (trashInfoFile, error)
27	remove          func(string) error
28	rename          func(string, string) error
29	removeAll       func(string) error
30	mkdir           func(string, os.FileMode) error
31	readDir         func(string) ([]os.DirEntry, error)
32	readlink        func(string) (string, error)
33	symlink         func(string, string) error
34	openSource      func(string) (io.ReadCloser, error)
35	openDestination func(string, int, os.FileMode) (io.WriteCloser, error)
36	copy            func(io.Writer, io.Reader) (int64, error)
37}
38
39var trashOS = trashOSOps{
40	mkdirAll:    os.MkdirAll,
41	abs:         filepath.Abs,
42	userHomeDir: os.UserHomeDir,
43	lstat:       os.Lstat,
44	openTrashInfo: func(name string, flag int, perm os.FileMode) (trashInfoFile, error) {
45		return os.OpenFile(name, flag, perm)
46	},
47	remove:    os.Remove,
48	rename:    renameNoReplace,
49	removeAll: os.RemoveAll,
50	mkdir:     os.Mkdir,
51	readDir:   os.ReadDir,
52	readlink:  os.Readlink,
53	symlink:   os.Symlink,
54	openSource: func(name string) (io.ReadCloser, error) {
55		return os.Open(name)
56	},
57	openDestination: func(name string, flag int, perm os.FileMode) (io.WriteCloser, error) {
58		return os.OpenFile(name, flag, perm)
59	},
60	copy: io.Copy,
61}
62
63// MoveItemToTrash moves item into the XDG trash and updates the in-memory dir tree.
64func MoveItemToTrash(dir, item fs.Item) error {
65	trashRoot, err := trashDir()
66	if err != nil {
67		return err
68	}
69	filesDir := filepath.Join(trashRoot, "files")
70	infoDir := filepath.Join(trashRoot, "info")
71	if err := trashOS.mkdirAll(filesDir, 0o700); err != nil {
72		return err
73	}
74	if err := trashOS.mkdirAll(infoDir, 0o700); err != nil {
75		return err
76	}
77
78	absSrc, err := trashOS.abs(item.GetPath())
79	if err != nil {
80		return err
81	}
82
83	for range 10001 {
84		destName, infoPath, err := reserveTrashInfo(filesDir, infoDir, item.GetName(), absSrc)
85		if err != nil {
86			return err
87		}
88		destPath := filepath.Join(filesDir, destName)
89
90		if err := movePath(absSrc, destPath); err != nil {
91			_ = trashOS.remove(infoPath) //nolint:errcheck // Best-effort rollback.
92			if os.IsExist(err) {
93				// Destination appeared after reservation; pick another name.
94				continue
95			}
96			return err
97		}
98
99		dir.RemoveFile(item)
100		return nil
101	}
102
103	return fmt.Errorf("could not find unique trash name for %s", item.GetName())
104}
105
106func trashDir() (string, error) {
107	if xdg := os.Getenv("XDG_DATA_HOME"); xdg != "" {
108		return filepath.Join(xdg, "Trash"), nil
109	}
110	home, err := trashOS.userHomeDir()
111	if err != nil {
112		return "", err
113	}
114	return filepath.Join(home, ".local", "share", "Trash"), nil
115}
116
117func reserveTrashInfo(filesDir, infoDir, base, absSrc string) (name, infoPath string, err error) {
118	for attempt := 0; attempt <= 10000; attempt++ {
119		candidate := base
120		if attempt > 0 {
121			candidate = fmt.Sprintf("%s.%d", base, attempt+1)
122		}
123
124		destPath := filepath.Join(filesDir, candidate)
125		if _, err := trashOS.lstat(destPath); err == nil {
126			continue
127		} else if !os.IsNotExist(err) {
128			return "", "", err
129		}
130
131		infoPath := filepath.Join(infoDir, candidate+".trashinfo")
132		err := writeTrashInfo(infoPath, absSrc)
133		if os.IsExist(err) {
134			continue
135		}
136		if err != nil {
137			return "", "", err
138		}
139
140		// The exclusive trashinfo file reserves this name among compliant
141		// trash implementations. Recheck files/ to avoid clobbering stale
142		// entries that have no corresponding trashinfo file.
143		if _, err := trashOS.lstat(destPath); os.IsNotExist(err) {
144			return candidate, infoPath, nil
145		} else if err != nil {
146			_ = trashOS.remove(infoPath) //nolint:errcheck // Best-effort rollback.
147			return "", "", err
148		}
149
150		_ = trashOS.remove(infoPath) //nolint:errcheck // Best-effort rollback.
151	}
152
153	return "", "", fmt.Errorf("could not find unique trash name for %s", base)
154}
155
156func writeTrashInfo(infoPath, absSrc string) error {
157	content := fmt.Sprintf("[Trash Info]\nPath=%s\nDeletionDate=%s\n",
158		escapeTrashPath(absSrc),
159		time.Now().Format("2006-01-02T15:04:05"),
160	)
161
162	file, err := trashOS.openTrashInfo(infoPath, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600)
163	if err != nil {
164		return err
165	}
166
167	if _, err := file.WriteString(content); err != nil {
168		_ = file.Close()
169		_ = trashOS.remove(infoPath) //nolint:errcheck // Best-effort rollback.
170		return err
171	}
172	if err := file.Close(); err != nil {
173		_ = trashOS.remove(infoPath) //nolint:errcheck // Best-effort rollback.
174		return err
175	}
176	return nil
177}
178
179func escapeTrashPath(p string) string {
180	var b strings.Builder
181	for _, r := range p {
182		if r == '/' || r == '-' || r == '.' || r == '_' || r == '~' ||
183			(r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z') || (r >= '0' && r <= '9') {
184			b.WriteRune(r)
185		} else {
186			for _, by := range []byte(string(r)) {
187				fmt.Fprintf(&b, "%%%02X", by)
188			}
189		}
190	}
191	return b.String()
192}
193
194func movePath(src, dst string) error {
195	err := trashOS.rename(src, dst)
196	if err == nil {
197		return nil
198	}
199	if os.IsExist(err) || !isEXDEV(err) {
200		return err
201	}
202	if err := copyRecursively(src, dst); err != nil {
203		_ = trashOS.removeAll(dst) //nolint:errcheck // Best-effort rollback.
204		return err
205	}
206	return trashOS.removeAll(src)
207}
208
209func copyRecursively(src, dst string) error {
210	info, err := trashOS.lstat(src)
211	if err != nil {
212		return err
213	}
214	if info.IsDir() {
215		if err := trashOS.mkdir(dst, info.Mode().Perm()); err != nil {
216			return err
217		}
218		entries, err := trashOS.readDir(src)
219		if err != nil {
220			return err
221		}
222		for _, e := range entries {
223			if err := copyRecursively(filepath.Join(src, e.Name()), filepath.Join(dst, e.Name())); err != nil {
224				return err
225			}
226		}
227		return nil
228	}
229	if info.Mode()&os.ModeSymlink != 0 {
230		target, err := trashOS.readlink(src)
231		if err != nil {
232			return err
233		}
234		return trashOS.symlink(target, dst)
235	}
236	if !info.Mode().IsRegular() {
237		return fmt.Errorf("unsupported file type %s: %s", info.Mode().Type(), src)
238	}
239
240	in, err := trashOS.openSource(src)
241	if err != nil {
242		return err
243	}
244	defer in.Close()
245	out, err := trashOS.openDestination(dst, os.O_CREATE|os.O_EXCL|os.O_WRONLY, info.Mode().Perm())
246	if err != nil {
247		return err
248	}
249	if _, err := trashOS.copy(out, in); err != nil {
250		_ = out.Close()
251		return err
252	}
253	return out.Close()
254}