-
Notifications
You must be signed in to change notification settings - Fork 0
/
askKey.go
45 lines (41 loc) · 981 Bytes
/
askKey.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
package main
import (
"bufio"
"bytes"
"context"
"errors"
"fmt"
"os"
"os/exec"
"time"
)
var ErrEmptyInput = errors.New(`Empty input`)
type AskKey struct {
EnvName string
Cmd string
AllowStdin bool
StdinPrompt string
}
func (askKey *AskKey) GetKey() ([]byte, error) {
if askKey.EnvName != `` {
if envContent := os.Getenv(askKey.EnvName); envContent != `` {
return []byte(envContent), nil
}
}
if askKey.Cmd != `` {
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
cmd := exec.CommandContext(ctx, os.Getenv(`SHELL`), `-c`, askKey.Cmd)
output, err := cmd.Output()
return bytes.TrimSuffix(output, []byte("\n")), err
}
if askKey.AllowStdin {
reader := bufio.NewReader(os.Stdin)
fmt.Print(askKey.StdinPrompt)
input, err := reader.ReadBytes(byte('\n'))
if err != nil { ErrorLog.Println(err.Error()) }
input = bytes.TrimSuffix(input, []byte("\n"))
return input, err
}
return []byte{}, ErrEmptyInput
}