-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgetTextFromEditor.go
70 lines (56 loc) · 1.11 KB
/
getTextFromEditor.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
package main
import (
"errors"
"io/ioutil"
"os"
"os/exec"
)
func getTextFromEditor() (string, error) {
tmpfile, err := ioutil.TempFile("", "tmp.*")
if err != nil {
return "", err
}
editor := os.Getenv("EDITOR")
if editor == "" {
editor = findEditor("vim")
}
if editor == "" {
editor = findEditor("nano")
}
if editor == "" {
editor = findEditor("pico")
}
// Ugh fiiiiine :þ
if editor == "" {
editor = findEditor("emacs")
}
if editor == "" {
return "", errors.New("No known editor could be found (including via $EDITOR env variable).")
}
defer os.Remove(tmpfile.Name()) // clean up
cmd := exec.Command(editor, tmpfile.Name())
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
err = cmd.Start()
if err != nil {
return "", err
}
err = cmd.Wait()
if err != nil {
return "", err
}
var fileContents []byte
fileContents, err = ioutil.ReadFile(tmpfile.Name())
if err != nil {
return "", err
}
return string(fileContents), nil
}
func findEditor(editorName string) string {
path, err := exec.LookPath(editorName)
if err != nil {
return ""
}
return path
}