github.com/kubeshop/testkube@v1.17.23/pkg/tcl/expressionstcl/machineutils.go (about)

     1  // Copyright 2024 Testkube.
     2  //
     3  // Licensed as a Testkube Pro file under the Testkube Community
     4  // License (the "License"); you may not use this file except in compliance with
     5  // the License. You may obtain a copy of the License at
     6  //
     7  //     https://github.com/kubeshop/testkube/blob/main/licenses/TCL.txt
     8  
     9  package expressionstcl
    10  
    11  import "strings"
    12  
    13  type limitedMachine struct {
    14  	prefix  string
    15  	machine Machine
    16  }
    17  
    18  func PrefixMachine(prefix string, machine Machine) Machine {
    19  	return &limitedMachine{
    20  		prefix:  prefix,
    21  		machine: machine,
    22  	}
    23  }
    24  
    25  func (m *limitedMachine) Get(name string) (Expression, bool, error) {
    26  	if strings.HasPrefix(name, m.prefix) {
    27  		return m.machine.Get(name)
    28  	}
    29  	return nil, false, nil
    30  }
    31  
    32  func (m *limitedMachine) Call(name string, args ...StaticValue) (Expression, bool, error) {
    33  	if strings.HasPrefix(name, m.prefix) {
    34  		return m.machine.Call(name, args...)
    35  	}
    36  	return nil, false, nil
    37  }
    38  
    39  type combinedMachine struct {
    40  	machines []Machine
    41  }
    42  
    43  func CombinedMachines(machines ...Machine) Machine {
    44  	return &combinedMachine{machines: machines}
    45  }
    46  
    47  func (m *combinedMachine) Get(name string) (Expression, bool, error) {
    48  	for i := range m.machines {
    49  		v, ok, err := m.machines[i].Get(name)
    50  		if err != nil || ok {
    51  			return v, ok, err
    52  		}
    53  	}
    54  	return nil, false, nil
    55  }
    56  
    57  func (m *combinedMachine) Call(name string, args ...StaticValue) (Expression, bool, error) {
    58  	for i := range m.machines {
    59  		v, ok, err := m.machines[i].Call(name, args...)
    60  		if err != nil || ok {
    61  			return v, ok, err
    62  		}
    63  	}
    64  	return nil, false, nil
    65  }
    66  
    67  func ReplacePrefixMachine(from string, to string) Machine {
    68  	return NewMachine().RegisterAccessor(func(name string) (interface{}, bool) {
    69  		if strings.HasPrefix(name, from) {
    70  			return newAccessor(to + name[len(from):]), true
    71  		}
    72  		return nil, false
    73  	})
    74  }