Revert "feat(config): swap viper and cobra for config (#684)"

This reverts commit ff8cb884a0.
This commit is contained in:
Simon Aronsson 2020-12-21 23:08:23 +01:00
parent 89119515af
commit 8b81fbd48d
No known key found for this signature in database
GPG key ID: 8DA57A5FD341605B
12 changed files with 255 additions and 229 deletions

View file

@ -4,7 +4,6 @@ import (
"encoding/base64"
"fmt"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"net/smtp"
"os"
"strings"
@ -34,17 +33,18 @@ type emailTypeNotifier struct {
delay time.Duration
}
func newEmailNotifier(_ *cobra.Command, acceptedLogLevels []log.Level) t.Notifier {
func newEmailNotifier(c *cobra.Command, acceptedLogLevels []log.Level) t.Notifier {
flags := c.PersistentFlags()
from := viper.GetString("notification-email-from")
to := viper.GetString("notification-email-to")
server := viper.GetString("notification-email-server")
user := viper.GetString("notification-email-server-user")
password := viper.GetString("notification-email-server-password")
port := viper.GetInt("notification-email-server-port")
tlsSkipVerify := viper.GetBool("notification-email-server-tls-skip-verify")
delay := viper.GetInt("notification-email-delay")
subjecttag := viper.GetString("notification-email-subjecttag")
from, _ := flags.GetString("notification-email-from")
to, _ := flags.GetString("notification-email-to")
server, _ := flags.GetString("notification-email-server")
user, _ := flags.GetString("notification-email-server-user")
password, _ := flags.GetString("notification-email-server-password")
port, _ := flags.GetInt("notification-email-server-port")
tlsSkipVerify, _ := flags.GetBool("notification-email-server-tls-skip-verify")
delay, _ := flags.GetInt("notification-email-delay")
subjecttag, _ := flags.GetString("notification-email-subjecttag")
n := &emailTypeNotifier{
From: from,
@ -81,13 +81,13 @@ func (e *emailTypeNotifier) buildMessage(entries []*log.Entry) []byte {
// We don't use fields in watchtower, so don't bother sending them.
}
now := time.Now()
t := time.Now()
header := make(map[string]string)
header["From"] = e.From
header["To"] = e.To
header["Subject"] = emailSubject
header["Date"] = now.Format(time.RFC1123Z)
header["Date"] = t.Format(time.RFC1123Z)
header["MIME-Version"] = "1.0"
header["Content-Type"] = "text/plain; charset=\"utf-8\""
header["Content-Transfer-Encoding"] = "base64"

View file

@ -5,7 +5,6 @@ import (
"crypto/tls"
"encoding/json"
"fmt"
"github.com/spf13/viper"
"net/http"
"strings"
@ -25,10 +24,10 @@ type gotifyTypeNotifier struct {
logLevels []log.Level
}
func newGotifyNotifier(_ *cobra.Command, acceptedLogLevels []log.Level) t.Notifier {
flags := viper.Sub(".")
func newGotifyNotifier(c *cobra.Command, acceptedLogLevels []log.Level) t.Notifier {
flags := c.PersistentFlags()
gotifyURL := flags.GetString("notification-gotify-url")
gotifyURL, _ := flags.GetString("notification-gotify-url")
if len(gotifyURL) < 1 {
log.Fatal("Required argument --notification-gotify-url(cli) or WATCHTOWER_NOTIFICATION_GOTIFY_URL(env) is empty.")
} else if !(strings.HasPrefix(gotifyURL, "http://") || strings.HasPrefix(gotifyURL, "https://")) {
@ -37,12 +36,12 @@ func newGotifyNotifier(_ *cobra.Command, acceptedLogLevels []log.Level) t.Notifi
log.Warn("Using an HTTP url for Gotify is insecure")
}
gotifyToken := flags.GetString("notification-gotify-token")
gotifyToken, _ := flags.GetString("notification-gotify-token")
if len(gotifyToken) < 1 {
log.Fatal("Required argument --notification-gotify-token(cli) or WATCHTOWER_NOTIFICATION_GOTIFY_TOKEN(env) is empty.")
}
gotifyInsecureSkipVerify := flags.GetBool("notification-gotify-tls-skip-verify")
gotifyInsecureSkipVerify, _ := flags.GetBool("notification-gotify-tls-skip-verify")
n := &gotifyTypeNotifier{
gotifyURL: gotifyURL,

View file

@ -5,7 +5,6 @@ import (
"encoding/json"
"fmt"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"net/http"
t "github.com/containrrr/watchtower/pkg/types"
@ -23,14 +22,16 @@ type msTeamsTypeNotifier struct {
data bool
}
func newMsTeamsNotifier(_ *cobra.Command, acceptedLogLevels []log.Level) t.Notifier {
func newMsTeamsNotifier(cmd *cobra.Command, acceptedLogLevels []log.Level) t.Notifier {
webHookURL := viper.GetString("notification-msteams-hook")
flags := cmd.PersistentFlags()
webHookURL, _ := flags.GetString("notification-msteams-hook")
if len(webHookURL) <= 0 {
log.Fatal("Required argument --notification-msteams-hook(cli) or WATCHTOWER_NOTIFICATION_MSTEAMS_HOOK_URL(env) is empty.")
}
withData := viper.GetBool("notification-msteams-data")
withData, _ := flags.GetBool("notification-msteams-data")
n := &msTeamsTypeNotifier{
levels: acceptedLogLevels,
webHookURL: webHookURL,
@ -84,19 +85,19 @@ func (n *msTeamsTypeNotifier) Fire(entry *log.Entry) error {
jsonBody, err := json.Marshal(webHookBody)
if err != nil {
fmt.Println("Failed to build JSON body for MSTeams notification: ", err)
fmt.Println("Failed to build JSON body for MSTeams notificattion: ", err)
return
}
resp, err := http.Post(n.webHookURL, "application/json", bytes.NewBuffer(jsonBody))
resp, err := http.Post(n.webHookURL, "application/json", bytes.NewBuffer([]byte(jsonBody)))
if err != nil {
fmt.Println("Failed to send MSTeams notification: ", err)
fmt.Println("Failed to send MSTeams notificattion: ", err)
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode > 299 {
fmt.Println("Failed to send MSTeams notification. HTTP RESPONSE STATUS: ", resp.StatusCode)
fmt.Println("Failed to send MSTeams notificattion. HTTP RESPONSE STATUS: ", resp.StatusCode)
if resp.Body != nil {
bodyBytes, err := ioutil.ReadAll(resp.Body)
if err == nil {

View file

@ -5,7 +5,6 @@ import (
"github.com/johntdyer/slackrus"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
// Notifier can send log output as notification to admins, with optional batching.
@ -17,7 +16,9 @@ type Notifier struct {
func NewNotifier(c *cobra.Command) *Notifier {
n := &Notifier{}
level := viper.GetString("notifications-level")
f := c.PersistentFlags()
level, _ := f.GetString("notifications-level")
logLevel, err := log.ParseLevel(level)
if err != nil {
log.Fatalf("Notifications invalid log level: %s", err.Error())
@ -26,7 +27,7 @@ func NewNotifier(c *cobra.Command) *Notifier {
acceptedLogLevels := slackrus.LevelThreshold(logLevel)
// Parse types and create notifiers.
types := viper.GetStringSlice("notifications")
types, err := f.GetStringSlice("notifications")
if err != nil {
log.WithField("could not read notifications argument", log.Fields{"Error": err}).Fatal()
}

View file

@ -4,7 +4,6 @@ import (
"bytes"
"fmt"
"github.com/containrrr/shoutrrr/pkg/types"
"github.com/spf13/viper"
"strings"
"text/template"
@ -35,8 +34,9 @@ type shoutrrrTypeNotifier struct {
}
func newShoutrrrNotifier(c *cobra.Command, acceptedLogLevels []log.Level) t.Notifier {
flags := c.PersistentFlags()
urls := viper.GetStringSlice("notification-url")
urls, _ := flags.GetStringArray("notification-url")
r, err := shoutrrr.CreateSender(urls...)
if err != nil {
log.Fatalf("Failed to initialize Shoutrrr notifications: %s\n", err.Error())
@ -126,11 +126,12 @@ func (e *shoutrrrTypeNotifier) Fire(entry *log.Entry) error {
return nil
}
func getShoutrrrTemplate(_ *cobra.Command) *template.Template {
func getShoutrrrTemplate(c *cobra.Command) *template.Template {
var tpl *template.Template
var err error
tplString := viper.GetString("notification-template")
flags := c.PersistentFlags()
tplString, err := flags.GetString("notification-template")
funcs := template.FuncMap{
"ToUpper": strings.ToUpper,
@ -140,7 +141,7 @@ func getShoutrrrTemplate(_ *cobra.Command) *template.Template {
// If we succeed in getting a non-empty template configuration
// try to parse the template string.
if tplString != "" {
if tplString != "" && err == nil {
tpl, err = template.New("").Funcs(funcs).Parse(tplString)
}

View file

@ -32,7 +32,6 @@ func TestShoutrrrDefaultTemplate(t *testing.T) {
func TestShoutrrrTemplate(t *testing.T) {
cmd := new(cobra.Command)
flags.RegisterNotificationFlags(cmd)
flags.BindViperFlags(cmd)
err := cmd.ParseFlags([]string{"--notification-template={{range .}}{{.Level}}: {{.Message}}{{println}}{{end}}"})
require.NoError(t, err)
@ -56,7 +55,6 @@ func TestShoutrrrTemplate(t *testing.T) {
func TestShoutrrrStringFunctions(t *testing.T) {
cmd := new(cobra.Command)
flags.RegisterNotificationFlags(cmd)
flags.BindViperFlags(cmd)
err := cmd.ParseFlags([]string{"--notification-template={{range .}}{{.Level | printf \"%v\" | ToUpper }}: {{.Message | ToLower }} {{.Message | Title }}{{println}}{{end}}"})
require.NoError(t, err)
@ -79,8 +77,8 @@ func TestShoutrrrStringFunctions(t *testing.T) {
func TestShoutrrrInvalidTemplateUsesTemplate(t *testing.T) {
cmd := new(cobra.Command)
flags.RegisterNotificationFlags(cmd)
flags.BindViperFlags(cmd)
err := cmd.ParseFlags([]string{"--notification-template={{"})
require.NoError(t, err)
@ -110,7 +108,7 @@ type blockingRouter struct {
sent chan bool
}
func (b blockingRouter) Send(_ string, _ *types.Params) []error {
func (b blockingRouter) Send(message string, params *types.Params) []error {
_ = <-b.unlock
b.sent <- true
return nil

View file

@ -5,7 +5,6 @@ import (
"github.com/johntdyer/slackrus"
log "github.com/sirupsen/logrus"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
const (
@ -16,13 +15,14 @@ type slackTypeNotifier struct {
slackrus.SlackrusHook
}
func newSlackNotifier(_ *cobra.Command, acceptedLogLevels []log.Level) t.Notifier {
func newSlackNotifier(c *cobra.Command, acceptedLogLevels []log.Level) t.Notifier {
flags := c.PersistentFlags()
hookURL := viper.GetString("notification-slack-hook-url")
userName := viper.GetString("notification-slack-identifier")
channel := viper.GetString("notification-slack-channel")
emoji := viper.GetString("notification-slack-icon-emoji")
iconURL := viper.GetString("notification-slack-icon-url")
hookURL, _ := flags.GetString("notification-slack-hook-url")
userName, _ := flags.GetString("notification-slack-identifier")
channel, _ := flags.GetString("notification-slack-channel")
emoji, _ := flags.GetString("notification-slack-icon-emoji")
iconURL, _ := flags.GetString("notification-slack-icon-url")
n := &slackTypeNotifier{
SlackrusHook: slackrus.SlackrusHook{