github.com/choria-io/go-choria@v0.28.1-0.20240416190746-b3bf9c7d5a45/filter/agents/agents.go (about)

     1  // Copyright (c) 2019-2021, R.I. Pienaar and the Choria Project contributors
     2  //
     3  // SPDX-License-Identifier: Apache-2.0
     4  
     5  package agents
     6  
     7  import (
     8  	"regexp"
     9  	"strings"
    10  )
    11  
    12  // Match agents on a AND basis
    13  func Match(needles []string, knownAgents []string) bool {
    14  	matched := 0
    15  	failed := 0
    16  
    17  	for _, needle := range needles {
    18  		if strings.HasPrefix(needle, "/") && strings.HasSuffix(needle, "/") {
    19  			needle = strings.TrimPrefix(needle, "/")
    20  			needle = strings.TrimSuffix(needle, "/")
    21  
    22  			if hasAgentMatching(needle, knownAgents) {
    23  				matched++
    24  			} else {
    25  				failed++
    26  			}
    27  
    28  			continue
    29  		}
    30  
    31  		if hasAgent(needle, knownAgents) {
    32  			matched++
    33  		} else {
    34  			failed++
    35  		}
    36  	}
    37  
    38  	return failed == 0 && matched > 0
    39  }
    40  
    41  func hasAgentMatching(needle string, stack []string) bool {
    42  	for _, agent := range stack {
    43  		if match, _ := regexp.MatchString(needle, agent); match {
    44  			return true
    45  		}
    46  	}
    47  
    48  	return false
    49  }
    50  
    51  func hasAgent(needle string, stack []string) bool {
    52  	for _, agent := range stack {
    53  		if agent == needle {
    54  			return true
    55  		}
    56  	}
    57  
    58  	return false
    59  }