-
Notifications
You must be signed in to change notification settings - Fork 72
/
editor.go
57 lines (49 loc) · 1000 Bytes
/
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
package editor
import (
"fmt"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
)
type Editor struct {
content []byte
filename string
}
func New(content []byte, filename string) *Editor {
return &Editor{
content: content,
filename: filename,
}
}
func (e *Editor) Run() ([]byte, error) {
shell := defaultShell
if os.Getenv("SHELL") != "" {
shell = os.Getenv("SHELL")
}
editor := defaultEditor
if os.Getenv("EDITOR") != "" {
editor = os.Getenv("EDITOR")
}
path := filepath.Join(os.TempDir(), e.filename)
err := ioutil.WriteFile(path, e.content, 0600)
if err != nil {
return nil, err
}
defer os.Remove(path)
args := []string{shell, shellCommandFlag, fmt.Sprintf("%s %s", editor, path)}
// #nosec 204
cmd := exec.Command(args[0], args[1:]...)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Stdin = os.Stdin
err = cmd.Run()
if err != nil {
return nil, err
}
content, err := ioutil.ReadFile(path)
if err != nil {
return nil, err
}
return content, nil
}