-
Notifications
You must be signed in to change notification settings - Fork 1
/
editor.go
66 lines (52 loc) · 1.38 KB
/
editor.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
package main
import (
"context"
"fmt"
"io"
"io/ioutil"
"os"
"os/exec"
"github.com/pokstad/nestable/orm"
)
var editorOptions = map[string][]string{
"mate": []string{"--wait"},
}
func runEditor(ctx context.Context, repo orm.Repo, blob, stdin io.Reader, stdout, stderr io.Writer) (io.ReadCloser, error) {
editor, err := repo.GetConfig(ctx, "editor")
if err != nil {
return nil, fmt.Errorf("getting editor config: %w", err)
}
edOpts := editorOptions[editor]
tf, err := ioutil.TempFile("", "nestable-*.md")
if err != nil {
return nil, fmt.Errorf("temp file open: %w", err)
}
_, err = io.Copy(tf, blob)
if err != nil {
return nil, fmt.Errorf("copying blob to temp file: %w", err)
}
if err := tf.Close(); err != nil {
return nil, fmt.Errorf("closing temp file: %w", err)
}
edOpts = append(edOpts, tf.Name())
cmd := exec.Command(editor, edOpts...)
cmd.Stdin = stdin
cmd.Stdout = stdout
cmd.Stderr = stderr
if err = cmd.Run(); err != nil {
return nil, fmt.Errorf("running editor: %w", err)
}
// TODO: replace in memory read of blob with io.Reader when sqlite streaming blob I/O lands
newBlob, err := os.Open(tf.Name())
if err != nil {
return nil, fmt.Errorf("opening temp file: %w", err)
}
return closeDeleter{newBlob}, nil
}
type closeDeleter struct {
*os.File
}
func (cd closeDeleter) Close() error {
defer os.Remove(cd.File.Name())
return cd.File.Close()
}