github.com/StackExchange/blackbox/v2@v2.0.1-0.20220331193400-d84e904973ab/pkg/crypters/crypters.go (about)

     1  package crypters
     2  
     3  import (
     4  	"sort"
     5  	"strings"
     6  
     7  	"github.com/StackExchange/blackbox/v2/models"
     8  )
     9  
    10  // Crypter is the handle
    11  type Crypter interface {
    12  	models.Crypter
    13  }
    14  
    15  // NewFnSig function signature needed by reg.
    16  type NewFnSig func(debug bool) (Crypter, error)
    17  
    18  // Item stores one item
    19  type Item struct {
    20  	Name     string
    21  	New      NewFnSig
    22  	Priority int
    23  }
    24  
    25  // Catalog is the list of registered vcs's.
    26  var Catalog []*Item
    27  
    28  // SearchByName returns a Crypter handle for name.
    29  // The search is case insensitive.
    30  func SearchByName(name string, debug bool) Crypter {
    31  	name = strings.ToLower(name)
    32  	for _, v := range Catalog {
    33  		//fmt.Printf("Trying %v %v\n", v.Name)
    34  		if strings.ToLower(v.Name) == name {
    35  			chandle, err := v.New(debug)
    36  			if err != nil {
    37  				return nil // No idea how that would happen.
    38  			}
    39  			//fmt.Printf("USING! %v\n", v.Name)
    40  			return chandle
    41  		}
    42  	}
    43  	return nil
    44  }
    45  
    46  // Register a new VCS.
    47  func Register(name string, priority int, newfn NewFnSig) {
    48  	//fmt.Printf("CRYPTER registered: %v\n", name)
    49  	item := &Item{
    50  		Name:     name,
    51  		New:      newfn,
    52  		Priority: priority,
    53  	}
    54  	Catalog = append(Catalog, item)
    55  
    56  	// Keep the list sorted.
    57  	sort.Slice(Catalog, func(i, j int) bool { return Catalog[j].Priority < Catalog[i].Priority })
    58  }