-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy patheditor.go
82 lines (73 loc) · 1.49 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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package main
import (
"fmt"
"io"
"io/ioutil"
"math/rand"
"os"
"os/exec"
"strings"
"github.com/google/uuid"
)
const (
DefaultEditor = "vim"
)
type Editor struct {
Binary string
}
func NewEditor() (Editor, error) {
bin := os.Getenv("EDITOR")
if bin == "" {
bin = DefaultEditor
} else {
elems := strings.Fields(bin)
if len(elems) > 0 {
bin = elems[0]
}
}
path, err := exec.LookPath(bin)
if err != nil {
return Editor{Binary: bin}, err
}
return Editor{Binary: path}, nil
}
func (e Editor) Launch(path string) error {
cmd := exec.Command(e.Binary, path)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
cmd.Stdin = os.Stdin
if err := cmd.Run(); err != nil {
if err, ok := err.(*exec.Error); ok {
if err.Err == exec.ErrNotFound {
return fmt.Errorf("unable to launch editor : %v", err)
}
}
return fmt.Errorf("editor failed : %v", err)
}
return nil
}
func (e Editor) LaunchTemp(r io.Reader) ([]byte, string, error) {
uuid, err := uuid.NewRandom()
if err != nil {
return []byte{}, "", err
}
tmpf := fmt.Sprintf("/dev/shm/%v", uuid)
f, err := os.OpenFile(tmpf, os.O_RDWR|os.O_CREATE, 0600)
if err != nil {
return nil, "", err
}
defer os.Remove(f.Name())
if _, err := io.Copy(f, r); err != nil {
return nil, "", err
}
if err := e.Launch(f.Name()); err != nil {
return nil, f.Name(), err
}
bytes, err := ioutil.ReadFile(f.Name())
return bytes, f.Name(), err
}
func randomString(n int) string {
b := make([]byte, 8)
_, _ = rand.Read(b)
return string(b)
}