-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patheditor.go
63 lines (49 loc) · 1.06 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
package noteofcli
import (
"fmt"
"io"
"log"
"os"
"os/exec"
"regexp"
)
var wsre = regexp.MustCompile("\\s")
func Edit(editor, text string) ([]byte, error) {
stat, _ := os.Stdin.Stat()
if (stat.Mode()&os.ModeCharDevice) == 0 || editor == "" {
return io.ReadAll(os.Stdin)
} else if editor != "" {
return ExecEditor(editor, text)
}
return []byte{}, fmt.Errorf("editor error")
}
func ExecEditor(editor, text string) ([]byte, error) {
parts := wsre.Split(editor, -1)
tmpfile, err := os.CreateTemp("", "post")
tmpfile.WriteString(text)
tmpPath := tmpfile.Name()
tmpfile.Close()
if err != nil {
return []byte{}, err
}
args := []string{}
if len(parts) > 1 {
args = append(args, parts[1:]...)
}
args = append(args, tmpPath)
log.Println(parts[0], args)
cmd := exec.Command(parts[0], args...)
cmd.Env = os.Environ()
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
log.Fatal(err)
}
log.Println()
body, err := os.ReadFile(tmpPath)
if err != nil {
return []byte{}, err
}
return body, err
}