github.com/docker/app@v0.9.1-beta3.0.20210611140623-a48f773ab002/internal/formatter/formatter.go (about)

     1  package formatter
     2  
     3  import (
     4  	"sort"
     5  	"sync"
     6  
     7  	"github.com/docker/app/internal/formatter/driver"
     8  	composetypes "github.com/docker/cli/cli/compose/types"
     9  	"github.com/pkg/errors"
    10  )
    11  
    12  var (
    13  	driversMu sync.RWMutex
    14  	drivers   = map[string]driver.Driver{}
    15  )
    16  
    17  // Register makes a formatter available by the provided name.
    18  // If Register is called twice with the same name or if driver is nil,
    19  // it panics.
    20  func Register(name string, driver driver.Driver) {
    21  	driversMu.Lock()
    22  	defer driversMu.Unlock()
    23  	if driver == nil {
    24  		panic("formatter: Register driver is nil")
    25  	}
    26  	if _, dup := drivers[name]; dup {
    27  		panic("formatter: Register called twice for driver " + name)
    28  	}
    29  	drivers[name] = driver
    30  }
    31  
    32  // Format uses the specified formatter to create a printable output.
    33  // If the formatter is not registered, this errors out.
    34  func Format(config *composetypes.Config, formatter string) (string, error) {
    35  	driversMu.RLock()
    36  	d, ok := drivers[formatter]
    37  	driversMu.RUnlock()
    38  	if !ok {
    39  		return "", errors.Errorf("unknown formatter %q", formatter)
    40  	}
    41  	s, err := d.Format(config)
    42  	if err != nil {
    43  		return "", err
    44  	}
    45  	return s, nil
    46  }
    47  
    48  // Drivers returns a sorted list of the names of the registered drivers.
    49  func Drivers() []string {
    50  	list := []string{}
    51  	driversMu.RLock()
    52  	for name := range drivers {
    53  		list = append(list, name)
    54  	}
    55  	driversMu.RUnlock()
    56  	sort.Strings(list)
    57  	return list
    58  }