github.com/tomwright/dasel@v1.27.3/condition_more_than.go (about)

     1  package dasel
     2  
     3  import (
     4  	"errors"
     5  	"fmt"
     6  	"reflect"
     7  	"sort"
     8  )
     9  
    10  // SortedComparisonCondition lets you check for an exact match.
    11  type SortedComparisonCondition struct {
    12  	// Key is the key of the value to check against.
    13  	Key string
    14  	// Value is the value we are looking for.
    15  	Value string
    16  	// Equal is true if the values can match.
    17  	Equal bool
    18  	// After is true if the input value should be sorted after the Value.
    19  	After bool
    20  }
    21  
    22  // Check checks to see if other contains the required key value pair.
    23  func (c SortedComparisonCondition) Check(other reflect.Value) (bool, error) {
    24  	if !other.IsValid() {
    25  		return false, &UnhandledCheckType{Value: nil}
    26  	}
    27  
    28  	value := unwrapValue(other)
    29  
    30  	if c.Key == "value" || c.Key == "." {
    31  		return fmt.Sprint(value.Interface()) == c.Value, nil
    32  	}
    33  
    34  	subRootNode := New(value.Interface())
    35  	foundNode, err := subRootNode.Query(c.Key)
    36  	if err != nil {
    37  		var valueNotFound = &ValueNotFound{}
    38  		if errors.As(err, &valueNotFound) {
    39  			return false, nil
    40  		}
    41  
    42  		return false, fmt.Errorf("subquery failed: %w", err)
    43  	}
    44  
    45  	foundValueStr := fmt.Sprint(foundNode.InterfaceValue())
    46  
    47  	// Check if the values are equal
    48  	if foundValueStr == c.Value {
    49  		return c.Equal, nil
    50  	}
    51  
    52  	sortedVals := []string{foundValueStr, c.Value}
    53  	sort.Strings(sortedVals)
    54  
    55  	if !c.After && sortedVals[1] == c.Value {
    56  		return true, nil
    57  	} else if c.After && sortedVals[0] == c.Value {
    58  		return true, nil
    59  	}
    60  
    61  	return false, nil
    62  }