github.com/inspektor-gadget/inspektor-gadget@v0.28.1/pkg/columns/templates.go (about)

     1  // Copyright 2022 The Inspektor Gadget authors
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package columns
    16  
    17  import (
    18  	"fmt"
    19  	"sync"
    20  )
    21  
    22  var (
    23  	templates    = map[string]string{}
    24  	templateLock sync.Mutex
    25  )
    26  
    27  // RegisterTemplate registers the column settings template in value to name. Whenever a column has "template:name" set,
    28  // this template will be used.  Plausibility and syntax checks will only be applied when the template gets used.
    29  func RegisterTemplate(name, value string) error {
    30  	templateLock.Lock()
    31  	defer templateLock.Unlock()
    32  
    33  	if name == "" {
    34  		return fmt.Errorf("no template name given")
    35  	}
    36  	if value == "" {
    37  		return fmt.Errorf("no value given for template %q", name)
    38  	}
    39  
    40  	if _, ok := templates[name]; ok {
    41  		return fmt.Errorf("template with name %q already exists", name)
    42  	}
    43  
    44  	templates[name] = value
    45  	return nil
    46  }
    47  
    48  // MustRegisterTemplate calls RegisterTemplate and will panic if an error occurs.
    49  func MustRegisterTemplate(name, value string) {
    50  	err := RegisterTemplate(name, value)
    51  	if err != nil {
    52  		panic(err)
    53  	}
    54  }
    55  
    56  // getTemplate returns a template that has previously been registered as name.
    57  func getTemplate(name string) (string, bool) {
    58  	templateLock.Lock()
    59  	defer templateLock.Unlock()
    60  
    61  	tpl, ok := templates[name]
    62  	return tpl, ok
    63  }