aboutsummaryrefslogtreecommitdiff
path: root/internal/admin/yaml_util.go
blob: 2d838ad33c92ba5574dd4d43848796ca4f7af1a0 (plain)
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
package admin

import (
	"bytes"
	"fmt"
	"log"
	"os"
	"path/filepath"
	"strings"

	"gopkg.in/yaml.v3"
)

func readYAMLFile(dataDir, subdir, id string) ([]byte, string, error) {
	path := filepath.Join(dataDir, subdir, id+".yaml")
	data, err := os.ReadFile(path)
	return data, path, err
}

func writeYAMLFile(path string, data any) ([]byte, error) {
	var buf bytes.Buffer
	enc := yaml.NewEncoder(&buf)
	enc.SetIndent(2)
	if err := enc.Encode(data); err != nil {
		return nil, err
	}
	enc.Close()
	content := buf.Bytes()
	if err := os.WriteFile(path, content, 0644); err != nil {
		return nil, err
	}
	return content, nil
}

func findYAMLFileInSubdirs(dataDir, subdir, id string) ([]byte, string, error) {
	base := filepath.Join(dataDir, subdir)
	rootPath := filepath.Join(base, id+".yaml")
	if data, err := os.ReadFile(rootPath); err == nil {
		return data, rootPath, nil
	}
	entries, err := os.ReadDir(base)
	if err != nil {
		return nil, "", err
	}
	for _, e := range entries {
		fullPath := filepath.Join(base, e.Name(), id+".yaml")
		if data, err := os.ReadFile(fullPath); err == nil {
			return data, fullPath, nil
		}
		subPath := filepath.Join(base, e.Name())
		subEntries, err := os.ReadDir(subPath)
		if err != nil {
			continue
		}
		for _, se := range subEntries {
			fullPath := filepath.Join(subPath, se.Name(), id+".yaml")
			if data, err := os.ReadFile(fullPath); err == nil {
				return data, fullPath, nil
			}
		}
	}
	return nil, "", os.ErrNotExist
}

func listYAMLFiles(dataDir, subdir string) ([]string, error) {
	var ids []string
	base := filepath.Join(dataDir, subdir)

	entries, err := os.ReadDir(base)
	if err != nil {
		return nil, err
	}
	for _, e := range entries {
		if !e.IsDir() && filepath.Ext(e.Name()) == ".yaml" {
			ids = append(ids, e.Name()[:len(e.Name())-5])
		}
	}
	for _, e := range entries {
		if e.IsDir() {
			subPath := filepath.Join(base, e.Name())
			subEntries, err := os.ReadDir(subPath)
			if err != nil {
				continue
			}
			for _, se := range subEntries {
				if !se.IsDir() && filepath.Ext(se.Name()) == ".yaml" {
					ids = append(ids, se.Name()[:len(se.Name())-5])
				}
			}
		}
	}
	return ids, nil
}

type YAMLTree struct {
	Root []string            `json:"root"`
	Dirs map[string][]string `json:"dirs"`
}

func listYAMLTree(dataDir, subdir string) (*YAMLTree, error) {
	tree := &YAMLTree{Root: []string{}, Dirs: map[string][]string{}}
	base := filepath.Join(dataDir, subdir)

	entries, err := os.ReadDir(base)
	if err != nil {
		return nil, err
	}
	for _, e := range entries {
		if !e.IsDir() && filepath.Ext(e.Name()) == ".yaml" {
			tree.Root = append(tree.Root, e.Name()[:len(e.Name())-5])
		}
	}
	for _, e := range entries {
		if e.IsDir() {
			subPath := filepath.Join(base, e.Name())
			subEntries, err := os.ReadDir(subPath)
			if err != nil {
				continue
			}
			var ids []string
			for _, se := range subEntries {
				if !se.IsDir() && filepath.Ext(se.Name()) == ".yaml" {
					ids = append(ids, se.Name()[:len(se.Name())-5])
				}
			}
			if len(ids) > 0 {
				tree.Dirs[e.Name()] = ids
			} else {
				tree.Dirs[e.Name()] = []string{}
			}
		}
	}
	return tree, nil
}

func listYAMLFilesDeep(dataDir, subdir string) ([]string, error) {
	var ids []string
	base := filepath.Join(dataDir, subdir)
	err := filepath.WalkDir(base, func(path string, d os.DirEntry, err error) error {
		if err != nil {
			return err
		}
		if !d.IsDir() && filepath.Ext(d.Name()) == ".yaml" {
			rel, _ := filepath.Rel(base, path)
			id := rel[:len(rel)-5]
			ids = append(ids, id)
		}
		return nil
	})
	return ids, err
}

func backupFile(path string) []byte {
	data, err := os.ReadFile(path)
	if err != nil {
		log.Printf("backup: WARNING failed to read %s: %v (undo will not be able to restore this file)", path, err)
		return nil
	}
	return data
}

func snapshotFile(path string) ([]byte, error) {
	return os.ReadFile(path)
}

func findEntityPath(dataDir, subdir, id string) (string, error) {
	_, path, err := readYAMLFile(dataDir, subdir, id)
	if err == nil {
		return path, nil
	}
	_, path, err = findYAMLFileInSubdirs(dataDir, subdir, id)
	return path, err
}

func moveEntityFile(dataDir, subdir, id, targetDir string) (string, string, []byte, error) {
	oldPath, err := findEntityPath(dataDir, subdir, id)
	if err != nil {
		return "", "", nil, fmt.Errorf("entity not found: %s/%s", subdir, id)
	}
	data, err := os.ReadFile(oldPath)
	if err != nil {
		return "", "", nil, fmt.Errorf("read: %w", err)
	}
	var newPath string
	if targetDir == "" {
		newPath = filepath.Join(dataDir, subdir, id+".yaml")
	} else {
		destDir := filepath.Join(dataDir, subdir, targetDir)
		if _, err := os.Stat(destDir); os.IsNotExist(err) {
			return "", "", nil, fmt.Errorf("directory does not exist: %s", targetDir)
		}
		newPath = filepath.Join(destDir, id+".yaml")
	}
	if oldPath == newPath {
		return "", "", nil, fmt.Errorf("already in target directory")
	}
	if _, err := os.Stat(newPath); err == nil {
		return "", "", nil, fmt.Errorf("entity already exists in target directory")
	}
	if err := os.WriteFile(newPath, data, 0644); err != nil {
		return "", "", nil, fmt.Errorf("write: %w", err)
	}
	if err := os.Remove(oldPath); err != nil {
		return "", "", nil, fmt.Errorf("remove old: %w", err)
	}
	return oldPath, newPath, data, nil
}

func createEntityDir(dataDir, subdir, name string) error {
	name = strings.TrimSpace(name)
	if name == "" || strings.ContainsAny(name, "/\\") || name == "." || name == ".." {
		return fmt.Errorf("invalid directory name")
	}
	dirPath := filepath.Join(dataDir, subdir, name)
	if _, err := os.Stat(dirPath); err == nil {
		return fmt.Errorf("directory already exists")
	}
	return os.Mkdir(dirPath, 0755)
}

func renameEntityFile(dataDir, subdir, oldID, newID string) (string, string, []byte, error) {
	oldPath, err := findEntityPath(dataDir, subdir, oldID)
	if err != nil {
		return "", "", nil, fmt.Errorf("entity not found: %s/%s", subdir, oldID)
	}
	dir := filepath.Dir(oldPath)
	newPath := filepath.Join(dir, newID+".yaml")
	if oldPath == newPath {
		return "", "", nil, fmt.Errorf("new name is same as current")
	}
	if _, err := os.Stat(newPath); err == nil {
		return "", "", nil, fmt.Errorf("entity %s already exists", newID)
	}
	data, err := os.ReadFile(oldPath)
	if err != nil {
		return "", "", nil, fmt.Errorf("read: %w", err)
	}
	if err := os.WriteFile(newPath, data, 0644); err != nil {
		return "", "", nil, fmt.Errorf("write: %w", err)
	}
	if err := os.Remove(oldPath); err != nil {
		return "", "", nil, fmt.Errorf("remove old: %w", err)
	}
	return oldPath, newPath, data, nil
}

func renameEntityDir(dataDir, subdir, oldName, newName string) error {
	oldName = strings.TrimSpace(oldName)
	newName = strings.TrimSpace(newName)
	if oldName == "" || newName == "" || strings.ContainsAny(oldName, "/\\") || oldName == "." || oldName == ".." {
		return fmt.Errorf("invalid old directory name")
	}
	if strings.ContainsAny(newName, "/\\") || newName == "." || newName == ".." {
		return fmt.Errorf("invalid new directory name")
	}
	oldPath := filepath.Join(dataDir, subdir, oldName)
	if _, err := os.Stat(oldPath); os.IsNotExist(err) {
		return fmt.Errorf("directory %s does not exist", oldName)
	}
	newPath := filepath.Join(dataDir, subdir, newName)
	if _, err := os.Stat(newPath); err == nil {
		return fmt.Errorf("directory %s already exists", newName)
	}
	return os.Rename(oldPath, newPath)
}

func deleteEntityDir(dataDir, subdir, dir string) ([]ChangeDesc, error) {
	dir = strings.TrimSpace(dir)
	if dir == "" || strings.ContainsAny(dir, "/\\") || dir == "." || dir == ".." {
		return nil, fmt.Errorf("invalid directory")
	}
	srcDir := filepath.Join(dataDir, subdir, dir)
	entries, err := os.ReadDir(srcDir)
	if err != nil {
		return nil, fmt.Errorf("directory not found: %s", dir)
	}

	rootDir := filepath.Join(dataDir, subdir)
	var clashes []string
	for _, e := range entries {
		if e.IsDir() || filepath.Ext(e.Name()) != ".yaml" {
			continue
		}
		if _, err := os.Stat(filepath.Join(rootDir, e.Name())); err == nil {
			clashes = append(clashes, e.Name())
		}
	}
	if len(clashes) > 0 {
		return nil, fmt.Errorf("files already exist in root: %s", strings.Join(clashes, ", "))
	}

	var changes []ChangeDesc
	for _, e := range entries {
		if e.IsDir() || filepath.Ext(e.Name()) != ".yaml" {
			continue
		}
		oldPath := filepath.Join(srcDir, e.Name())
		newPath := filepath.Join(rootDir, e.Name())
		data, err := os.ReadFile(oldPath)
		if err != nil {
			return nil, fmt.Errorf("read %s: %w", e.Name(), err)
		}
		if err := os.WriteFile(newPath, data, 0644); err != nil {
			return nil, fmt.Errorf("write %s: %w", e.Name(), err)
		}
		if err := os.Remove(oldPath); err != nil {
			return nil, fmt.Errorf("remove %s: %w", e.Name(), err)
		}
		changes = append(changes, ChangeDesc{
			Description: fmt.Sprintf("move %s %s to root", subdir, e.Name()),
			FilePath:    oldPath,
			NewFilePath: newPath,
			OldContent:  data,
			NewContent:  data,
		})
	}

	if err := os.Remove(srcDir); err != nil {
		return nil, fmt.Errorf("remove directory: %w", err)
	}
	changes = append(changes, ChangeDesc{
		Description: fmt.Sprintf("delete directory %s/%s", subdir, dir),
		FilePath:    srcDir,
		IsDelete:    true,
	})

	return changes, nil
}