Skip to content

Commit

Permalink
support stdin for passing files
Browse files Browse the repository at this point in the history
  • Loading branch information
garethr committed Apr 11, 2019
1 parent 63ef92f commit 4d8ffed
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 6 deletions.
10 changes: 10 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,16 @@ testdata/deployment.yaml
Deployments are not allowed
```

`conftest` can also be used with stdin:

```console
$ cat deployment.yaml | conftest -
testdata/deployment.yaml
Containers must not run as root
Deployments are not allowed
```


## Build

The only way of trying out `conftest` today is to build from source. For that you'll need
Expand Down
25 changes: 19 additions & 6 deletions conftest.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package main

import (
"bufio"
"bytes"
"context"
"errors"
Expand Down Expand Up @@ -35,22 +36,24 @@ var RootCmd = &cobra.Command{
Short: "Test your configuration files using Open Policy Agent",
Version: fmt.Sprintf("Version: %s\nCommit: %s\nDate: %s\n", version, commit, date),
Run: func(cmd *cobra.Command, args []string) {

if len(args) < 1 {
cmd.SilenceErrors = true
fmt.Println("The first argument should be a file")
os.Exit(1)
}
cmd.SilenceUsage = true

compiler, err := buildCompiler(viper.GetString("policy"))
if err != nil {
fmt.Sprintf("Unable to find policies directory: %s", err)
fmt.Printf("Unable to find policy directory: %s", err)
os.Exit(1)
}

foundFailures := false
for _, fileName := range args {
fmt.Println(fileName)
if fileName != "-" {
fmt.Println(fileName)
}
failures, warnings := processFile(fileName, compiler)
if failures != nil {
foundFailures = true
Expand Down Expand Up @@ -89,8 +92,18 @@ func detectLineBreak(haystack []byte) string {
}

func processFile(fileName string, compiler *ast.Compiler) (error, error) {
filePath, _ := filepath.Abs(fileName)
data, err := ioutil.ReadFile(filePath)

var data []byte
var err error

if fileName == "-" {
reader := bufio.NewReader(os.Stdin)
data, err = ioutil.ReadAll(reader)
} else {
filePath, _ := filepath.Abs(fileName)
data, err = ioutil.ReadFile(filePath)
}

if err != nil {
return fmt.Errorf("Unable to open file %s: %s", fileName, err), nil
}
Expand Down Expand Up @@ -139,7 +152,7 @@ func makeQuery(query string, input interface{}, compiler *ast.Compiler) error {
ctx := context.Background()
rs, err := rego.Eval(ctx)
if err != nil {
return fmt.Errorf("Problem evaluating rego policies: %s", err)
return fmt.Errorf("Problem evaluating rego policy: %s", err)
}

var errorsList *multierror.Error
Expand Down

0 comments on commit 4d8ffed

Please sign in to comment.