slack-bot/cmd/main.go

89 lines
2.5 KiB
Go

package main
import (
"context"
"flag"
"fmt"
"go/slack-bot/pkg/check"
"go/slack-bot/pkg/notify"
"io/ioutil"
"log"
"os"
"path/filepath"
"github.com/hashicorp/hcl/v2"
"github.com/hashicorp/hcl/v2/gohcl"
"github.com/hashicorp/hcl/v2/hclsyntax"
)
//SlackConf bot global configuration
type SlackConf struct {
BotID string `hcl:"bot_id"`
DestChannelID string `hcl:"dest_channel_id"`
WebhookID string `hcl:"webhook_id"`
DryRun *bool `hcl:"dry_run"`
Df []check.DfParameter `hcl:"df,block"`
}
func main() {
var configFile string
flag.StringVar(&configFile, "config", "config.hcl", "hcl application configuration file")
flag.Parse()
conf := ParseConfiguration(configFile)
slackNotifier := notify.NewSlackNotifier(conf.BotID, conf.DestChannelID, conf.WebhookID)
dfChecker := check.NewDfChecker()
msg := dfChecker.Check(func(stdout string) []notify.Message {
var messages []notify.Message
parsedDf := dfChecker.Parse(stdout)
casted := parsedDf.(check.DfStdout)
for _, dfCheck := range conf.Df {
messages = append(messages, dfChecker.FileSystemUsedCheck(casted, dfCheck))
}
return messages
})
dryRunCtx := context.WithValue(context.Background(), notify.DryRunContextKey, conf.DryRun)
slackNotifier.Notify(dryRunCtx, msg...)
}
//ParseConfiguration take filename path and parse it to Config.SlackConf
func ParseConfiguration(filename string) *SlackConf {
dir, err := os.Getwd()
if err != nil {
log.Fatalf("Fail to determine current directory to load default ./config.hcl file, %+v\n", err)
}
log.Printf("current dir is %s", dir)
if filename == "config.hcl" {
filename = fmt.Sprintf("%s%c%s", dir, os.PathSeparator, filename)
}
relativeFilename, err := filepath.Rel(dir, filename)
if err != nil {
log.Fatalf("Fail to determine configuration relative directory for file %s, %+v", filename, err)
}
src, err := ioutil.ReadFile(relativeFilename)
if err != nil {
log.Fatalf("Missing required parameter filename got : %s, %+v", relativeFilename, err)
}
file, diags := hclsyntax.ParseConfig(src, relativeFilename, hcl.Pos{Line: 1, Column: 1})
if diags.HasErrors() {
log.Fatalf("parse config error, %s", diags.Error())
}
config := &SlackConf{}
diags = gohcl.DecodeBody(file.Body, nil, config)
if diags.HasErrors() {
log.Fatalf("error config decode, %s", diags.Error())
}
if config.BotID == "" || config.DestChannelID == "" || config.WebhookID == "" {
log.Fatal("Missing required parameter : bot_id, dest_channel_id or webhook_id")
}
return config
}