This repository has been archived by the owner on Sep 7, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
set.go
93 lines (80 loc) · 2.01 KB
/
set.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
92
93
package core
import (
"bytes"
"fmt"
"io"
"os"
"github.com/sirupsen/logrus"
"github.com/carlosabalde/pgp-tomb/internal/core/config"
"github.com/carlosabalde/pgp-tomb/internal/core/secret"
)
func Set(uri, inputPath string, tags []secret.Tag, ignoreSchema bool) {
s := secret.New(uri)
s.SetTags(tags)
if !set(s, inputPath, ignoreSchema) {
os.Exit(1)
}
fmt.Println("Done!")
}
func set(s *secret.Secret, inputPath string, ignoreSchema bool) bool {
// Initialize input reader.
var input io.Reader
if inputPath == "" {
input = os.Stdin
} else {
file, err := os.Open(inputPath)
if err != nil {
logrus.WithFields(logrus.Fields{
"error": err,
"file": inputPath,
}).Error("Failed to open input file!")
return false
}
defer file.Close()
input = file
}
// Check tags?
if !ignoreSchema {
if serializedTags, err := s.GetSerializedTags(); err != nil {
logrus.WithFields(logrus.Fields{
"error": err,
}).Error("Failed to serialize tags!")
return false
} else {
if valid, errs := validateSchema(serializedTags, config.GetTags()); !valid {
fmt.Fprintf(os.Stderr, "Tags do not match schema!\n")
for _, err := range errs {
fmt.Fprintf(os.Stderr, " - %s\n", err)
}
return false
}
}
}
// Check template?
if template := s.GetTemplate(); template != nil && template.Schema != nil && !ignoreSchema {
buffer := new(bytes.Buffer)
if _, err := io.Copy(buffer, input); err != nil {
logrus.WithFields(logrus.Fields{
"error": err,
}).Error("Failed to read input!")
return false
}
if valid, errs := validateSchema(buffer.String(), template.Schema); !valid {
fmt.Fprintf(os.Stderr, "Secret does not match '%s' schema!\n", template.Alias)
for _, err := range errs {
fmt.Fprintf(os.Stderr, " - %s\n", err)
}
return false
}
input = buffer
}
// Encrypt secret.
if err := s.Encrypt(input); err != nil {
logrus.WithFields(logrus.Fields{
"error": err,
}).Error("Failed to encrypt file!")
return false
}
// Done!
return true
}