/
root.go
94 lines (85 loc) · 2.09 KB
/
root.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package cmd
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
"github.com/fatih/color"
"github.com/pkg/errors"
"github.com/spf13/cobra"
)
var configPath string
var failFast bool
var pwd string
// RootCmd represents the base command when called without any subcommands
var RootCmd = &cobra.Command{
Use: "filetest",
Short: "Runs tests against files/file system",
// Uncomment the following line if your bare application
// has an action associated with it:
// Run: func(cmd *cobra.Command, args []string) { },
Run: func(cmd *cobra.Command, args []string) {
err := Run(configPath)
if err != nil {
color.Red(err.Error())
os.Exit(-1)
}
if len(errs) > 0 {
color.Red("There were %d test failures:\n", len(errs))
for _, e := range errs {
color.Red("\t%s\n", e.Error())
}
os.Exit(-1)
}
color.Green("All of your tests have passed with flying colors!")
},
}
// Execute adds all child commands to the root command sets flags appropriately.
// This is called by main.main(). It only needs to happen once to the rootCmd.
func Execute() {
if err := RootCmd.Execute(); err != nil {
fmt.Println(err)
os.Exit(-1)
}
}
func Run(path string) error {
pwd, _ = os.Getwd()
s, err := os.Stat(path)
if err != nil {
return err
}
if s.IsDir() {
return RunDir(path)
}
return RunFile(path)
}
func RunDir(path string) error {
return filepath.Walk(path, func(p string, info os.FileInfo, err error) error {
if !info.IsDir() {
return RunFile(p)
}
return nil
})
}
func RunFile(path string) error {
ext := strings.ToLower(filepath.Ext(path))
if ext != ".json" {
return errors.Errorf("%s is not a .json file", path)
}
b, err := ioutil.ReadFile(path)
if err != nil {
return err
}
ff := Files{}
err = json.Unmarshal(b, &ff)
if err != nil {
return err
}
return ff.Test()
}
func init() {
RootCmd.Flags().StringVarP(&configPath, "config", "c", "filetest.json", "path to the filetest.json or directory containing many json files you want to run")
RootCmd.Flags().BoolVarP(&failFast, "fail-fast", "f", false, "fail fast if there are any errors")
}