-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy patheditor_command.go
91 lines (74 loc) · 1.61 KB
/
editor_command.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
83
84
85
86
87
88
89
90
91
package main
import (
"fmt"
"io/ioutil"
"os"
"os/exec"
"path"
"github.com/urfave/cli"
)
type editorCommand struct {
*command
decode bool
editor string
validator *validator
}
func editorCommandFromContext(c *cli.Context) (*editorCommand, error) {
cmd, err := commandFromContext(c)
if err != nil {
return nil, err
}
editor := c.String(editorFlagName)
if editor == "" {
return nil, fmt.Errorf("editor is required")
}
validator, err := newValidator()
if err != nil {
return nil, err
}
return &editorCommand{
cmd,
c.Bool(decodeBase64FlagName),
editor,
validator,
}, nil
}
func (c *editorCommand) create(plainText []byte) error {
cipherText, err := c.crypto.encrypt(plainText)
if err != nil {
return err
}
// re-check before save
if exists(c.filename) {
return fmt.Errorf("%s already exists", c.filename)
}
return ioutil.WriteFile(c.filename, cipherText, 0644)
}
func (c *editorCommand) update(plainText []byte) error {
cipherText, err := c.crypto.encrypt(plainText)
if err != nil {
return err
}
fi, err := os.Stat(c.filename)
if err != nil {
return err
}
return ioutil.WriteFile(c.filename, cipherText, fi.Mode())
}
func (c *editorCommand) editText(text []byte) ([]byte, error) {
tmpFile, err := ioutil.TempFile("", path.Base(c.filename))
if err != nil {
return nil, err
}
defer removeTempFile(tmpFile.Name())
if _, err := tmpFile.Write(text); err != nil {
return nil, err
}
cmd := exec.Command(c.editor, tmpFile.Name())
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
if err := cmd.Run(); err != nil {
return nil, err
}
return ioutil.ReadFile(tmpFile.Name())
}