-
Notifications
You must be signed in to change notification settings - Fork 0
/
vim.go
74 lines (62 loc) · 1.81 KB
/
vim.go
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
package edit
import (
"encoding/json"
"fmt"
"os"
"os/exec"
"github.com/lukasschwab/tiir/pkg/text"
)
// TODO: can we support the user's preferred editor without launching an
// arbitrary application?
// Vim based [text.Editor]. Uses a temporary file for every Update call.
const Vim vimEditor = iota
type vimEditor int
// Update implements Editor.
func (v vimEditor) Update(initial *text.Text) (final *text.Text, err error) {
f, err := os.CreateTemp("", "meta.*.json")
if err != nil {
return nil, fmt.Errorf("error creating temp file: %w", err)
}
defer os.Remove(f.Name())
bytes, err := json.MarshalIndent(editable(*initial), "", "\t")
if err != nil {
return nil, fmt.Errorf("error marshaling stored text: %w", err)
} else if err := os.WriteFile(f.Name(), bytes, os.ModeAppend); err != nil {
return nil, fmt.Errorf("error initializing temp file: %w", err)
}
// Run vim.
cmd := exec.Command("vim", f.Name())
cmd.Stdin = os.Stdin
cmd.Stderr = os.Stderr
cmd.Stdout = os.Stdout
if err := cmd.Run(); err != nil {
return nil, fmt.Errorf("error running editor: %w", err)
}
bytes, err = os.ReadFile(f.Name())
if err != nil {
return nil, fmt.Errorf("error reading temp file: %w", err)
}
final = new(text.Text)
if err := json.Unmarshal(bytes, final); err != nil {
return nil, fmt.Errorf("couldn't parse user JSON: %w", err)
}
return final, nil
}
type editable text.Text
// MarshalJSON marshals the editable subset of e.Text.
//
// NOTE: these must correspond to the JSON tags in text.Text. Any divergence
// may break this editor.
func (e editable) MarshalJSON() ([]byte, error) {
return json.Marshal(&struct {
Title string `json:"title"`
URL string `json:"url"`
Author string `json:"author"`
Note string `json:"note"`
}{
Title: e.Title,
URL: e.URL,
Author: e.Author,
Note: e.Note,
})
}