-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathapp.go
More file actions
377 lines (319 loc) · 9.21 KB
/
app.go
File metadata and controls
377 lines (319 loc) · 9.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
package main
import (
"context"
"fmt"
"io"
"os"
"path/filepath"
"sort"
"strings"
"time"
"github.com/wailsapp/wails/v2/pkg/runtime"
)
// App struct
type App struct {
ctx context.Context
}
// FileNode represents a file or directory in the tree
type FileNode struct {
Name string `json:"name"`
Path string `json:"path"`
IsDir bool `json:"isDir"`
Size int64 `json:"size"`
ModTime string `json:"modTime"`
Children []*FileNode `json:"children,omitempty"`
}
// CopyProgress represents the progress of a file copy operation
type CopyProgress struct {
CurrentFile string `json:"currentFile"`
FilesDone int `json:"filesDone"`
TotalFiles int `json:"totalFiles"`
Percentage float64 `json:"percentage"`
}
// NewApp creates a new App application struct
// NewApp 创建一个新的 App 应用程序
func NewApp() *App {
return &App{}
}
// startup is called at application startup
// startup 在应用程序启动时调用
func (a *App) startup(ctx context.Context) {
// Perform your setup here
// 在这里执行初始化设置
a.ctx = ctx
}
// domReady is called after the front-end dom has been loaded
// domReady 在前端Dom加载完毕后调用
func (a *App) domReady(ctx context.Context) {
// Add your action here
// 在这里添加你的操作
}
// beforeClose is called when the application is about to quit,
// either by clicking the window close button or calling runtime.Quit.
// Returning true will cause the application to continue,
// false will continue shutdown as normal.
// beforeClose在单击窗口关闭按钮或调用runtime.Quit即将退出应用程序时被调用.
// 返回 true 将导致应用程序继续,false 将继续正常关闭。
func (a *App) beforeClose(ctx context.Context) (prevent bool) {
return false
}
// shutdown is called at application termination
// 在应用程序终止时被调用
func (a *App) shutdown(ctx context.Context) {
// Perform your teardown here
// 在此处做一些资源释放的操作
}
// GetHomeDir returns the user's home directory
func (a *App) GetHomeDir() (string, error) {
return os.UserHomeDir()
}
// ScanDirectory scans the given path and returns the file tree (non-recursive by default)
func (a *App) ScanDirectory(path string) (*FileNode, error) {
runtime.LogDebugf(a.ctx, "Scanning directory: %s", path)
// Use Lstat to avoid following symlinks automatically
info, err := os.Lstat(path)
if err != nil {
runtime.LogErrorf(a.ctx, "Failed to stat path %s: %v", path, err)
return nil, err
}
root := &FileNode{
Name: info.Name(),
Path: path,
IsDir: info.IsDir(),
Size: info.Size(),
ModTime: info.ModTime().Format(time.RFC3339),
}
// If it's a symlink that points to a directory, treat it as a directory
if info.Mode()&os.ModeSymlink != 0 {
resolvedPath, err := os.Readlink(path)
if err == nil {
resolvedInfo, err := os.Stat(resolvedPath)
if err == nil && resolvedInfo.IsDir() {
root.IsDir = true
}
}
}
if !root.IsDir {
return root, nil
}
entries, err := os.ReadDir(path)
if err != nil {
runtime.LogErrorf(a.ctx, "Failed to read dir %s: %v", path, err)
return nil, fmt.Errorf("failed to read directory %s: %v", path, err)
}
// Sort entries: directories first, then files
sort.Slice(entries, func(i, j int) bool {
if entries[i].IsDir() != entries[j].IsDir() {
return entries[i].IsDir()
}
return entries[i].Name() < entries[j].Name()
})
for _, entry := range entries {
childInfo, err := entry.Info()
if err != nil {
continue
}
childNode := &FileNode{
Name: entry.Name(),
Path: filepath.Join(path, entry.Name()),
IsDir: entry.IsDir(),
Size: childInfo.Size(),
ModTime: childInfo.ModTime().Format(time.RFC3339),
}
// Initialize empty children array for directories so frontend knows it can be expanded
if childNode.IsDir {
childNode.Children = []*FileNode{}
}
root.Children = append(root.Children, childNode)
}
runtime.LogDebugf(a.ctx, "Scan complete for %s. Found %d items.", path, len(root.Children))
return root, nil
}
// SearchFiles searches for files matching the query within the given root path (recursive)
func (a *App) SearchFiles(query string, rootPath string) ([]*FileNode, error) {
runtime.LogDebugf(a.ctx, "Searching for '%s' in %s", query, rootPath)
var results []*FileNode
// Validate root path
rootInfo, err := os.Stat(rootPath)
if err != nil {
return nil, fmt.Errorf("invalid root path: %v", err)
}
if !rootInfo.IsDir() {
return nil, fmt.Errorf("root path is not a directory")
}
// Walk directory tree
err = filepath.WalkDir(rootPath, func(path string, d os.DirEntry, err error) error {
if err != nil {
// Log error but continue walking
runtime.LogErrorf(a.ctx, "Error accessing %s: %v", path, err)
return nil
}
// Skip root directory itself
if path == rootPath {
return nil
}
// Check if name matches query (case-insensitive substring match)
if strings.Contains(strings.ToLower(d.Name()), strings.ToLower(query)) {
info, err := d.Info()
if err != nil {
runtime.LogErrorf(a.ctx, "Failed to get info for %s: %v", path, err)
return nil
}
node := &FileNode{
Name: d.Name(),
Path: path,
IsDir: d.IsDir(),
Size: info.Size(),
ModTime: info.ModTime().Format(time.RFC3339),
}
results = append(results, node)
}
return nil
})
if err != nil {
return nil, fmt.Errorf("search failed: %v", err)
}
runtime.LogDebugf(a.ctx, "Search complete. Found %d matches.", len(results))
return results, nil
}
// CopyFiles copies a list of files to a destination directory
func (a *App) CopyFiles(srcPaths []string, destDir string) error {
destInfo, err := os.Stat(destDir)
if err != nil {
return fmt.Errorf("destination directory does not exist: %v", err)
}
if !destInfo.IsDir() {
return fmt.Errorf("destination is not a directory")
}
// Filter valid files and directories
var itemsToCopy []string
for _, src := range srcPaths {
_, err := os.Stat(src)
if err == nil {
itemsToCopy = append(itemsToCopy, src)
}
}
totalItems := len(itemsToCopy)
if totalItems == 0 {
return fmt.Errorf("no valid items to copy")
}
// Start copy loop
for i, src := range itemsToCopy {
srcBase := filepath.Base(src)
// Emit progress before starting file
progress := CopyProgress{
CurrentFile: srcBase,
FilesDone: i,
TotalFiles: totalItems,
Percentage: float64(i) / float64(totalItems) * 100,
}
runtime.EventsEmit(a.ctx, "copy-progress", progress)
srcInfo, err := os.Stat(src)
if err != nil {
runtime.LogErrorf(a.ctx, "Failed to stat source %s: %v", src, err)
continue
}
destPath := filepath.Join(destDir, srcBase)
if srcInfo.IsDir() {
// Recursive copy
err = copyDir(src, destPath)
if err != nil {
runtime.LogErrorf(a.ctx, "Failed to copy directory %s: %v", src, err)
return fmt.Errorf("failed to copy directory %s: %v", src, err)
}
} else {
// File copy
err = copyFile(src, destPath, srcInfo)
if err != nil {
runtime.LogErrorf(a.ctx, "Failed to copy file %s: %v", src, err)
return fmt.Errorf("failed to copy file %s: %v", src, err)
}
}
// Progress events are handled by frontend, no artificial delay needed
}
// Emit 100% completion
runtime.EventsEmit(a.ctx, "copy-progress", CopyProgress{
CurrentFile: "Complete",
FilesDone: totalItems,
TotalFiles: totalItems,
Percentage: 100,
})
return nil
}
// copyFile copies a single file from src to dst, preserving mod time
// If dst already exists, it will be overwritten
func copyFile(src, dst string, info os.FileInfo) error {
// Check if destination already exists
if _, err := os.Stat(dst); err == nil {
// File exists - remove it first to ensure clean overwrite
if err := os.Remove(dst); err != nil {
return fmt.Errorf("failed to remove existing file %s: %v", dst, err)
}
}
in, err := os.Open(src)
if err != nil {
return err
}
defer in.Close()
out, err := os.Create(dst)
if err != nil {
return err
}
defer out.Close()
_, err = io.Copy(out, in)
if err != nil {
return err
}
// Preserve file permissions from source
if err := os.Chmod(dst, info.Mode()); err != nil {
return fmt.Errorf("failed to set permissions on %s: %v", dst, err)
}
return os.Chtimes(dst, time.Now(), info.ModTime())
}
// copyDir recursively copies a directory tree, attempting to preserve permissions
func copyDir(src string, dst string) error {
src = filepath.Clean(src)
dst = filepath.Clean(dst)
si, err := os.Stat(src)
if err != nil {
return err
}
if !si.IsDir() {
return fmt.Errorf("source is not a directory")
}
_, err = os.Stat(dst)
if os.IsNotExist(err) {
err = os.MkdirAll(dst, si.Mode())
if err != nil {
return err
}
}
entries, err := os.ReadDir(src)
if err != nil {
return err
}
for _, entry := range entries {
srcPath := filepath.Join(src, entry.Name())
dstPath := filepath.Join(dst, entry.Name())
if entry.IsDir() {
err = copyDir(srcPath, dstPath)
if err != nil {
return err
}
} else {
// Skip symlinks for now if not needed, or handle them
if entry.Type()&os.ModeSymlink != 0 {
continue
}
info, err := entry.Info()
if err != nil {
return err
}
err = copyFile(srcPath, dstPath, info)
if err != nil {
return err
}
}
}
return nil
}