forked from mkideal/cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
editor.go
53 lines (46 loc) · 1.07 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
package cli
import (
"crypto/rand"
"fmt"
"io/ioutil"
"os"
"os/exec"
)
const DefaultEditor = "vim"
// GetEditor sets callback to get editor program
var GetEditor func() (string, error)
func getEditor() (string, error) {
if GetEditor != nil {
return GetEditor()
}
return exec.LookPath(DefaultEditor)
}
func randomFilename() string {
buf := make([]byte, 16)
if _, err := rand.Read(buf); err != nil {
return "CLI_EDIT_FILE"
}
return fmt.Sprintf(".%x", buf)
}
// LaunchEditor launchs the specified editor with a random filename
func LaunchEditor(editor string) (content []byte, err error) {
return launchEditorWithFilename(editor, randomFilename())
}
func launchEditorWithFilename(editor, filename string) (content []byte, err error) {
cmd := exec.Command(editor, filename)
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
defer os.Remove(filename)
err = cmd.Run()
if err != nil {
if _, isExitError := err.(*exec.ExitError); !isExitError {
return
}
}
content, err = ioutil.ReadFile(filename)
if err != nil {
return []byte{}, nil
}
return
}