-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgnupg.go
70 lines (55 loc) · 1.2 KB
/
gnupg.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 gognupg
import (
"bytes"
"context"
"log"
"os"
"os/exec"
"github.com/pkg/errors"
)
var GnuPGHomeEnvVarName = "GNUPGHOME"
type GnuPG struct {
homedir string
// pipes stderr of gnupg to the stderr of your application.
pipeStdErr bool
}
type GnuPGOptions func(*GnuPG)
func WithHomeDir(homeDir string) GnuPGOptions {
return func(gp *GnuPG) {
gp.homedir = homeDir
}
}
func WithPipeStdErr() GnuPGOptions {
return func(gp *GnuPG) {
gp.pipeStdErr = true
}
}
func NewGnuPG(options ...GnuPGOptions) *GnuPG {
gp := &GnuPG{}
for _, opt := range options {
opt(gp)
}
if gp.homedir == "" {
gp.homedir = os.Getenv(GnuPGHomeEnvVarName)
}
return gp
}
func (gpg *GnuPG) runGnuPG(ctx context.Context, input []byte, args ...string) ([]byte, error) {
var inputBuf = bytes.NewBuffer(input)
var outputBuf bytes.Buffer
cmd := exec.CommandContext(ctx, "gpg", args...)
cmd.Stdin = inputBuf
cmd.Stdout = &outputBuf
if gpg.pipeStdErr {
cmd.Stderr = os.Stderr
}
if gpg.homedir != "" {
cmd.Env = append(cmd.Env, "GNUPGHOME="+gpg.homedir)
}
err := cmd.Run()
if err != nil {
log.Println(outputBuf.String())
return nil, errors.Wrap(err, "failed to run command")
}
return outputBuf.Bytes(), nil
}