...

Source file src/go.einride.tech/aip/filtering/exprs/match_example_test.go

Documentation: go.einride.tech/aip/filtering/exprs

     1  package exprs
     2  
     3  import (
     4  	"fmt"
     5  
     6  	"go.einride.tech/aip/filtering"
     7  	"go.einride.tech/aip/resourcename"
     8  	expr "google.golang.org/genproto/googleapis/api/expr/v1alpha1"
     9  )
    10  
    11  func ExampleMatchFunction_validateResourceNames() {
    12  	const pattern = "books/{book}"
    13  
    14  	var walkErr error
    15  	walkFn := func(currExpr, _ *expr.Expr) bool {
    16  		var name string
    17  		// match any function expression with name '=' and LHS 'name'
    18  		matcher := MatchFunction(filtering.FunctionEquals, MatchText("name"), MatchAnyString(&name))
    19  		if matcher(currExpr) && !resourcename.Match(pattern, name) {
    20  			walkErr = fmt.Errorf("expected resource name matching '%s' but got '%s'", pattern, name)
    21  			return false
    22  		}
    23  		return true
    24  	}
    25  
    26  	// name = "not a resource name" or name = "books/2"
    27  	invalidExpr := filtering.Or(
    28  		filtering.Equals(filtering.Text("name"), filtering.String("not a resource name")),
    29  		filtering.Equals(filtering.Text("name"), filtering.String("books/2")),
    30  	)
    31  	filtering.Walk(walkFn, invalidExpr)
    32  	fmt.Println(walkErr)
    33  
    34  	// reset
    35  	walkErr = nil
    36  
    37  	// name = "books/1" or name = "books/2"
    38  	validExpr := filtering.Or(
    39  		filtering.Equals(filtering.Text("name"), filtering.String("books/1")),
    40  		filtering.Equals(filtering.Text("name"), filtering.String("books/2")),
    41  	)
    42  	filtering.Walk(walkFn, validExpr)
    43  	fmt.Println(walkErr)
    44  
    45  	// Output:
    46  	// expected resource name matching 'books/{book}' but got 'not a resource name'
    47  	// <nil>
    48  }
    49  

View as plain text