forked from gopasspw/gopass
-
Notifications
You must be signed in to change notification settings - Fork 0
/
insert.go
78 lines (64 loc) · 1.96 KB
/
insert.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
package action
import (
"bytes"
"fmt"
"io"
"os"
"github.com/justwatchcom/gopass/password"
"github.com/urfave/cli"
)
// Insert a string as content to a secret file
func (s *Action) Insert(c *cli.Context) error {
echo := c.Bool("echo")
multiline := c.Bool("multiline")
force := c.Bool("force")
confirm := s.confirmRecipients
if force {
confirm = nil
}
name := c.Args().Get(0)
if name == "" {
return fmt.Errorf("provide a secret name")
}
info, err := os.Stdin.Stat()
if err != nil {
return fmt.Errorf("Failed to stat stdin: %s", err)
}
// if content is piped to stdin, read and save it
if info.Mode()&os.ModeCharDevice == 0 {
content := &bytes.Buffer{}
if written, err := io.Copy(content, os.Stdin); err != nil {
return fmt.Errorf("Failed to copy after %d bytes: %s", written, err)
}
return s.Store.SetConfirm(name, content.Bytes(), "Read secret from STDIN", confirm)
}
replacing, err := s.Store.Exists(name)
if err != nil && err != password.ErrNotFound {
return fmt.Errorf("failed to see if %s exists", name)
}
if !force { // don't check if it's force anyway
if replacing && !askForConfirmation(fmt.Sprintf("An entry already exists for %s. Overwrite it?", name)) {
return fmt.Errorf("not overwriting your current secret")
}
}
// if multi-line input is requested start an editor
if multiline {
content, err := s.editor([]byte{})
if err != nil {
return err
}
return s.Store.SetConfirm(name, []byte(content), fmt.Sprintf("Inserted user supplied password with %s", os.Getenv("EDITOR")), confirm)
}
// if echo mode is requested use a simple string input function
var promptFn func(string) (string, error)
if echo {
promptFn = func(prompt string) (string, error) {
return askForString(prompt, "")
}
}
content, err := askForPassword(name, promptFn)
if err != nil {
return fmt.Errorf("failed to ask for password: %v", err)
}
return s.Store.SetConfirm(name, []byte(content), "Inserted user supplied password", confirm)
}