Repository navigation
Expand file tree
/
Copy pathsystem_files.go
More file actions
385 lines (338 loc) · 10.8 KB
/
Copy pathsystem_files.go
File metadata and controls
385 lines (338 loc) · 10.8 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
378
379
380
381
382
383
384
385
package fest
import "github.com/emad-elsaid/types"
import (
"bytes"
"fmt"
"io/fs"
"log/slog"
"os"
"path/filepath"
"github.com/manifoldco/promptui"
)
var (
systemFilesDirs = []string{"system"}
)
// SystemFilesDir adds a directory to scan for system files to deploy.
// Files in this directory are copied to the system, mirroring the directory structure.
// For example, a file at "system/etc/hosts" will be copied to "/etc/hosts".
//
// The framework tracks changes and can restore original files when uninstalling.
//
// Example:
//
// fest.SystemFilesDir("system") // Default
// fest.SystemFilesDir("custom-system-files") // Additional directory
func SystemFilesDir(dir string) {
// Deduplicate: only add if not already present
for _, existing := range systemFilesDirs {
if existing == dir {
return
}
}
systemFilesDirs = append(systemFilesDirs, dir)
}
// readFileWithSudo attempts to read a file, falling back to sudo if permission is denied
func readFileWithSudo(path string) ([]byte, error) {
content, err := os.ReadFile(path)
if err != nil && os.IsPermission(err) {
output, err := types.Sudo("cat", path).StdoutErr()
return []byte(output), err
}
return content, err
}
// listSystemDirFiles returns all files in the system files directories and their target paths
func listSystemDirFiles() (map[string]string, error) {
files := make(map[string]string) // srcPath -> targetPath
targetToSources := make(map[string][]string) // targetPath -> []srcPath (for collision detection)
for _, systemFilesDir := range systemFilesDirs {
if systemFilesDir == "" {
continue
}
err := filepath.WalkDir(systemFilesDir, func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
if d.IsDir() {
return nil
}
// Get relative path from systemFilesDir
relPath, err := filepath.Rel(systemFilesDir, path)
if err != nil {
return err
}
// Target path is / + relPath
targetPath := "/" + relPath
// Track potential collision
targetToSources[targetPath] = append(targetToSources[targetPath], path)
// Later directories override earlier ones if same target path
files[path] = targetPath
return nil
})
if err != nil {
return files, err
}
}
// Warn about collisions
for target, sources := range targetToSources {
if len(sources) > 1 {
slog.Warn("Multiple source files target same destination (last one wins)",
"target", target, "sources", sources)
}
}
return files, nil
}
type systemFiles struct{}
func (s systemFiles) ResourceName() string { return "system-files" }
func (s systemFiles) Wanted() []string {
dirFiles, err := listSystemDirFiles()
if err != nil {
slog.Warn("Failed to list system files directory", "error", err)
}
wanted := make([]string, 0, len(dirFiles))
for _, targetPath := range dirFiles {
wanted = append(wanted, targetPath)
}
return wanted
}
func (s systemFiles) Match(want, have string) bool { return want == have }
func (s systemFiles) ListInstalled() ([]string, error) {
// Check directory-based files
dirFiles, err := listSystemDirFiles()
if err != nil {
return nil, err
}
installed := make([]string, 0, len(dirFiles))
// Files we deployed whose source was since deleted from the system dirs
// can't be seen by the walk above. Read them back from state so they're
// reported as installed and offered for uninstall, instead of being
// orphaned on the system forever.
if state, stateErr := loadState(); stateErr == nil {
current := make(map[string]struct{}, len(dirFiles))
for _, targetPath := range dirFiles {
current[targetPath] = struct{}{}
}
for targetPath, entry := range state.Files {
if _, ok := current[targetPath]; ok {
continue
}
// Only still ours while our exact content is deployed. If a
// package reinstall or manual edit replaced it, the file belongs
// to something else now and must not be offered for uninstall.
content, readErr := readFileWithSudo(targetPath)
if readErr != nil || hashBytes(content) != entry.InstalledHash {
continue
}
installed = append(installed, targetPath)
}
}
for srcPath, targetPath := range dirFiles {
// Read source file content
srcContent, err := os.ReadFile(srcPath)
if err != nil {
continue
}
// Read target file content
targetContent, err := readFileWithSudo(targetPath)
if err != nil {
continue
}
// Compare contents exactly
if bytes.Equal(srcContent, targetContent) {
installed = append(installed, targetPath)
}
}
return installed, nil
}
func (s systemFiles) ListExplicit() ([]string, error) { return s.ListInstalled() }
func (s systemFiles) Install(ops []string) error {
state, err := loadState()
if err != nil {
slog.Warn("Failed to load state, starting fresh", "error", err)
state = &systemFilesState{Version: 1, Files: make(map[string]fileState)}
}
// Persist tracked state even if a later operation fails, so files already
// deployed in this run stay restorable/uninstallable.
defer func() {
if err := saveState(state); err != nil {
slog.Warn("Failed to save state", "error", err)
}
}()
dirFiles, err := listSystemDirFiles()
if err != nil {
return err
}
targetToSrc := make(map[string]string, len(dirFiles))
for src, dst := range dirFiles {
targetToSrc[dst] = src
}
for _, targetPath := range ops {
srcPath, ok := targetToSrc[targetPath]
if !ok {
return fmt.Errorf("source file not found for target: %s", targetPath)
}
srcInfo, err := os.Stat(srcPath)
if err != nil {
return fmt.Errorf("failed to stat source file %s: %w", srcPath, err)
}
content, err := os.ReadFile(srcPath)
if err != nil {
return fmt.Errorf("failed to read source file %s: %w", srcPath, err)
}
// Track state before modification
entry, tracked := state.Files[targetPath]
if !tracked {
// First time managing this file
entry = fileState{}
if currentContent, readErr := readFileWithSudo(targetPath); readErr == nil {
// File exists - backup it
entry.OriginalExists = true
entry.OriginalHash = hashBytes(currentContent)
if backupPath, backupErr := backupFile(targetPath, currentContent); backupErr == nil {
entry.BackupPath = backupPath
} else {
slog.Warn("Failed to backup", "path", targetPath, "error", backupErr)
}
}
} else {
// Check for external modifications
if currentContent, readErr := readFileWithSudo(targetPath); readErr == nil {
currentHash := hashBytes(currentContent)
if currentHash != entry.InstalledHash && currentHash != entry.OriginalHash {
action := askExternalModification(targetPath)
switch action {
case "skip":
continue
case "backup":
extBackup := targetPath[1:] + ".external.backup"
extPath := filepath.Join(backupsDir(), extBackup)
os.MkdirAll(filepath.Dir(extPath), 0755)
os.WriteFile(extPath, currentContent, 0644)
slog.Info("Backed up external changes", "path", extPath)
}
}
}
}
// Create parent directories
slog.Debug("Copying " + srcPath + " → " + targetPath)
perm := fmt.Sprintf("%o", srcInfo.Mode().Perm())
dir := filepath.Dir(targetPath)
if err := os.MkdirAll(dir, 0755); err != nil {
if !os.IsPermission(err) {
return fmt.Errorf("failed to create parent dir %s: %w", dir, err)
}
if err := types.Sudo("mkdir", "-p", dir).Interactive().Error(); err != nil {
return fmt.Errorf("failed to create parent dir %s: %w", dir, err)
}
}
if err := types.Sudo("install", "-m", perm, srcPath, targetPath).Error(); err != nil {
return fmt.Errorf("failed to install %s: %w", targetPath, err)
}
if installed, readErr := readFileWithSudo(targetPath); readErr == nil {
entry.InstalledHash = hashBytes(installed)
} else {
slog.Warn("Could not verify installed content; recording pre-install hash",
"path", targetPath, "error", readErr)
entry.InstalledHash = hashBytes(content)
}
// Update state
entry.InstalledAt = nowRFC3339()
state.Files[targetPath] = entry
}
return nil
}
func askExternalModification(path string) string {
prompt := promptui.Select{
Label: fmt.Sprintf("File %s was modified externally", path),
Items: []string{"Overwrite", "Skip", "Backup external then overwrite"},
}
idx, _, _ := prompt.Run()
switch idx {
case 1:
return "skip"
case 2:
return "backup"
default:
return "overwrite"
}
}
func (s systemFiles) Uninstall(ops []string) error {
state, err := loadState()
if err != nil {
slog.Warn("Cannot load state - skipping uninstall", "error", err)
return nil
}
toDelete := make([]string, 0, len(ops))
for _, targetPath := range ops {
entry, tracked := state.Files[targetPath]
if !tracked {
slog.Warn("File not tracked, skipping", "path", targetPath)
continue
}
if entry.OriginalExists && entry.BackupPath != "" {
// Restore original
if err := restoreFile(targetPath, entry.BackupPath); err != nil {
slog.Warn("Failed to restore", "path", targetPath, "error", err)
continue
}
slog.Info("Restored original", "path", targetPath)
deleteBackup(entry.BackupPath)
delete(state.Files, targetPath)
} else {
toDelete = append(toDelete, targetPath)
}
}
for _, path := range deleteInBatches(toDelete) {
slog.Info("Deleted", "path", path)
delete(state.Files, path)
}
if err := saveState(state); err != nil {
slog.Warn("Failed to save state", "error", err)
}
return nil
}
// deleteInBatches removes the given paths with rm -f, splitting them into
// batches to stay under the OS argument-length limit (ARG_MAX). Batches that
// fail are logged and skipped; the successfully deleted paths are returned so
// the caller can update its state.
func deleteInBatches(paths []string) []string {
const rmBatch = 100
deleted := make([]string, 0, len(paths))
for i := 0; i < len(paths); i += rmBatch {
end := i + rmBatch
if end > len(paths) {
end = len(paths)
}
batch := paths[i:end]
if err := types.Sudo("rm", append([]string{"-f"}, batch...)...).Error(); err != nil {
slog.Warn("Failed to delete files", "error", err, "count", len(batch))
continue
}
deleted = append(deleted, batch...)
}
return deleted
}
func (s systemFiles) MarkExplicit(ops []string) error { return nil }
func (s systemFiles) Update() error { return nil }
// UninstallPreview returns what would happen for each file to uninstall
func (s systemFiles) UninstallPreview(ops []string) map[string]string {
result := make(map[string]string)
state, err := loadState()
if err != nil {
return result
}
for _, targetPath := range ops {
entry, tracked := state.Files[targetPath]
if !tracked {
result[targetPath] = "not tracked"
} else if entry.OriginalExists && entry.BackupPath != "" {
result[targetPath] = "would restore original"
} else {
result[targetPath] = "would delete"
}
}
return result
}
func (s systemFiles) GetDependencies() (map[string][]string, error) {
return make(map[string][]string), nil
}
func (s systemFiles) SaveAsGo(wanted []string) error { return nil }