github.com/hairyhenderson/templater@v3.5.0+incompatible/funcs/uuid.go (about)

     1  package funcs
     2  
     3  import (
     4  	"sync"
     5  
     6  	"github.com/hairyhenderson/gomplate/conv"
     7  
     8  	"github.com/google/uuid"
     9  )
    10  
    11  var (
    12  	uuidNS     *UUIDFuncs
    13  	uuidNSInit sync.Once
    14  )
    15  
    16  // UUIDNS -
    17  func UUIDNS() *UUIDFuncs {
    18  	uuidNSInit.Do(func() {
    19  		uuidNS = &UUIDFuncs{}
    20  	})
    21  	return uuidNS
    22  }
    23  
    24  // AddUUIDFuncs -
    25  func AddUUIDFuncs(f map[string]interface{}) {
    26  	f["uuid"] = UUIDNS
    27  }
    28  
    29  // UUIDFuncs -
    30  type UUIDFuncs struct{}
    31  
    32  // V1 - return a version 1 UUID (based on the current MAC Address and the
    33  // current date/time). Use V4 instead in most cases.
    34  func (f *UUIDFuncs) V1() (string, error) {
    35  	u, err := uuid.NewUUID()
    36  	if err != nil {
    37  		return "", err
    38  	}
    39  	return u.String(), nil
    40  }
    41  
    42  // V4 - return a version 4 (random) UUID
    43  func (f *UUIDFuncs) V4() (string, error) {
    44  	u, err := uuid.NewRandom()
    45  	if err != nil {
    46  		return "", err
    47  	}
    48  	return u.String(), nil
    49  }
    50  
    51  // Nil -
    52  func (f *UUIDFuncs) Nil() (string, error) {
    53  	return uuid.Nil.String(), nil
    54  }
    55  
    56  // IsValid - checks if the given UUID is in the correct format. It does not
    57  // validate whether the version or variant are correct.
    58  func (f *UUIDFuncs) IsValid(in interface{}) (bool, error) {
    59  	_, err := f.Parse(in)
    60  	return err == nil, nil
    61  }
    62  
    63  // Parse - parse a UUID for further manipulation or inspection.
    64  //
    65  // Both the standard UUID forms of xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx and
    66  // urn:uuid:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx are decoded as well as the
    67  // Microsoft encoding {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx} and the raw hex
    68  // encoding: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.
    69  func (f *UUIDFuncs) Parse(in interface{}) (uuid.UUID, error) {
    70  	u, err := uuid.Parse(conv.ToString(in))
    71  	if err != nil {
    72  		return uuid.Nil, err
    73  	}
    74  	return u, err
    75  }