github.com/zntrio/harp/v2@v2.0.9/pkg/bundle/selector/match_jmespath.go (about)

     1  // Licensed to Elasticsearch B.V. under one or more contributor
     2  // license agreements. See the NOTICE file distributed with
     3  // this work for additional information regarding copyright
     4  // ownership. Elasticsearch B.V. licenses this file to you under
     5  // the Apache License, Version 2.0 (the "License"); you may
     6  // not use this file except in compliance with the License.
     7  // You may obtain a copy of the License at
     8  //
     9  //     http://www.apache.org/licenses/LICENSE-2.0
    10  //
    11  // Unless required by applicable law or agreed to in writing,
    12  // software distributed under the License is distributed on an
    13  // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    14  // KIND, either express or implied.  See the License for the
    15  // specific language governing permissions and limitations
    16  // under the License.
    17  
    18  package selector
    19  
    20  import (
    21  	"encoding/json"
    22  
    23  	"github.com/jmespath/go-jmespath"
    24  	"google.golang.org/protobuf/encoding/protojson"
    25  
    26  	bundlev1 "github.com/zntrio/harp/v2/api/gen/go/harp/bundle/v1"
    27  )
    28  
    29  // MatchJMESPath returns a JMESPatch package matcher specification.
    30  func MatchJMESPath(exp *jmespath.JMESPath) Specification {
    31  	return &jmesPathMatcher{
    32  		exp: exp,
    33  	}
    34  }
    35  
    36  type jmesPathMatcher struct {
    37  	exp *jmespath.JMESPath
    38  }
    39  
    40  // IsSatisfiedBy returns specification satisfaction status.
    41  func (s *jmesPathMatcher) IsSatisfiedBy(object interface{}) bool {
    42  	// If object is a package
    43  	if p, ok := object.(*bundlev1.Package); ok {
    44  		// Eliminate all package in case of nil query.
    45  		if s.exp == nil {
    46  			return false
    47  		}
    48  
    49  		// Rencode as json
    50  		jsonRaw, err := protojson.Marshal(p)
    51  		if err != nil {
    52  			return false
    53  		}
    54  
    55  		var object map[string]interface{}
    56  		if errJSON := json.Unmarshal(jsonRaw, &object); errJSON != nil {
    57  			return false
    58  		}
    59  
    60  		// Check if query match results
    61  		res, err := s.exp.Search(object)
    62  		if err != nil {
    63  			return false
    64  		}
    65  
    66  		// If result is a boolean
    67  		if bRes, ok := res.(bool); ok {
    68  			return bRes
    69  		}
    70  	}
    71  
    72  	return false
    73  }