drone-yaml/cmd/drone-yaml/main.go

76 lines
1.5 KiB
Go
Raw Normal View History

// Copyright (c), the Drone Authors.
// Copyright (c) 2021, Robert Kaussow <mail@thegeeklab.de>
2019-02-10 20:00:16 +01:00
2019-01-23 00:44:17 +01:00
package main
import (
"bytes"
"io"
"os"
"github.com/alecthomas/kingpin/v2"
2019-01-23 00:44:17 +01:00
"github.com/drone/drone-yaml/yaml"
"github.com/drone/drone-yaml/yaml/linter"
"github.com/drone/drone-yaml/yaml/pretty"
)
//nolint:gochecknoglobals
2019-01-23 00:44:17 +01:00
var (
format = kingpin.Command("fmt", "format the yaml file")
formatSave = format.Flag("save", "save result to source").Short('s').Bool()
formatFile = format.Arg("source", "source file location").Default(".drone.yml").File()
lint = kingpin.Command("lint", "lint the yaml file")
lintPriv = lint.Flag("privileged", "privileged mode").Short('p').Bool()
lintFile = lint.Arg("source", "source file location").Default(".drone.yml").File()
)
const DefaultFilePerm = 0o640
2019-01-23 00:44:17 +01:00
func main() {
switch kingpin.Parse() {
case format.FullCommand():
kingpin.FatalIfError(runFormat(), "")
case lint.FullCommand():
kingpin.FatalIfError(runLint(), "")
}
}
func runFormat() error {
f := *formatFile
2019-01-23 00:44:17 +01:00
m, err := yaml.Parse(f)
if err != nil {
return err
}
b := new(bytes.Buffer)
pretty.Print(b, m)
if *formatSave {
return os.WriteFile(f.Name(), b.Bytes(), DefaultFilePerm)
2019-01-23 00:44:17 +01:00
}
2019-01-23 00:44:17 +01:00
_, err = io.Copy(os.Stderr, b)
2019-01-23 00:44:17 +01:00
return err
}
func runLint() error {
f := *lintFile
2019-01-23 00:44:17 +01:00
m, err := yaml.Parse(f)
if err != nil {
return err
}
2019-01-23 00:44:17 +01:00
for _, r := range m.Resources {
err := linter.Lint(r, *lintPriv)
if err != nil {
return err
}
}
2019-01-23 00:44:17 +01:00
return nil
}