4
vendor/github.com/hashicorp/go-bexpr/.gitignore
generated
vendored
Normal file
4
vendor/github.com/hashicorp/go-bexpr/.gitignore
generated
vendored
Normal file
@@ -0,0 +1,4 @@
|
||||
/expr-parse
|
||||
/expr-eval
|
||||
/filter
|
||||
/simple
|
||||
373
vendor/github.com/hashicorp/go-bexpr/LICENSE
generated
vendored
Normal file
373
vendor/github.com/hashicorp/go-bexpr/LICENSE
generated
vendored
Normal file
@@ -0,0 +1,373 @@
|
||||
Mozilla Public License Version 2.0
|
||||
==================================
|
||||
|
||||
1. Definitions
|
||||
--------------
|
||||
|
||||
1.1. "Contributor"
|
||||
means each individual or legal entity that creates, contributes to
|
||||
the creation of, or owns Covered Software.
|
||||
|
||||
1.2. "Contributor Version"
|
||||
means the combination of the Contributions of others (if any) used
|
||||
by a Contributor and that particular Contributor's Contribution.
|
||||
|
||||
1.3. "Contribution"
|
||||
means Covered Software of a particular Contributor.
|
||||
|
||||
1.4. "Covered Software"
|
||||
means Source Code Form to which the initial Contributor has attached
|
||||
the notice in Exhibit A, the Executable Form of such Source Code
|
||||
Form, and Modifications of such Source Code Form, in each case
|
||||
including portions thereof.
|
||||
|
||||
1.5. "Incompatible With Secondary Licenses"
|
||||
means
|
||||
|
||||
(a) that the initial Contributor has attached the notice described
|
||||
in Exhibit B to the Covered Software; or
|
||||
|
||||
(b) that the Covered Software was made available under the terms of
|
||||
version 1.1 or earlier of the License, but not also under the
|
||||
terms of a Secondary License.
|
||||
|
||||
1.6. "Executable Form"
|
||||
means any form of the work other than Source Code Form.
|
||||
|
||||
1.7. "Larger Work"
|
||||
means a work that combines Covered Software with other material, in
|
||||
a separate file or files, that is not Covered Software.
|
||||
|
||||
1.8. "License"
|
||||
means this document.
|
||||
|
||||
1.9. "Licensable"
|
||||
means having the right to grant, to the maximum extent possible,
|
||||
whether at the time of the initial grant or subsequently, any and
|
||||
all of the rights conveyed by this License.
|
||||
|
||||
1.10. "Modifications"
|
||||
means any of the following:
|
||||
|
||||
(a) any file in Source Code Form that results from an addition to,
|
||||
deletion from, or modification of the contents of Covered
|
||||
Software; or
|
||||
|
||||
(b) any new file in Source Code Form that contains any Covered
|
||||
Software.
|
||||
|
||||
1.11. "Patent Claims" of a Contributor
|
||||
means any patent claim(s), including without limitation, method,
|
||||
process, and apparatus claims, in any patent Licensable by such
|
||||
Contributor that would be infringed, but for the grant of the
|
||||
License, by the making, using, selling, offering for sale, having
|
||||
made, import, or transfer of either its Contributions or its
|
||||
Contributor Version.
|
||||
|
||||
1.12. "Secondary License"
|
||||
means either the GNU General Public License, Version 2.0, the GNU
|
||||
Lesser General Public License, Version 2.1, the GNU Affero General
|
||||
Public License, Version 3.0, or any later versions of those
|
||||
licenses.
|
||||
|
||||
1.13. "Source Code Form"
|
||||
means the form of the work preferred for making modifications.
|
||||
|
||||
1.14. "You" (or "Your")
|
||||
means an individual or a legal entity exercising rights under this
|
||||
License. For legal entities, "You" includes any entity that
|
||||
controls, is controlled by, or is under common control with You. For
|
||||
purposes of this definition, "control" means (a) the power, direct
|
||||
or indirect, to cause the direction or management of such entity,
|
||||
whether by contract or otherwise, or (b) ownership of more than
|
||||
fifty percent (50%) of the outstanding shares or beneficial
|
||||
ownership of such entity.
|
||||
|
||||
2. License Grants and Conditions
|
||||
--------------------------------
|
||||
|
||||
2.1. Grants
|
||||
|
||||
Each Contributor hereby grants You a world-wide, royalty-free,
|
||||
non-exclusive license:
|
||||
|
||||
(a) under intellectual property rights (other than patent or trademark)
|
||||
Licensable by such Contributor to use, reproduce, make available,
|
||||
modify, display, perform, distribute, and otherwise exploit its
|
||||
Contributions, either on an unmodified basis, with Modifications, or
|
||||
as part of a Larger Work; and
|
||||
|
||||
(b) under Patent Claims of such Contributor to make, use, sell, offer
|
||||
for sale, have made, import, and otherwise transfer either its
|
||||
Contributions or its Contributor Version.
|
||||
|
||||
2.2. Effective Date
|
||||
|
||||
The licenses granted in Section 2.1 with respect to any Contribution
|
||||
become effective for each Contribution on the date the Contributor first
|
||||
distributes such Contribution.
|
||||
|
||||
2.3. Limitations on Grant Scope
|
||||
|
||||
The licenses granted in this Section 2 are the only rights granted under
|
||||
this License. No additional rights or licenses will be implied from the
|
||||
distribution or licensing of Covered Software under this License.
|
||||
Notwithstanding Section 2.1(b) above, no patent license is granted by a
|
||||
Contributor:
|
||||
|
||||
(a) for any code that a Contributor has removed from Covered Software;
|
||||
or
|
||||
|
||||
(b) for infringements caused by: (i) Your and any other third party's
|
||||
modifications of Covered Software, or (ii) the combination of its
|
||||
Contributions with other software (except as part of its Contributor
|
||||
Version); or
|
||||
|
||||
(c) under Patent Claims infringed by Covered Software in the absence of
|
||||
its Contributions.
|
||||
|
||||
This License does not grant any rights in the trademarks, service marks,
|
||||
or logos of any Contributor (except as may be necessary to comply with
|
||||
the notice requirements in Section 3.4).
|
||||
|
||||
2.4. Subsequent Licenses
|
||||
|
||||
No Contributor makes additional grants as a result of Your choice to
|
||||
distribute the Covered Software under a subsequent version of this
|
||||
License (see Section 10.2) or under the terms of a Secondary License (if
|
||||
permitted under the terms of Section 3.3).
|
||||
|
||||
2.5. Representation
|
||||
|
||||
Each Contributor represents that the Contributor believes its
|
||||
Contributions are its original creation(s) or it has sufficient rights
|
||||
to grant the rights to its Contributions conveyed by this License.
|
||||
|
||||
2.6. Fair Use
|
||||
|
||||
This License is not intended to limit any rights You have under
|
||||
applicable copyright doctrines of fair use, fair dealing, or other
|
||||
equivalents.
|
||||
|
||||
2.7. Conditions
|
||||
|
||||
Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
|
||||
in Section 2.1.
|
||||
|
||||
3. Responsibilities
|
||||
-------------------
|
||||
|
||||
3.1. Distribution of Source Form
|
||||
|
||||
All distribution of Covered Software in Source Code Form, including any
|
||||
Modifications that You create or to which You contribute, must be under
|
||||
the terms of this License. You must inform recipients that the Source
|
||||
Code Form of the Covered Software is governed by the terms of this
|
||||
License, and how they can obtain a copy of this License. You may not
|
||||
attempt to alter or restrict the recipients' rights in the Source Code
|
||||
Form.
|
||||
|
||||
3.2. Distribution of Executable Form
|
||||
|
||||
If You distribute Covered Software in Executable Form then:
|
||||
|
||||
(a) such Covered Software must also be made available in Source Code
|
||||
Form, as described in Section 3.1, and You must inform recipients of
|
||||
the Executable Form how they can obtain a copy of such Source Code
|
||||
Form by reasonable means in a timely manner, at a charge no more
|
||||
than the cost of distribution to the recipient; and
|
||||
|
||||
(b) You may distribute such Executable Form under the terms of this
|
||||
License, or sublicense it under different terms, provided that the
|
||||
license for the Executable Form does not attempt to limit or alter
|
||||
the recipients' rights in the Source Code Form under this License.
|
||||
|
||||
3.3. Distribution of a Larger Work
|
||||
|
||||
You may create and distribute a Larger Work under terms of Your choice,
|
||||
provided that You also comply with the requirements of this License for
|
||||
the Covered Software. If the Larger Work is a combination of Covered
|
||||
Software with a work governed by one or more Secondary Licenses, and the
|
||||
Covered Software is not Incompatible With Secondary Licenses, this
|
||||
License permits You to additionally distribute such Covered Software
|
||||
under the terms of such Secondary License(s), so that the recipient of
|
||||
the Larger Work may, at their option, further distribute the Covered
|
||||
Software under the terms of either this License or such Secondary
|
||||
License(s).
|
||||
|
||||
3.4. Notices
|
||||
|
||||
You may not remove or alter the substance of any license notices
|
||||
(including copyright notices, patent notices, disclaimers of warranty,
|
||||
or limitations of liability) contained within the Source Code Form of
|
||||
the Covered Software, except that You may alter any license notices to
|
||||
the extent required to remedy known factual inaccuracies.
|
||||
|
||||
3.5. Application of Additional Terms
|
||||
|
||||
You may choose to offer, and to charge a fee for, warranty, support,
|
||||
indemnity or liability obligations to one or more recipients of Covered
|
||||
Software. However, You may do so only on Your own behalf, and not on
|
||||
behalf of any Contributor. You must make it absolutely clear that any
|
||||
such warranty, support, indemnity, or liability obligation is offered by
|
||||
You alone, and You hereby agree to indemnify every Contributor for any
|
||||
liability incurred by such Contributor as a result of warranty, support,
|
||||
indemnity or liability terms You offer. You may include additional
|
||||
disclaimers of warranty and limitations of liability specific to any
|
||||
jurisdiction.
|
||||
|
||||
4. Inability to Comply Due to Statute or Regulation
|
||||
---------------------------------------------------
|
||||
|
||||
If it is impossible for You to comply with any of the terms of this
|
||||
License with respect to some or all of the Covered Software due to
|
||||
statute, judicial order, or regulation then You must: (a) comply with
|
||||
the terms of this License to the maximum extent possible; and (b)
|
||||
describe the limitations and the code they affect. Such description must
|
||||
be placed in a text file included with all distributions of the Covered
|
||||
Software under this License. Except to the extent prohibited by statute
|
||||
or regulation, such description must be sufficiently detailed for a
|
||||
recipient of ordinary skill to be able to understand it.
|
||||
|
||||
5. Termination
|
||||
--------------
|
||||
|
||||
5.1. The rights granted under this License will terminate automatically
|
||||
if You fail to comply with any of its terms. However, if You become
|
||||
compliant, then the rights granted under this License from a particular
|
||||
Contributor are reinstated (a) provisionally, unless and until such
|
||||
Contributor explicitly and finally terminates Your grants, and (b) on an
|
||||
ongoing basis, if such Contributor fails to notify You of the
|
||||
non-compliance by some reasonable means prior to 60 days after You have
|
||||
come back into compliance. Moreover, Your grants from a particular
|
||||
Contributor are reinstated on an ongoing basis if such Contributor
|
||||
notifies You of the non-compliance by some reasonable means, this is the
|
||||
first time You have received notice of non-compliance with this License
|
||||
from such Contributor, and You become compliant prior to 30 days after
|
||||
Your receipt of the notice.
|
||||
|
||||
5.2. If You initiate litigation against any entity by asserting a patent
|
||||
infringement claim (excluding declaratory judgment actions,
|
||||
counter-claims, and cross-claims) alleging that a Contributor Version
|
||||
directly or indirectly infringes any patent, then the rights granted to
|
||||
You by any and all Contributors for the Covered Software under Section
|
||||
2.1 of this License shall terminate.
|
||||
|
||||
5.3. In the event of termination under Sections 5.1 or 5.2 above, all
|
||||
end user license agreements (excluding distributors and resellers) which
|
||||
have been validly granted by You or Your distributors under this License
|
||||
prior to termination shall survive termination.
|
||||
|
||||
************************************************************************
|
||||
* *
|
||||
* 6. Disclaimer of Warranty *
|
||||
* ------------------------- *
|
||||
* *
|
||||
* Covered Software is provided under this License on an "as is" *
|
||||
* basis, without warranty of any kind, either expressed, implied, or *
|
||||
* statutory, including, without limitation, warranties that the *
|
||||
* Covered Software is free of defects, merchantable, fit for a *
|
||||
* particular purpose or non-infringing. The entire risk as to the *
|
||||
* quality and performance of the Covered Software is with You. *
|
||||
* Should any Covered Software prove defective in any respect, You *
|
||||
* (not any Contributor) assume the cost of any necessary servicing, *
|
||||
* repair, or correction. This disclaimer of warranty constitutes an *
|
||||
* essential part of this License. No use of any Covered Software is *
|
||||
* authorized under this License except under this disclaimer. *
|
||||
* *
|
||||
************************************************************************
|
||||
|
||||
************************************************************************
|
||||
* *
|
||||
* 7. Limitation of Liability *
|
||||
* -------------------------- *
|
||||
* *
|
||||
* Under no circumstances and under no legal theory, whether tort *
|
||||
* (including negligence), contract, or otherwise, shall any *
|
||||
* Contributor, or anyone who distributes Covered Software as *
|
||||
* permitted above, be liable to You for any direct, indirect, *
|
||||
* special, incidental, or consequential damages of any character *
|
||||
* including, without limitation, damages for lost profits, loss of *
|
||||
* goodwill, work stoppage, computer failure or malfunction, or any *
|
||||
* and all other commercial damages or losses, even if such party *
|
||||
* shall have been informed of the possibility of such damages. This *
|
||||
* limitation of liability shall not apply to liability for death or *
|
||||
* personal injury resulting from such party's negligence to the *
|
||||
* extent applicable law prohibits such limitation. Some *
|
||||
* jurisdictions do not allow the exclusion or limitation of *
|
||||
* incidental or consequential damages, so this exclusion and *
|
||||
* limitation may not apply to You. *
|
||||
* *
|
||||
************************************************************************
|
||||
|
||||
8. Litigation
|
||||
-------------
|
||||
|
||||
Any litigation relating to this License may be brought only in the
|
||||
courts of a jurisdiction where the defendant maintains its principal
|
||||
place of business and such litigation shall be governed by laws of that
|
||||
jurisdiction, without reference to its conflict-of-law provisions.
|
||||
Nothing in this Section shall prevent a party's ability to bring
|
||||
cross-claims or counter-claims.
|
||||
|
||||
9. Miscellaneous
|
||||
----------------
|
||||
|
||||
This License represents the complete agreement concerning the subject
|
||||
matter hereof. If any provision of this License is held to be
|
||||
unenforceable, such provision shall be reformed only to the extent
|
||||
necessary to make it enforceable. Any law or regulation which provides
|
||||
that the language of a contract shall be construed against the drafter
|
||||
shall not be used to construe this License against a Contributor.
|
||||
|
||||
10. Versions of the License
|
||||
---------------------------
|
||||
|
||||
10.1. New Versions
|
||||
|
||||
Mozilla Foundation is the license steward. Except as provided in Section
|
||||
10.3, no one other than the license steward has the right to modify or
|
||||
publish new versions of this License. Each version will be given a
|
||||
distinguishing version number.
|
||||
|
||||
10.2. Effect of New Versions
|
||||
|
||||
You may distribute the Covered Software under the terms of the version
|
||||
of the License under which You originally received the Covered Software,
|
||||
or under the terms of any subsequent version published by the license
|
||||
steward.
|
||||
|
||||
10.3. Modified Versions
|
||||
|
||||
If you create software not governed by this License, and you want to
|
||||
create a new license for such software, you may create and use a
|
||||
modified version of this License if you rename the license and remove
|
||||
any references to the name of the license steward (except to note that
|
||||
such modified license differs from this License).
|
||||
|
||||
10.4. Distributing Source Code Form that is Incompatible With Secondary
|
||||
Licenses
|
||||
|
||||
If You choose to distribute Source Code Form that is Incompatible With
|
||||
Secondary Licenses under the terms of this version of the License, the
|
||||
notice described in Exhibit B of this License must be attached.
|
||||
|
||||
Exhibit A - Source Code Form License Notice
|
||||
-------------------------------------------
|
||||
|
||||
This Source Code Form is subject to the terms of the Mozilla Public
|
||||
License, v. 2.0. If a copy of the MPL was not distributed with this
|
||||
file, You can obtain one at http://mozilla.org/MPL/2.0/.
|
||||
|
||||
If it is not possible or desirable to put the notice in a particular
|
||||
file, then You may include the notice in a location (such as a LICENSE
|
||||
file in a relevant directory) where a recipient would be likely to look
|
||||
for such a notice.
|
||||
|
||||
You may add additional accurate notices of copyright ownership.
|
||||
|
||||
Exhibit B - "Incompatible With Secondary Licenses" Notice
|
||||
---------------------------------------------------------
|
||||
|
||||
This Source Code Form is "Incompatible With Secondary Licenses", as
|
||||
defined by the Mozilla Public License, v. 2.0.
|
||||
63
vendor/github.com/hashicorp/go-bexpr/Makefile
generated
vendored
Normal file
63
vendor/github.com/hashicorp/go-bexpr/Makefile
generated
vendored
Normal file
@@ -0,0 +1,63 @@
|
||||
GOTEST_PKGS=$(shell go list ./... | grep -v examples)
|
||||
|
||||
BENCHTIME ?= 2s
|
||||
BENCHTESTS ?= .
|
||||
|
||||
BENCHFULL?=0
|
||||
ifeq (${BENCHFULL},1)
|
||||
BENCHFULL_ARG=-bench-full -timeout 60m
|
||||
else
|
||||
BENCHFULL_ARG=
|
||||
endif
|
||||
|
||||
TEST_VERBOSE?=0
|
||||
ifeq (${TEST_VERBOSE},1)
|
||||
TEST_VERBOSE_ARG=-v
|
||||
else
|
||||
TEST_VERBOSE_ARG=
|
||||
endif
|
||||
|
||||
TEST_RESULTS?="/tmp/test-results"
|
||||
|
||||
generate:
|
||||
@echo "Regenerating Parser"
|
||||
@go generate ./
|
||||
|
||||
test:
|
||||
@go test $(TEST_VERBOSE_ARG) $(GOTEST_PKGS)
|
||||
|
||||
test-ci:
|
||||
@gotestsum --junitfile $(TEST_RESULTS)/gotestsum-report.xml -- $(GOTEST_PKGS)
|
||||
|
||||
bench:
|
||||
@go test $(TEST_VERBOSE_ARG) -run DONTRUNTESTS -bench $(BENCHTESTS) $(BENCHFULL_ARG) -benchtime=$(BENCHTIME) $(GOTEST_PKGS)
|
||||
|
||||
coverage:
|
||||
@go test -coverprofile /tmp/coverage.out $(GOTEST_PKGS)
|
||||
@go tool cover -html /tmp/coverage.out
|
||||
|
||||
fmt:
|
||||
@gofmt -w -s
|
||||
|
||||
examples: simple expr-parse expr-eval filter
|
||||
|
||||
simple:
|
||||
@go build ./examples/simple
|
||||
|
||||
expr-parse:
|
||||
@go build ./examples/expr-parse
|
||||
|
||||
expr-eval:
|
||||
@go build ./examples/expr-eval
|
||||
|
||||
filter:
|
||||
@go build ./examples/filter
|
||||
|
||||
deps:
|
||||
@go get github.com/mna/pigeon@master
|
||||
@go get golang.org/x/tools/cmd/goimports
|
||||
@go get golang.org/x/tools/cmd/cover
|
||||
@go mod tidy
|
||||
|
||||
.PHONY: generate test coverage fmt deps bench examples expr-parse expr-eval filter
|
||||
|
||||
104
vendor/github.com/hashicorp/go-bexpr/README.md
generated
vendored
Normal file
104
vendor/github.com/hashicorp/go-bexpr/README.md
generated
vendored
Normal file
@@ -0,0 +1,104 @@
|
||||
# bexpr - Boolean Expression Evaluator [](https://godoc.org/github.com/hashicorp/go-bexpr) [](https://circleci.com/gh/hashicorp/go-bexpr)
|
||||
|
||||
`bexpr` is a Go (golang) library to provide generic boolean expression
|
||||
evaluation and filtering for Go data structures and maps. Under the hood,
|
||||
`bexpr` uses
|
||||
[`pointerstructure`](https://github.com/mitchellh/pointerstructure), meaning
|
||||
that any path within a map or structure that can be expressed via that library
|
||||
can be used with `bexpr`. This also means that you can use the custom `bexpr`
|
||||
dotted syntax (kept mainly for backwards compatibility) to select values in
|
||||
expressions, or, by enclosing the selectors in quotes, you can use [JSON
|
||||
Pointer](https://tools.ietf.org/html/rfc6901) syntax to select values in
|
||||
expressions.
|
||||
|
||||
## Usage (Reflection)
|
||||
|
||||
This example program is available in [examples/simple](examples/simple)
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/hashicorp/go-bexpr"
|
||||
)
|
||||
|
||||
type Example struct {
|
||||
X int
|
||||
|
||||
// Can rename a field with the struct tag
|
||||
Y string `bexpr:"y"`
|
||||
Z bool `bexpr:"foo"`
|
||||
|
||||
// Tag with "-" to prevent allowing this field from being used
|
||||
Hidden string `bexpr:"-"`
|
||||
|
||||
// Unexported fields are not available for evaluation
|
||||
unexported string
|
||||
}
|
||||
|
||||
func main() {
|
||||
value := map[string]Example{
|
||||
"foo": Example{X: 5, Y: "foo", Z: true, Hidden: "yes", unexported: "no"},
|
||||
"bar": Example{X: 42, Y: "bar", Z: false, Hidden: "no", unexported: "yes"},
|
||||
}
|
||||
|
||||
expressions := []string{
|
||||
"foo.X == 5",
|
||||
"bar.y == bar",
|
||||
"foo.baz == true",
|
||||
|
||||
// will error in evaluator creation
|
||||
"bar.Hidden != yes",
|
||||
|
||||
// will error in evaluator creation
|
||||
"foo.unexported == no",
|
||||
}
|
||||
|
||||
for _, expression := range expressions {
|
||||
eval, err := bexpr.CreateEvaluator(expression)
|
||||
|
||||
if err != nil {
|
||||
fmt.Printf("Failed to create evaluator for expression %q: %v\n", expression, err)
|
||||
continue
|
||||
}
|
||||
|
||||
result, err := eval.Evaluate(value)
|
||||
if err != nil {
|
||||
fmt.Printf("Failed to run evaluation of expression %q: %v\n", expression, err)
|
||||
continue
|
||||
}
|
||||
|
||||
fmt.Printf("Result of expression %q evaluation: %t\n", expression, result)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
This will output:
|
||||
|
||||
```
|
||||
Result of expression "foo.X == 5" evaluation: true
|
||||
Result of expression "bar.y == bar" evaluation: true
|
||||
Result of expression "foo.baz == true" evaluation: true
|
||||
Failed to run evaluation of expression "bar.Hidden != yes": error finding value in datum: /bar/Hidden at part 1: struct field "Hidden" is ignored and cannot be used
|
||||
Failed to run evaluation of expression "foo.unexported == no": error finding value in datum: /foo/unexported at part 1: couldn't find struct field with name "unexported"
|
||||
```
|
||||
|
||||
## Testing
|
||||
|
||||
The [Makefile](Makefile) contains 3 main targets to aid with testing:
|
||||
|
||||
1. `make test` - runs the standard test suite
|
||||
2. `make coverage` - runs the test suite gathering coverage information
|
||||
3. `make bench` - this will run benchmarks. You can use the [`benchcmp`](https://godoc.org/golang.org/x/tools/cmd/benchcmp) tool to compare
|
||||
subsequent runs of the tool to compare performance. There are a few arguments you can
|
||||
provide to the make invocation to alter the behavior a bit
|
||||
* `BENCHFULL=1` - This will enable running all the benchmarks. Some could be fairly redundant but
|
||||
could be useful when modifying specific sections of the code.
|
||||
* `BENCHTIME=5s` - By default the -benchtime paramater used for the `go test` invocation is `2s`.
|
||||
`1s` seemed like too little to get results consistent enough for comparison between two runs.
|
||||
For the highest degree of confidence that performance has remained steady increase this value
|
||||
even further. The time it takes to run the bench testing suite grows linearly with this value.
|
||||
* `BENCHTESTS=BenchmarkEvalute` - This is used to run a particular benchmark including all of its
|
||||
sub-benchmarks. This is just an example and "BenchmarkEvaluate" can be replaced with any
|
||||
benchmark functions name.
|
||||
51
vendor/github.com/hashicorp/go-bexpr/bexpr.go
generated
vendored
Normal file
51
vendor/github.com/hashicorp/go-bexpr/bexpr.go
generated
vendored
Normal file
@@ -0,0 +1,51 @@
|
||||
// bexpr is an implementation of a generic boolean expression evaluator.
|
||||
// The general goal is to be able to evaluate some expression against some
|
||||
// arbitrary data and get back a boolean of whether or not the data
|
||||
// was matched by the expression
|
||||
package bexpr
|
||||
|
||||
//go:generate pigeon -o grammar/grammar.go -optimize-parser grammar/grammar.peg
|
||||
//go:generate goimports -w grammar/grammar.go
|
||||
|
||||
import (
|
||||
"github.com/hashicorp/go-bexpr/grammar"
|
||||
"github.com/mitchellh/pointerstructure"
|
||||
)
|
||||
|
||||
// HookFn provides a way to translate one reflect.Value to another during
|
||||
// evaluation by bexpr. This facilitates making Go structures appear in a way
|
||||
// that matches the expected JSON Pointers used for evaluation. This is
|
||||
// helpful, for example, when working with protocol buffers' well-known types.
|
||||
type ValueTransformationHookFn = pointerstructure.ValueTransformationHookFn
|
||||
|
||||
type Evaluator struct {
|
||||
// The syntax tree
|
||||
ast grammar.Expression
|
||||
tagName string
|
||||
valueTransformationHook ValueTransformationHookFn
|
||||
}
|
||||
|
||||
func CreateEvaluator(expression string, opts ...Option) (*Evaluator, error) {
|
||||
parsedOpts := getOpts(opts...)
|
||||
var parserOpts []grammar.Option
|
||||
if parsedOpts.withMaxExpressions != 0 {
|
||||
parserOpts = append(parserOpts, grammar.MaxExpressions(parsedOpts.withMaxExpressions))
|
||||
}
|
||||
|
||||
ast, err := grammar.Parse("", []byte(expression), parserOpts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
eval := &Evaluator{
|
||||
ast: ast.(grammar.Expression),
|
||||
tagName: parsedOpts.withTagName,
|
||||
valueTransformationHook: parsedOpts.withHookFn,
|
||||
}
|
||||
|
||||
return eval, nil
|
||||
}
|
||||
|
||||
func (eval *Evaluator) Evaluate(datum interface{}) (bool, error) {
|
||||
return evaluate(eval.ast, datum, WithTagName(eval.tagName), WithHookFn(eval.valueTransformationHook))
|
||||
}
|
||||
46
vendor/github.com/hashicorp/go-bexpr/coerce.go
generated
vendored
Normal file
46
vendor/github.com/hashicorp/go-bexpr/coerce.go
generated
vendored
Normal file
@@ -0,0 +1,46 @@
|
||||
package bexpr
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
)
|
||||
|
||||
// CoerceInt64 conforms to the FieldValueCoercionFn signature
|
||||
// and can be used to convert the raw string value of
|
||||
// an expression into an `int64`
|
||||
func CoerceInt64(value string) (interface{}, error) {
|
||||
i, err := strconv.ParseInt(value, 0, 64)
|
||||
return int64(i), err
|
||||
}
|
||||
|
||||
// CoerceUint64 conforms to the FieldValueCoercionFn signature
|
||||
// and can be used to convert the raw string value of
|
||||
// an expression into an `int64`
|
||||
func CoerceUint64(value string) (interface{}, error) {
|
||||
i, err := strconv.ParseUint(value, 0, 64)
|
||||
return uint64(i), err
|
||||
}
|
||||
|
||||
// CoerceBool conforms to the FieldValueCoercionFn signature
|
||||
// and can be used to convert the raw string value of
|
||||
// an expression into a `bool`
|
||||
func CoerceBool(value string) (interface{}, error) {
|
||||
return strconv.ParseBool(value)
|
||||
}
|
||||
|
||||
// CoerceFloat32 conforms to the FieldValueCoercionFn signature
|
||||
// and can be used to convert the raw string value of
|
||||
// an expression into an `float32`
|
||||
func CoerceFloat32(value string) (interface{}, error) {
|
||||
// ParseFloat always returns a float64 but ensures
|
||||
// it can be converted to a float32 without changing
|
||||
// its value
|
||||
f, err := strconv.ParseFloat(value, 32)
|
||||
return float32(f), err
|
||||
}
|
||||
|
||||
// CoerceFloat64 conforms to the FieldValueCoercionFn signature
|
||||
// and can be used to convert the raw string value of
|
||||
// an expression into an `float64`
|
||||
func CoerceFloat64(value string) (interface{}, error) {
|
||||
return strconv.ParseFloat(value, 64)
|
||||
}
|
||||
309
vendor/github.com/hashicorp/go-bexpr/evaluate.go
generated
vendored
Normal file
309
vendor/github.com/hashicorp/go-bexpr/evaluate.go
generated
vendored
Normal file
@@ -0,0 +1,309 @@
|
||||
package bexpr
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"reflect"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/hashicorp/go-bexpr/grammar"
|
||||
"github.com/mitchellh/pointerstructure"
|
||||
)
|
||||
|
||||
var byteSliceTyp reflect.Type = reflect.TypeOf([]byte{})
|
||||
|
||||
func primitiveEqualityFn(kind reflect.Kind) func(first interface{}, second reflect.Value) bool {
|
||||
switch kind {
|
||||
case reflect.Bool:
|
||||
return doEqualBool
|
||||
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
|
||||
return doEqualInt64
|
||||
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
|
||||
return doEqualUint64
|
||||
case reflect.Float32:
|
||||
return doEqualFloat32
|
||||
case reflect.Float64:
|
||||
return doEqualFloat64
|
||||
case reflect.String:
|
||||
return doEqualString
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func doEqualBool(first interface{}, second reflect.Value) bool {
|
||||
return first.(bool) == second.Bool()
|
||||
}
|
||||
|
||||
func doEqualInt64(first interface{}, second reflect.Value) bool {
|
||||
return first.(int64) == second.Int()
|
||||
}
|
||||
|
||||
func doEqualUint64(first interface{}, second reflect.Value) bool {
|
||||
return first.(uint64) == second.Uint()
|
||||
}
|
||||
|
||||
func doEqualFloat32(first interface{}, second reflect.Value) bool {
|
||||
return first.(float32) == float32(second.Float())
|
||||
}
|
||||
|
||||
func doEqualFloat64(first interface{}, second reflect.Value) bool {
|
||||
return first.(float64) == second.Float()
|
||||
}
|
||||
|
||||
func doEqualString(first interface{}, second reflect.Value) bool {
|
||||
return first.(string) == second.String()
|
||||
}
|
||||
|
||||
// Get rid of 0 to many levels of pointers to get at the real type
|
||||
func derefType(rtype reflect.Type) reflect.Type {
|
||||
for rtype.Kind() == reflect.Ptr {
|
||||
rtype = rtype.Elem()
|
||||
}
|
||||
return rtype
|
||||
}
|
||||
|
||||
func doMatchMatches(expression *grammar.MatchExpression, value reflect.Value) (bool, error) {
|
||||
if !value.Type().ConvertibleTo(byteSliceTyp) {
|
||||
return false, fmt.Errorf("Value of type %s is not convertible to []byte", value.Type())
|
||||
}
|
||||
|
||||
var re *regexp.Regexp
|
||||
var ok bool
|
||||
if expression.Value.Converted != nil {
|
||||
re, ok = expression.Value.Converted.(*regexp.Regexp)
|
||||
}
|
||||
if !ok || re == nil {
|
||||
var err error
|
||||
re, err = regexp.Compile(expression.Value.Raw)
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("Failed to compile regular expression %q: %v", expression.Value.Raw, err)
|
||||
}
|
||||
expression.Value.Converted = re
|
||||
}
|
||||
|
||||
return re.Match(value.Convert(byteSliceTyp).Interface().([]byte)), nil
|
||||
}
|
||||
|
||||
func doMatchEqual(expression *grammar.MatchExpression, value reflect.Value) (bool, error) {
|
||||
// NOTE: see preconditions in evaluategrammar.MatchExpressionRecurse
|
||||
eqFn := primitiveEqualityFn(value.Kind())
|
||||
if eqFn == nil {
|
||||
return false, errors.New("unable to find suitable primitive comparison function for matching")
|
||||
}
|
||||
matchValue, err := getMatchExprValue(expression, value.Kind())
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("error getting match value in expression: %w", err)
|
||||
}
|
||||
return eqFn(matchValue, value), nil
|
||||
}
|
||||
|
||||
func doMatchIn(expression *grammar.MatchExpression, value reflect.Value) (bool, error) {
|
||||
matchValue, err := getMatchExprValue(expression, value.Kind())
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("error getting match value in expression: %w", err)
|
||||
}
|
||||
|
||||
switch kind := value.Kind(); kind {
|
||||
case reflect.Map:
|
||||
found := value.MapIndex(reflect.ValueOf(matchValue))
|
||||
return found.IsValid(), nil
|
||||
|
||||
case reflect.Slice, reflect.Array:
|
||||
itemType := derefType(value.Type().Elem())
|
||||
kind := itemType.Kind()
|
||||
switch kind {
|
||||
case reflect.Interface:
|
||||
// If it's an interface, that is, the type was []interface{}, we
|
||||
// have to treat each element individually, checking each element's
|
||||
// type/kind and rederiving the match value.
|
||||
for i := 0; i < value.Len(); i++ {
|
||||
item := value.Index(i).Elem()
|
||||
itemType := derefType(item.Type())
|
||||
kind := itemType.Kind()
|
||||
// We need to special case errors here. The reason is that in an
|
||||
// interface slice there can be a mix/match of types, but the
|
||||
// coerce functions expect a certain type. So the expression
|
||||
// passed in might be `"true" in "/my/slice"` but the value it's
|
||||
// checking against might be an integer, thus it will try to
|
||||
// coerce "true" to an integer and fail. However, all of the
|
||||
// functions use strconv which has a specific error type for
|
||||
// syntax errors, so as a special case in this situation, don't
|
||||
// error on a strconv.ErrSyntax, just continue on to the next
|
||||
// element.
|
||||
matchValue, err = getMatchExprValue(expression, kind)
|
||||
if err != nil {
|
||||
if errors.Is(err, strconv.ErrSyntax) {
|
||||
continue
|
||||
}
|
||||
return false, errors.New(`error getting interface slice match value in expression`)
|
||||
}
|
||||
eqFn := primitiveEqualityFn(kind)
|
||||
if eqFn == nil {
|
||||
return false, fmt.Errorf(`unable to find suitable primitive comparison function for "in" comparison in interface slice: %s`, kind)
|
||||
}
|
||||
// the value will be the correct type as we verified the itemType
|
||||
if eqFn(matchValue, reflect.Indirect(item)) {
|
||||
return true, nil
|
||||
}
|
||||
}
|
||||
return false, nil
|
||||
|
||||
default:
|
||||
// Otherwise it's a concrete type and we can essentially cache the
|
||||
// answers. First we need to re-derive the match value for equality
|
||||
// assertion.
|
||||
matchValue, err = getMatchExprValue(expression, kind)
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("error getting match value in expression: %w", err)
|
||||
}
|
||||
eqFn := primitiveEqualityFn(kind)
|
||||
if eqFn == nil {
|
||||
return false, errors.New(`unable to find suitable primitive comparison function for "in" comparison`)
|
||||
}
|
||||
for i := 0; i < value.Len(); i++ {
|
||||
item := value.Index(i)
|
||||
// the value will be the correct type as we verified the itemType
|
||||
if eqFn(matchValue, reflect.Indirect(item)) {
|
||||
return true, nil
|
||||
}
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
|
||||
case reflect.String:
|
||||
return strings.Contains(value.String(), matchValue.(string)), nil
|
||||
|
||||
default:
|
||||
return false, fmt.Errorf("Cannot perform in/contains operations on type %s for selector: %q", kind, expression.Selector)
|
||||
}
|
||||
}
|
||||
|
||||
func doMatchIsEmpty(matcher *grammar.MatchExpression, value reflect.Value) (bool, error) {
|
||||
// NOTE: see preconditions in evaluategrammar.MatchExpressionRecurse
|
||||
return value.Len() == 0, nil
|
||||
}
|
||||
|
||||
func getMatchExprValue(expression *grammar.MatchExpression, rvalue reflect.Kind) (interface{}, error) {
|
||||
if expression.Value == nil {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
switch rvalue {
|
||||
case reflect.Bool:
|
||||
return CoerceBool(expression.Value.Raw)
|
||||
|
||||
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
|
||||
return CoerceInt64(expression.Value.Raw)
|
||||
|
||||
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
|
||||
return CoerceUint64(expression.Value.Raw)
|
||||
|
||||
case reflect.Float32:
|
||||
return CoerceFloat32(expression.Value.Raw)
|
||||
|
||||
case reflect.Float64:
|
||||
return CoerceFloat64(expression.Value.Raw)
|
||||
|
||||
default:
|
||||
return expression.Value.Raw, nil
|
||||
}
|
||||
}
|
||||
|
||||
func evaluateMatchExpression(expression *grammar.MatchExpression, datum interface{}, opt ...Option) (bool, error) {
|
||||
opts := getOpts(opt...)
|
||||
ptr := pointerstructure.Pointer{
|
||||
Parts: expression.Selector.Path,
|
||||
Config: pointerstructure.Config{
|
||||
TagName: opts.withTagName,
|
||||
ValueTransformationHook: opts.withHookFn,
|
||||
},
|
||||
}
|
||||
val, err := ptr.Get(datum)
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("error finding value in datum: %w", err)
|
||||
}
|
||||
|
||||
if jn, ok := val.(json.Number); ok {
|
||||
if jni, err := jn.Int64(); err == nil {
|
||||
val = jni
|
||||
} else if jnf, err := jn.Float64(); err == nil {
|
||||
val = jnf
|
||||
} else {
|
||||
return false, fmt.Errorf("unable to convert json number %s to int or float", jn)
|
||||
}
|
||||
}
|
||||
|
||||
rvalue := reflect.Indirect(reflect.ValueOf(val))
|
||||
switch expression.Operator {
|
||||
case grammar.MatchEqual:
|
||||
return doMatchEqual(expression, rvalue)
|
||||
case grammar.MatchNotEqual:
|
||||
result, err := doMatchEqual(expression, rvalue)
|
||||
if err == nil {
|
||||
return !result, nil
|
||||
}
|
||||
return false, err
|
||||
case grammar.MatchIn:
|
||||
return doMatchIn(expression, rvalue)
|
||||
case grammar.MatchNotIn:
|
||||
result, err := doMatchIn(expression, rvalue)
|
||||
if err == nil {
|
||||
return !result, nil
|
||||
}
|
||||
return false, err
|
||||
case grammar.MatchIsEmpty:
|
||||
return doMatchIsEmpty(expression, rvalue)
|
||||
case grammar.MatchIsNotEmpty:
|
||||
result, err := doMatchIsEmpty(expression, rvalue)
|
||||
if err == nil {
|
||||
return !result, nil
|
||||
}
|
||||
return false, err
|
||||
case grammar.MatchMatches:
|
||||
return doMatchMatches(expression, rvalue)
|
||||
case grammar.MatchNotMatches:
|
||||
result, err := doMatchMatches(expression, rvalue)
|
||||
if err == nil {
|
||||
return !result, nil
|
||||
}
|
||||
return false, err
|
||||
default:
|
||||
return false, fmt.Errorf("Invalid match operation: %d", expression.Operator)
|
||||
}
|
||||
}
|
||||
|
||||
func evaluate(ast grammar.Expression, datum interface{}, opt ...Option) (bool, error) {
|
||||
switch node := ast.(type) {
|
||||
case *grammar.UnaryExpression:
|
||||
switch node.Operator {
|
||||
case grammar.UnaryOpNot:
|
||||
result, err := evaluate(node.Operand, datum, opt...)
|
||||
return !result, err
|
||||
}
|
||||
case *grammar.BinaryExpression:
|
||||
switch node.Operator {
|
||||
case grammar.BinaryOpAnd:
|
||||
result, err := evaluate(node.Left, datum, opt...)
|
||||
if err != nil || !result {
|
||||
return result, err
|
||||
}
|
||||
|
||||
return evaluate(node.Right, datum, opt...)
|
||||
|
||||
case grammar.BinaryOpOr:
|
||||
result, err := evaluate(node.Left, datum, opt...)
|
||||
if err != nil || result {
|
||||
return result, err
|
||||
}
|
||||
|
||||
return evaluate(node.Right, datum, opt...)
|
||||
}
|
||||
case *grammar.MatchExpression:
|
||||
return evaluateMatchExpression(node, datum, opt...)
|
||||
}
|
||||
return false, fmt.Errorf("Invalid AST node")
|
||||
}
|
||||
93
vendor/github.com/hashicorp/go-bexpr/filter.go
generated
vendored
Normal file
93
vendor/github.com/hashicorp/go-bexpr/filter.go
generated
vendored
Normal file
@@ -0,0 +1,93 @@
|
||||
package bexpr
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"reflect"
|
||||
)
|
||||
|
||||
type Filter struct {
|
||||
// The underlying boolean expression evaluator
|
||||
evaluator *Evaluator
|
||||
}
|
||||
|
||||
// Creates a filter to operate on the given data type.
|
||||
// The data type passed can be either be a container type (map, slice or array) or the element type.
|
||||
// For example, if you want to filter a []Foo then the data type to pass here is either []Foo or just Foo.
|
||||
// If no expression is provided the nil filter will be returned but is not an error. This is done
|
||||
// to allow for executing the nil filter which is just a no-op
|
||||
func CreateFilter(expression string) (*Filter, error) {
|
||||
if expression == "" {
|
||||
// nil filter
|
||||
return nil, nil
|
||||
}
|
||||
exp, err := CreateEvaluator(expression)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("Failed to create boolean expression evaluator: %v", err)
|
||||
}
|
||||
|
||||
return &Filter{
|
||||
evaluator: exp,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Execute the filter. If called on a nil filter this is a no-op and
|
||||
// will return the original data
|
||||
func (f *Filter) Execute(data interface{}) (interface{}, error) {
|
||||
if f == nil {
|
||||
return data, nil
|
||||
}
|
||||
|
||||
rvalue := reflect.ValueOf(data)
|
||||
rtype := rvalue.Type()
|
||||
|
||||
switch rvalue.Kind() {
|
||||
case reflect.Array:
|
||||
// For arrays we return slices instead of fixed sized arrays
|
||||
rtype = reflect.SliceOf(rtype.Elem())
|
||||
fallthrough
|
||||
case reflect.Slice:
|
||||
newSlice := reflect.MakeSlice(rtype, 0, rvalue.Len())
|
||||
|
||||
for i := 0; i < rvalue.Len(); i++ {
|
||||
item := rvalue.Index(i)
|
||||
if !item.CanInterface() {
|
||||
return nil, fmt.Errorf("Slice/Array value can not be used")
|
||||
}
|
||||
result, err := f.evaluator.Evaluate(item.Interface())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if result {
|
||||
newSlice = reflect.Append(newSlice, item)
|
||||
}
|
||||
}
|
||||
|
||||
return newSlice.Interface(), nil
|
||||
case reflect.Map:
|
||||
newMap := reflect.MakeMap(rtype)
|
||||
|
||||
// TODO (mkeeler) - Update to use a MapRange iterator once Go 1.12 is usable
|
||||
// for all of our products
|
||||
for _, mapKey := range rvalue.MapKeys() {
|
||||
item := rvalue.MapIndex(mapKey)
|
||||
|
||||
if !item.CanInterface() {
|
||||
return nil, fmt.Errorf("Map value cannot be used")
|
||||
}
|
||||
|
||||
result, err := f.evaluator.Evaluate(item.Interface())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if result {
|
||||
newMap.SetMapIndex(mapKey, item)
|
||||
}
|
||||
}
|
||||
|
||||
return newMap.Interface(), nil
|
||||
default:
|
||||
return nil, fmt.Errorf("Only slices, arrays and maps are filterable")
|
||||
}
|
||||
}
|
||||
155
vendor/github.com/hashicorp/go-bexpr/grammar/ast.go
generated
vendored
Normal file
155
vendor/github.com/hashicorp/go-bexpr/grammar/ast.go
generated
vendored
Normal file
@@ -0,0 +1,155 @@
|
||||
package grammar
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// TODO - Probably should make most of what is in here un-exported
|
||||
|
||||
type Expression interface {
|
||||
ExpressionDump(w io.Writer, indent string, level int)
|
||||
}
|
||||
|
||||
type UnaryOperator int
|
||||
|
||||
const (
|
||||
UnaryOpNot UnaryOperator = iota
|
||||
)
|
||||
|
||||
func (op UnaryOperator) String() string {
|
||||
switch op {
|
||||
case UnaryOpNot:
|
||||
return "Not"
|
||||
default:
|
||||
return "UNKNOWN"
|
||||
}
|
||||
}
|
||||
|
||||
type BinaryOperator int
|
||||
|
||||
const (
|
||||
BinaryOpAnd BinaryOperator = iota
|
||||
BinaryOpOr
|
||||
)
|
||||
|
||||
func (op BinaryOperator) String() string {
|
||||
switch op {
|
||||
case BinaryOpAnd:
|
||||
return "And"
|
||||
case BinaryOpOr:
|
||||
return "Or"
|
||||
default:
|
||||
return "UNKNOWN"
|
||||
}
|
||||
}
|
||||
|
||||
type MatchOperator int
|
||||
|
||||
const (
|
||||
MatchEqual MatchOperator = iota
|
||||
MatchNotEqual
|
||||
MatchIn
|
||||
MatchNotIn
|
||||
MatchIsEmpty
|
||||
MatchIsNotEmpty
|
||||
MatchMatches
|
||||
MatchNotMatches
|
||||
)
|
||||
|
||||
func (op MatchOperator) String() string {
|
||||
switch op {
|
||||
case MatchEqual:
|
||||
return "Equal"
|
||||
case MatchNotEqual:
|
||||
return "Not Equal"
|
||||
case MatchIn:
|
||||
return "In"
|
||||
case MatchNotIn:
|
||||
return "Not In"
|
||||
case MatchIsEmpty:
|
||||
return "Is Empty"
|
||||
case MatchIsNotEmpty:
|
||||
return "Is Not Empty"
|
||||
case MatchMatches:
|
||||
return "Matches"
|
||||
case MatchNotMatches:
|
||||
return "Not Matches"
|
||||
default:
|
||||
return "UNKNOWN"
|
||||
}
|
||||
}
|
||||
|
||||
type MatchValue struct {
|
||||
Raw string
|
||||
Converted interface{}
|
||||
}
|
||||
|
||||
type UnaryExpression struct {
|
||||
Operator UnaryOperator
|
||||
Operand Expression
|
||||
}
|
||||
|
||||
type BinaryExpression struct {
|
||||
Left Expression
|
||||
Operator BinaryOperator
|
||||
Right Expression
|
||||
}
|
||||
|
||||
type SelectorType uint32
|
||||
|
||||
const (
|
||||
SelectorTypeUnknown = iota
|
||||
SelectorTypeBexpr
|
||||
SelectorTypeJsonPointer
|
||||
)
|
||||
|
||||
type Selector struct {
|
||||
Type SelectorType
|
||||
Path []string
|
||||
}
|
||||
|
||||
func (sel Selector) String() string {
|
||||
if len(sel.Path) == 0 {
|
||||
return ""
|
||||
}
|
||||
switch sel.Type {
|
||||
case SelectorTypeBexpr:
|
||||
return strings.Join(sel.Path, ".")
|
||||
case SelectorTypeJsonPointer:
|
||||
return strings.Join(sel.Path, "/")
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
}
|
||||
|
||||
type MatchExpression struct {
|
||||
Selector Selector
|
||||
Operator MatchOperator
|
||||
Value *MatchValue
|
||||
}
|
||||
|
||||
func (expr *UnaryExpression) ExpressionDump(w io.Writer, indent string, level int) {
|
||||
localIndent := strings.Repeat(indent, level)
|
||||
fmt.Fprintf(w, "%s%s {\n", localIndent, expr.Operator.String())
|
||||
expr.Operand.ExpressionDump(w, indent, level+1)
|
||||
fmt.Fprintf(w, "%s}\n", localIndent)
|
||||
}
|
||||
|
||||
func (expr *BinaryExpression) ExpressionDump(w io.Writer, indent string, level int) {
|
||||
localIndent := strings.Repeat(indent, level)
|
||||
fmt.Fprintf(w, "%s%s {\n", localIndent, expr.Operator.String())
|
||||
expr.Left.ExpressionDump(w, indent, level+1)
|
||||
expr.Right.ExpressionDump(w, indent, level+1)
|
||||
fmt.Fprintf(w, "%s}\n", localIndent)
|
||||
}
|
||||
|
||||
func (expr *MatchExpression) ExpressionDump(w io.Writer, indent string, level int) {
|
||||
switch expr.Operator {
|
||||
case MatchEqual, MatchNotEqual, MatchIn, MatchNotIn:
|
||||
fmt.Fprintf(w, "%[1]s%[3]s {\n%[2]sSelector: %[4]v\n%[2]sValue: %[5]q\n%[1]s}\n", strings.Repeat(indent, level), strings.Repeat(indent, level+1), expr.Operator.String(), expr.Selector, expr.Value.Raw)
|
||||
default:
|
||||
fmt.Fprintf(w, "%[1]s%[3]s {\n%[2]sSelector: %[4]v\n%[1]s}\n", strings.Repeat(indent, level), strings.Repeat(indent, level+1), expr.Operator.String(), expr.Selector)
|
||||
}
|
||||
}
|
||||
3107
vendor/github.com/hashicorp/go-bexpr/grammar/grammar.go
generated
vendored
Normal file
3107
vendor/github.com/hashicorp/go-bexpr/grammar/grammar.go
generated
vendored
Normal file
File diff suppressed because it is too large
Load Diff
193
vendor/github.com/hashicorp/go-bexpr/grammar/grammar.peg
generated
vendored
Normal file
193
vendor/github.com/hashicorp/go-bexpr/grammar/grammar.peg
generated
vendored
Normal file
@@ -0,0 +1,193 @@
|
||||
{
|
||||
package grammar
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/mitchellh/pointerstructure"
|
||||
)
|
||||
}
|
||||
|
||||
Input <- _? "(" _? expr:OrExpression _? ")" _? EOF {
|
||||
return expr, nil
|
||||
} / _? expr:OrExpression _? EOF {
|
||||
return expr, nil
|
||||
}
|
||||
|
||||
OrExpression <- left:AndExpression _ "or" _ right:OrExpression {
|
||||
return &BinaryExpression{
|
||||
Operator: BinaryOpOr,
|
||||
Left: left.(Expression),
|
||||
Right: right.(Expression),
|
||||
}, nil
|
||||
} / expr:AndExpression {
|
||||
return expr, nil
|
||||
}
|
||||
|
||||
AndExpression <- left:NotExpression _ "and" _ right:AndExpression {
|
||||
return &BinaryExpression{
|
||||
Operator: BinaryOpAnd,
|
||||
Left: left.(Expression),
|
||||
Right: right.(Expression),
|
||||
}, nil
|
||||
} / expr:NotExpression {
|
||||
return expr, nil
|
||||
}
|
||||
|
||||
NotExpression <- "not" _ expr:NotExpression {
|
||||
if unary, ok := expr.(*UnaryExpression); ok && unary.Operator == UnaryOpNot {
|
||||
// small optimization to get rid unnecessary levels of AST nodes
|
||||
// for things like: not not foo == 3 which is equivalent to foo == 3
|
||||
return unary.Operand, nil
|
||||
}
|
||||
|
||||
return &UnaryExpression{
|
||||
Operator: UnaryOpNot,
|
||||
Operand: expr.(Expression),
|
||||
}, nil
|
||||
} / expr:ParenthesizedExpression {
|
||||
return expr, nil
|
||||
}
|
||||
|
||||
ParenthesizedExpression "grouping" <- "(" _? expr:OrExpression _? ")" {
|
||||
return expr, nil
|
||||
} / expr:MatchExpression {
|
||||
return expr, nil
|
||||
} / "(" _? OrExpression _? !")" &{
|
||||
return false, errors.New("Unmatched parentheses")
|
||||
}
|
||||
|
||||
MatchExpression "match" <- MatchSelectorOpValue / MatchSelectorOp / MatchValueOpSelector
|
||||
|
||||
MatchSelectorOpValue "match" <- selector:Selector operator:(MatchEqual / MatchNotEqual / MatchContains / MatchNotContains / MatchMatches / MatchNotMatches) value:Value {
|
||||
return &MatchExpression{Selector: selector.(Selector), Operator: operator.(MatchOperator), Value: value.(*MatchValue)}, nil
|
||||
}
|
||||
|
||||
MatchSelectorOp "match" <- selector:Selector operator:(MatchIsEmpty / MatchIsNotEmpty) {
|
||||
return &MatchExpression{Selector: selector.(Selector), Operator: operator.(MatchOperator), Value: nil}, nil
|
||||
}
|
||||
|
||||
MatchValueOpSelector "match" <- value:Value operator:(MatchIn / MatchNotIn) selector:Selector {
|
||||
return &MatchExpression{Selector: selector.(Selector), Operator: operator.(MatchOperator), Value: value.(*MatchValue)}, nil
|
||||
} / Value operator:(MatchIn / MatchNotIn) !Selector &{
|
||||
return false, errors.New("Invalid selector")
|
||||
}
|
||||
|
||||
MatchEqual <- _? "==" _? {
|
||||
return MatchEqual, nil
|
||||
}
|
||||
MatchNotEqual <- _? "!=" _? {
|
||||
return MatchNotEqual, nil
|
||||
}
|
||||
MatchIsEmpty <- _ "is" _ "empty" {
|
||||
return MatchIsEmpty, nil
|
||||
}
|
||||
MatchIsNotEmpty <- _"is" _ "not" _ "empty" {
|
||||
return MatchIsNotEmpty, nil
|
||||
}
|
||||
MatchIn <- _ "in" _ {
|
||||
return MatchIn, nil
|
||||
}
|
||||
MatchNotIn <- _ "not" _ "in" _ {
|
||||
return MatchNotIn, nil
|
||||
}
|
||||
MatchContains <- _ "contains" _ {
|
||||
return MatchIn, nil
|
||||
}
|
||||
MatchNotContains <- _ "not" _ "contains" _ {
|
||||
return MatchNotIn, nil
|
||||
}
|
||||
MatchMatches <- _ "matches" _ {
|
||||
return MatchMatches, nil
|
||||
}
|
||||
MatchNotMatches <- _ "not" _ "matches" _ {
|
||||
return MatchNotMatches, nil
|
||||
}
|
||||
|
||||
Selector "selector" <- first:Identifier rest:SelectorOrIndex* {
|
||||
sel := Selector{
|
||||
Type: SelectorTypeBexpr,
|
||||
Path: []string{first.(string)},
|
||||
}
|
||||
if rest != nil {
|
||||
for _, v := range rest.([]interface{}) {
|
||||
sel.Path = append(sel.Path, v.(string))
|
||||
}
|
||||
}
|
||||
return sel, nil
|
||||
} / '"' ptrsegs:JsonPointerSegment* '"' {
|
||||
sel := Selector{
|
||||
Type: SelectorTypeJsonPointer,
|
||||
}
|
||||
if ptrsegs != nil {
|
||||
for _, v := range ptrsegs.([]interface{}) {
|
||||
sel.Path = append(sel.Path, v.(string))
|
||||
}
|
||||
}
|
||||
|
||||
// Validate and cache
|
||||
ptrStr := fmt.Sprintf("/%s", strings.Join(sel.Path, "/"))
|
||||
ptr, err := pointerstructure.Parse(ptrStr)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("error validating json pointer: %w", err)
|
||||
}
|
||||
sel.Path = ptr.Parts
|
||||
|
||||
return sel, nil
|
||||
}
|
||||
|
||||
JsonPointerSegment <- '/' ident:[\pL\pN-_.~:|]+ {
|
||||
return string(c.text)[1:], nil
|
||||
}
|
||||
|
||||
Identifier <- [a-zA-Z] [a-zA-Z0-9_/]* {
|
||||
return string(c.text), nil
|
||||
}
|
||||
|
||||
SelectorOrIndex <- "." ident:Identifier {
|
||||
return ident, nil
|
||||
} / expr:IndexExpression {
|
||||
return expr, nil
|
||||
} / "." idx:[0-9]+ {
|
||||
return string(c.text)[1:], nil
|
||||
}
|
||||
|
||||
IndexExpression "index" <- "[" _? lit:StringLiteral _? "]" {
|
||||
return lit, nil
|
||||
} / "[" _? !StringLiteral &{
|
||||
return false, errors.New("Invalid index")
|
||||
} / "[" _? StringLiteral _? !"]" &{
|
||||
return false, errors.New("Unclosed index expression")
|
||||
}
|
||||
|
||||
Value "value" <- selector:Selector {
|
||||
return &MatchValue{Raw:selector.(Selector).String()}, nil
|
||||
} / n:NumberLiteral {
|
||||
return &MatchValue{Raw: n.(string)}, nil
|
||||
} / s:StringLiteral {
|
||||
return &MatchValue{Raw: s.(string)}, nil
|
||||
}
|
||||
|
||||
NumberLiteral "number" <- "-"? IntegerOrFloat &AfterNumbers {
|
||||
return string(c.text), nil
|
||||
} / "-"? IntegerOrFloat !AfterNumbers &{
|
||||
return false, errors.New("Invalid number literal")
|
||||
}
|
||||
|
||||
AfterNumbers <- &(_ / EOF / ")")
|
||||
|
||||
IntegerOrFloat <- ("0" / [1-9][0-9]*) ("." [0-9]+)?
|
||||
|
||||
StringLiteral "string" <- ('`' RawStringChar* '`' / '"' DoubleStringChar* '"') {
|
||||
return strconv.Unquote(string(c.text))
|
||||
} / ('`' RawStringChar* / '"' DoubleStringChar*) EOF &{
|
||||
return false, errors.New("Unterminated string literal")
|
||||
}
|
||||
|
||||
RawStringChar <- !'`' .
|
||||
DoubleStringChar <- !'"' .
|
||||
|
||||
_ "whitespace" <- [ \t\r\n]+
|
||||
|
||||
EOF <- !.
|
||||
52
vendor/github.com/hashicorp/go-bexpr/options.go
generated
vendored
Normal file
52
vendor/github.com/hashicorp/go-bexpr/options.go
generated
vendored
Normal file
@@ -0,0 +1,52 @@
|
||||
package bexpr
|
||||
|
||||
// getOpts - iterate the inbound Options and return a struct
|
||||
func getOpts(opt ...Option) options {
|
||||
opts := getDefaultOptions()
|
||||
for _, o := range opt {
|
||||
if o != nil {
|
||||
o(&opts)
|
||||
}
|
||||
}
|
||||
return opts
|
||||
}
|
||||
|
||||
// Option - how Options are passed as arguments
|
||||
type Option func(*options)
|
||||
|
||||
// options = how options are represented
|
||||
type options struct {
|
||||
withMaxExpressions uint64
|
||||
withTagName string
|
||||
withHookFn ValueTransformationHookFn
|
||||
}
|
||||
|
||||
func WithMaxExpressions(maxExprCnt uint64) Option {
|
||||
return func(o *options) {
|
||||
o.withMaxExpressions = maxExprCnt
|
||||
}
|
||||
}
|
||||
|
||||
// WithTagName indictes what tag to use instead of the default "bexpr"
|
||||
func WithTagName(tagName string) Option {
|
||||
return func(o *options) {
|
||||
o.withTagName = tagName
|
||||
}
|
||||
}
|
||||
|
||||
// WithHookFn sets a HookFn to be called on the Go data under evaluation
|
||||
// and all subfields, indexes, and values recursively. That makes it
|
||||
// easier for the JSON Pointer to not match exactly the Go value being
|
||||
// evaluated (for example, when using protocol buffers' well-known types).
|
||||
func WithHookFn(fn ValueTransformationHookFn) Option {
|
||||
return func(o *options) {
|
||||
o.withHookFn = fn
|
||||
}
|
||||
}
|
||||
|
||||
func getDefaultOptions() options {
|
||||
return options{
|
||||
withMaxExpressions: 0,
|
||||
withTagName: "bexpr",
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user