Take in an io.Reader instead of file path (#885)

Signed-off-by: jolheiser <john.olheiser@gmail.com>
This commit is contained in:
John Olheiser 2022-04-19 03:40:48 -05:00 committed by GitHub
parent 3a3282cde2
commit 67d76248a3
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
4 changed files with 21 additions and 7 deletions

View file

@ -44,7 +44,13 @@ func lintDir(c *cli.Context, dir string) error {
}
func lintFile(_ *cli.Context, file string) error {
configErrors, err := schema.Lint(file)
fi, err := os.Open(file)
if err != nil {
return err
}
defer fi.Close()
configErrors, err := schema.Lint(fi)
if err != nil {
fmt.Println("❌ Config is invalid")
for _, configError := range configErrors {

View file

@ -3,6 +3,7 @@ package schema
import (
_ "embed"
"fmt"
"io"
"github.com/xeipuuv/gojsonschema"
@ -12,9 +13,10 @@ import (
//go:embed schema.json
var schemaDefinition []byte
func Lint(file string) ([]gojsonschema.ResultError, error) {
// Lint lints an io.Reader against the Woodpecker schema.json
func Lint(r io.Reader) ([]gojsonschema.ResultError, error) {
schemaLoader := gojsonschema.NewBytesLoader(schemaDefinition)
j, err := yml.LoadYmlFileAsJSON(file)
j, err := yml.LoadYmlReaderAsJSON(r)
if err != nil {
return nil, fmt.Errorf("Failed to load yml file %w", err)
}

View file

@ -2,6 +2,7 @@ package schema_test
import (
"fmt"
"os"
"testing"
"github.com/stretchr/testify/assert"
@ -78,7 +79,10 @@ func TestSchema(t *testing.T) {
for _, tt := range testTable {
t.Run(tt.name, func(t *testing.T) {
configErrors, err := schema.Lint(tt.testFile)
fi, err := os.Open(tt.testFile)
assert.NoError(t, err, "could not open test file")
defer fi.Close()
configErrors, err := schema.Lint(fi)
if tt.fail {
if len(configErrors) == 0 {
assert.Error(t, err, "Expected config errors but got none")

View file

@ -3,7 +3,7 @@ package yml
import (
"encoding/json"
"fmt"
"os"
"io"
"strconv"
"gopkg.in/yaml.v3"
@ -59,6 +59,7 @@ func toJSON(node *yaml.Node) (interface{}, error) {
return nil, fmt.Errorf("do not support yaml node kind '%v'", node.Kind)
}
// ToJSON converts YAML bytes to JSON
func ToJSON(data []byte) ([]byte, error) {
m := &yaml.Node{}
if err := yaml.Unmarshal(data, m); err != nil {
@ -72,8 +73,9 @@ func ToJSON(data []byte) ([]byte, error) {
return json.Marshal(d)
}
func LoadYmlFileAsJSON(path string) (j []byte, err error) {
data, err := os.ReadFile(path)
// LoadYmlReaderAsJSON reads from an io.Reader containing YAML and converts it to JSON
func LoadYmlReaderAsJSON(r io.Reader) (j []byte, err error) {
data, err := io.ReadAll(r)
if err != nil {
return nil, err
}