aboutsummaryrefslogtreecommitdiff
path: root/internal/admin/undo.go
blob: 0c5ebaaebe6b28abd86a97ec64f12c21af3b06a5 (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
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
package admin

import (
	"encoding/json"
	"fmt"
	"log"
	"os"
	"path/filepath"
	"sync"
	"time"
)

type ExtraFile struct {
	FilePath   string `json:"file_path"`
	OldContent []byte `json:"-"`
	NewContent []byte `json:"-"`
}

type ChangeDesc struct {
	Time        string      `json:"time"`
	Description string      `json:"description"`
	FilePath    string      `json:"file_path"`
	NewFilePath string      `json:"new_file_path,omitempty"`
	OldContent  []byte      `json:"old_content"`
	NewContent  []byte      `json:"new_content"`
	IsDelete    bool        `json:"is_delete"`
	IsCreate    bool        `json:"is_create"`
	ExtraFiles  []ExtraFile `json:"extra_files,omitempty"`
}

func (c ChangeDesc) ShortDesc() string {
	switch {
	case c.IsCreate:
		return fmt.Sprintf("Created %s", filepath.Base(c.FilePath))
	case c.IsDelete:
		return fmt.Sprintf("Deleted %s", filepath.Base(c.FilePath))
	case c.NewFilePath != "":
		return fmt.Sprintf("Moved %s", filepath.Base(c.NewFilePath))
	default:
		return fmt.Sprintf("Edited %s", filepath.Base(c.FilePath))
	}
}

type UndoInfo struct {
	CanUndo   bool   `json:"can_undo"`
	CanRedo   bool   `json:"can_redo"`
	UndoDesc  string `json:"undo_desc"`
	RedoDesc  string `json:"redo_desc"`
	StackSize int    `json:"stack_size"`
	RedoSize  int    `json:"redo_size"`
}

type UndoStack struct {
	mu       sync.Mutex
	dataDir  string
	history  []ChangeDesc
	redo     []ChangeDesc
	maxSize  int
	filePath string
}

func NewUndoStack(dataDir string) *UndoStack {
	us := &UndoStack{
		dataDir:  dataDir,
		maxSize:  100,
		filePath: filepath.Join(dataDir, ".admin_history.json"),
	}
	us.load()
	us.redo = nil
	return us
}

func (us *UndoStack) Push(desc ChangeDesc) {
	us.mu.Lock()
	defer us.mu.Unlock()
	desc.Time = time.Now().Format(time.RFC3339)
	us.history = append(us.history, desc)
	us.redo = nil
	if len(us.history) > us.maxSize {
		us.history = us.history[len(us.history)-us.maxSize:]
	}
	us.save()
	log.Printf("undo: push  %s", desc.ShortDesc())
}

func (us *UndoStack) Undo() *ChangeDesc {
	us.mu.Lock()
	defer us.mu.Unlock()
	if len(us.history) == 0 {
		return nil
	}
	last := us.history[len(us.history)-1]

	if err := us.applyUndo(last); err != nil {
		log.Printf("undo: failed %s: %v", last.ShortDesc(), err)
		return nil
	}

	us.history = us.history[:len(us.history)-1]
	us.redo = append(us.redo, last)
	us.save()
	log.Printf("undo: undid %s", last.ShortDesc())
	return &last
}

func (us *UndoStack) Redo() *ChangeDesc {
	us.mu.Lock()
	defer us.mu.Unlock()
	if len(us.redo) == 0 {
		return nil
	}
	last := us.redo[len(us.redo)-1]

	if err := us.applyRedo(last); err != nil {
		log.Printf("redo: failed %s: %v", last.ShortDesc(), err)
		return nil
	}

	us.redo = us.redo[:len(us.redo)-1]
	us.history = append(us.history, last)
	us.save()
	log.Printf("redo: redid %s", last.ShortDesc())
	return &last
}

func (us *UndoStack) applyUndo(c ChangeDesc) error {
	if c.NewFilePath != "" {
		os.Remove(c.NewFilePath)
	}
	if c.IsDelete {
		if c.OldContent == nil {
			os.MkdirAll(c.FilePath, 0755)
		} else {
			os.MkdirAll(filepath.Dir(c.FilePath), 0755)
			if err := os.WriteFile(c.FilePath, c.OldContent, 0644); err != nil {
				return fmt.Errorf("restore deleted %s: %w", c.FilePath, err)
			}
		}
		for _, ef := range c.ExtraFiles {
			os.MkdirAll(filepath.Dir(ef.FilePath), 0755)
			os.WriteFile(ef.FilePath, ef.OldContent, 0644)
		}
	} else if c.IsCreate {
		os.Remove(c.FilePath)
		for _, ef := range c.ExtraFiles {
			os.MkdirAll(filepath.Dir(ef.FilePath), 0755)
			os.WriteFile(ef.FilePath, ef.OldContent, 0644)
		}
	} else {
		target := c.FilePath
		content := c.OldContent
		if c.NewFilePath != "" {
			target = c.FilePath
		}
		os.MkdirAll(filepath.Dir(target), 0755)
		if err := os.WriteFile(target, content, 0644); err != nil {
			return fmt.Errorf("revert %s: %w", target, err)
		}
		for _, ef := range c.ExtraFiles {
			os.MkdirAll(filepath.Dir(ef.FilePath), 0755)
			os.WriteFile(ef.FilePath, ef.OldContent, 0644)
		}
	}
	return nil
}

func (us *UndoStack) applyRedo(c ChangeDesc) error {
	if c.NewFilePath != "" {
		os.Remove(c.FilePath)
	}
	if c.IsCreate {
		target := c.FilePath
		if c.NewFilePath != "" {
			target = c.NewFilePath
		}
		os.MkdirAll(filepath.Dir(target), 0755)
		if err := os.WriteFile(target, c.NewContent, 0644); err != nil {
			return fmt.Errorf("recreate %s: %w", target, err)
		}
		for _, ef := range c.ExtraFiles {
			os.MkdirAll(filepath.Dir(ef.FilePath), 0755)
			os.WriteFile(ef.FilePath, ef.NewContent, 0644)
		}
	} else if c.IsDelete {
		os.Remove(c.FilePath)
		for _, ef := range c.ExtraFiles {
			os.MkdirAll(filepath.Dir(ef.FilePath), 0755)
			os.WriteFile(ef.FilePath, ef.NewContent, 0644)
		}
	} else {
		target := c.FilePath
		content := c.NewContent
		if c.NewFilePath != "" {
			target = c.NewFilePath
		}
		os.MkdirAll(filepath.Dir(target), 0755)
		if err := os.WriteFile(target, content, 0644); err != nil {
			return fmt.Errorf("reapply %s: %w", target, err)
		}
		for _, ef := range c.ExtraFiles {
			os.MkdirAll(filepath.Dir(ef.FilePath), 0755)
			os.WriteFile(ef.FilePath, ef.NewContent, 0644)
		}
	}
	return nil
}

func (us *UndoStack) Info() UndoInfo {
	us.mu.Lock()
	defer us.mu.Unlock()
	info := UndoInfo{
		StackSize: len(us.history),
		RedoSize:  len(us.redo),
	}
	if len(us.history) > 0 {
		info.CanUndo = true
		info.UndoDesc = us.history[len(us.history)-1].ShortDesc()
	}
	if len(us.redo) > 0 {
		info.CanRedo = true
		info.RedoDesc = us.redo[len(us.redo)-1].ShortDesc()
	}
	return info
}

func (us *UndoStack) save() {
	type extraEntry struct {
		FilePath   string `json:"file_path"`
		OldContent string `json:"old_content"`
		NewContent string `json:"new_content"`
	}
	type entry struct {
		Time        string       `json:"time"`
		Description string       `json:"description"`
		FilePath    string       `json:"file_path"`
		NewFilePath string       `json:"new_file_path,omitempty"`
		OldContent  string       `json:"old_content"`
		NewContent  string       `json:"new_content"`
		IsDelete    bool         `json:"is_delete"`
		IsCreate    bool         `json:"is_create"`
		ExtraFiles  []extraEntry `json:"extra_files,omitempty"`
	}
	type saveData struct {
		History []entry `json:"history"`
		Redo    []entry `json:"redo"`
	}
	toEntries := func(changes []ChangeDesc) []entry {
		var entries []entry
		for _, c := range changes {
			var extra []extraEntry
			for _, ef := range c.ExtraFiles {
				extra = append(extra, extraEntry{
					FilePath:   ef.FilePath,
					OldContent: string(ef.OldContent),
					NewContent: string(ef.NewContent),
				})
			}
			entries = append(entries, entry{
				Time:        c.Time,
				Description: c.Description,
				FilePath:    c.FilePath,
				NewFilePath: c.NewFilePath,
				OldContent:  string(c.OldContent),
				NewContent:  string(c.NewContent),
				IsDelete:    c.IsDelete,
				IsCreate:    c.IsCreate,
				ExtraFiles:  extra,
			})
		}
		return entries
	}
	data := saveData{
		History: toEntries(us.history),
		Redo:    toEntries(us.redo),
	}
	b, err := json.Marshal(data)
	if err != nil {
		log.Printf("undo: failed to marshal history: %v", err)
		return
	}
	if err := os.WriteFile(us.filePath, b, 0644); err != nil {
		log.Printf("undo: failed to write history file: %v", err)
	}
}

func (us *UndoStack) load() {
	data, err := os.ReadFile(us.filePath)
	if err != nil {
		return
	}
	log.Printf("undo: loaded history from %s", us.filePath)
	type extraEntry struct {
		FilePath   string `json:"file_path"`
		OldContent string `json:"old_content"`
		NewContent string `json:"new_content"`
	}
	type entry struct {
		Time        string       `json:"time"`
		Description string       `json:"description"`
		FilePath    string       `json:"file_path"`
		NewFilePath string       `json:"new_file_path,omitempty"`
		OldContent  string       `json:"old_content"`
		NewContent  string       `json:"new_content"`
		IsDelete    bool         `json:"is_delete"`
		IsCreate    bool         `json:"is_create"`
		ExtraFiles  []extraEntry `json:"extra_files,omitempty"`
	}
	var saveData struct {
		History []entry `json:"history"`
		Redo    []entry `json:"redo"`
	}
	if err := json.Unmarshal(data, &saveData); err != nil {
		log.Printf("undo: failed to unmarshal history: %v", err)
		return
	}
	fromEntries := func(entries []entry) []ChangeDesc {
		var changes []ChangeDesc
		for _, e := range entries {
			var extra []ExtraFile
			for _, ef := range e.ExtraFiles {
				extra = append(extra, ExtraFile{
					FilePath:   ef.FilePath,
					OldContent: []byte(ef.OldContent),
					NewContent: []byte(ef.NewContent),
				})
			}
			changes = append(changes, ChangeDesc{
				Time:        e.Time,
				Description: e.Description,
				FilePath:    e.FilePath,
				NewFilePath: e.NewFilePath,
				OldContent:  []byte(e.OldContent),
				NewContent:  []byte(e.NewContent),
				IsDelete:    e.IsDelete,
				IsCreate:    e.IsCreate,
				ExtraFiles:  extra,
			})
		}
		return changes
	}
	us.history = fromEntries(saveData.History)
	log.Printf("undo: loaded %d history entries", len(us.history))
}

func (us *UndoStack) Clear() {
	us.mu.Lock()
	defer us.mu.Unlock()
	us.history = nil
	us.redo = nil
	os.Remove(us.filePath)
	log.Printf("undo: cleared history")
}