github.com/makyo/juju@v0.0.0-20160425123129-2608902037e9/cmd/juju/storage/poollistformatters.go (about)

     1  package storage
     2  
     3  import (
     4  	"bytes"
     5  	"fmt"
     6  	"sort"
     7  	"strings"
     8  	"text/tabwriter"
     9  
    10  	"github.com/juju/errors"
    11  )
    12  
    13  // formatPoolListTabular returns a tabular summary of pool instances or
    14  // errors out if parameter is not a map of PoolInfo.
    15  func formatPoolListTabular(value interface{}) ([]byte, error) {
    16  	pools, ok := value.(map[string]PoolInfo)
    17  	if !ok {
    18  		return nil, errors.Errorf("expected value of type %T, got %T", pools, value)
    19  	}
    20  	return formatPoolsTabular(pools)
    21  }
    22  
    23  // formatPoolsTabular returns a tabular summary of pool instances.
    24  func formatPoolsTabular(pools map[string]PoolInfo) ([]byte, error) {
    25  	var out bytes.Buffer
    26  	const (
    27  		// To format things into columns.
    28  		minwidth = 0
    29  		tabwidth = 1
    30  		padding  = 2
    31  		padchar  = ' '
    32  		flags    = 0
    33  	)
    34  	tw := tabwriter.NewWriter(&out, minwidth, tabwidth, padding, padchar, flags)
    35  	print := func(values ...string) {
    36  		fmt.Fprintln(tw, strings.Join(values, "\t"))
    37  	}
    38  
    39  	print("NAME", "PROVIDER", "ATTRS")
    40  
    41  	poolNames := make([]string, 0, len(pools))
    42  	for name := range pools {
    43  		poolNames = append(poolNames, name)
    44  	}
    45  	sort.Strings(poolNames)
    46  	for _, name := range poolNames {
    47  		pool := pools[name]
    48  		// order by key for deterministic return
    49  		keys := make([]string, 0, len(pool.Attrs))
    50  		for key := range pool.Attrs {
    51  			keys = append(keys, key)
    52  		}
    53  		sort.Strings(keys)
    54  		attrs := make([]string, len(pool.Attrs))
    55  		for i, key := range keys {
    56  			attrs[i] = fmt.Sprintf("%v=%v", key, pool.Attrs[key])
    57  		}
    58  		print(name, pool.Provider, strings.Join(attrs, " "))
    59  	}
    60  	tw.Flush()
    61  
    62  	return out.Bytes(), nil
    63  }