forked from unprofession-al/scum
-
Notifications
You must be signed in to change notification settings - Fork 0
/
edit.go
65 lines (51 loc) · 1.29 KB
/
edit.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
package main
import (
"io/ioutil"
"os"
"os/exec"
)
const DefaultEditor = "vim"
// OpenFileInEditor opens filename in a text editor.
func OpenFileInEditor(filename string) error {
editor := os.Getenv("EDITOR")
if editor == "" {
editor = DefaultEditor
}
// Get the full executable path for the editor.
executable, err := exec.LookPath(editor)
if err != nil {
return err
}
cmd := exec.Command(executable, filename)
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
return cmd.Run()
}
// CaptureInputFromEditor opens a temporary file in a text editor and returns
// the written bytes on success or an error on failure. It handles deletion
// of the temporary file behind the scenes.
func CaptureInputFromEditor(in []byte) ([]byte, error) {
file, err := ioutil.TempFile(os.TempDir(), "*")
if err != nil {
return []byte{}, err
}
_, err = file.Write(in)
if err != nil {
return []byte{}, err
}
filename := file.Name()
// Defer removal of the temporary file in case any of the next steps fail.
defer os.Remove(filename)
if err = file.Close(); err != nil {
return []byte{}, err
}
if err = OpenFileInEditor(filename); err != nil {
return []byte{}, err
}
bytes, err := ioutil.ReadFile(filename)
if err != nil {
return []byte{}, err
}
return bytes, nil
}