Skip to content

Commit 41627a2

Browse files
committed
Added Validate method to Tq API struct
1 parent cede004 commit 41627a2

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed

example_test.go

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,3 +36,20 @@ role = "backend"
3636
// Output:
3737
// '10.0.0.2'
3838
}
39+
40+
// ExampleTq_Validate shows how to use the Tq struct to validate whether a
41+
// given query is syntactically correct. The example shows how the error is
42+
// reported and represented as a string.
43+
func ExampleTq_Validate() {
44+
query := "['servers'][['ip']"
45+
config := toml.GoTOMLConf{}
46+
goToml := toml.NewGoTOML(config)
47+
adapter := toml.NewAdapter(goToml)
48+
tq := tq.New(adapter)
49+
err := tq.Validate(query)
50+
fmt.Println(err)
51+
// Output:
52+
// ['servers'][['ip']
53+
// ^
54+
// Parser error: expected ']' to terminate selector but got '['
55+
}

tq.go

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,28 @@ func New(adapter toml.Adapter) *Tq {
3232
}
3333
}
3434

35+
// Validate checks if the query string is syntactically correct.
36+
func (t *Tq) Validate(query string) error {
37+
reader := strings.NewReader(query)
38+
scanner, err := scanner.New(reader)
39+
if err != nil {
40+
return err
41+
}
42+
lexer, err := lexer.New(scanner)
43+
if err != nil {
44+
return err
45+
}
46+
parser, err := parser.New(lexer)
47+
if err != nil {
48+
return err
49+
}
50+
_, err = parser.Parse()
51+
if err != nil {
52+
return err
53+
}
54+
return nil
55+
}
56+
3557
// Run executes the query string against the input data and writes the output
3658
// data to the output writer.
3759
func (t *Tq) Run(input io.Reader, output io.Writer, query string) error {

0 commit comments

Comments
 (0)