-
Notifications
You must be signed in to change notification settings - Fork 152
/
main.go
103 lines (90 loc) · 2.24 KB
/
main.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
95
96
97
98
99
100
101
102
103
package main
import (
"context"
"fmt"
"io/ioutil"
"os"
"github.com/influxdata/flux"
"github.com/influxdata/flux/ast"
"github.com/influxdata/flux/codes"
"github.com/influxdata/flux/dependencies/filesystem"
_ "github.com/influxdata/flux/fluxinit/static"
"github.com/influxdata/flux/internal/errors"
"github.com/influxdata/flux/lang"
"github.com/influxdata/flux/memory"
"github.com/influxdata/flux/parser"
"github.com/influxdata/flux/runtime"
"github.com/spf13/cobra"
)
var rootCmd = &cobra.Command{
Use: "test_rewriter",
Short: "A tool for fixing common problems with Flux tests by rewriting them in-place.",
Long: "A tool for fixing common problems with Flux tests by rewriting them in-place.",
}
func init() {
rootCmd.Flags().BoolVar(&flagDryRun, "dry-run", false, "do nothing, but show what would be done")
}
var (
flagDryRun = false
)
func main() {
if err := rootCmd.Execute(); err != nil {
_, _ = fmt.Fprint(os.Stderr, err)
os.Exit(1)
}
os.Exit(0)
}
func doSubCommand(f func(fileName string) error, args []string) error {
for _, arg := range args {
fmt.Printf("%v:\n", arg)
if err := f(arg); err != nil {
return errors.Wrap(err, codes.Inherit, arg)
}
fmt.Println()
}
return nil
}
func getFileAST(fileName string) (*ast.Package, error) {
f, err := os.Open(fileName)
if err != nil {
return nil, err
}
defer func() {
_ = f.Close()
}()
script, err := ioutil.ReadAll(f)
if err != nil {
return nil, err
}
astPkg := parser.ParseSource(string(script))
return astPkg, nil
}
func runQuery(query string) (flux.ResultIterator, error) {
c := lang.FluxCompiler{
Extern: nil,
Query: query,
}
deps := flux.NewDefaultDependencies()
deps.Deps.FilesystemService = filesystem.SystemFS
ctx := deps.Inject(context.Background())
program, err := c.Compile(ctx, runtime.Default)
if err != nil {
return nil, err
}
ctx = deps.Inject(ctx)
alloc := &memory.Allocator{}
qry, err := program.Start(ctx, alloc)
if err != nil {
return nil, err
}
return flux.NewResultIteratorFromQuery(qry), nil
}
func rewriteFile(fileName string, astPkg *ast.Package) error {
newScript := ast.Format(astPkg) + "\n"
if !flagDryRun {
if err := ioutil.WriteFile(fileName, []byte(newScript), 0644); err != nil {
return err
}
}
return nil
}