github.com/makyo/juju@v0.0.0-20160425123129-2608902037e9/payload/status/output_tabular.go (about)

     1  // Copyright 2015 Canonical Ltd.
     2  // Licensed under the AGPLv3, see LICENCE file for details.
     3  
     4  package status
     5  
     6  import (
     7  	"bytes"
     8  	"fmt"
     9  	"strings"
    10  	"text/tabwriter"
    11  
    12  	"github.com/juju/errors"
    13  )
    14  
    15  const tabularSection = "[Unit Payloads]"
    16  
    17  var (
    18  	tabularColumns = []string{
    19  		"UNIT",
    20  		"MACHINE",
    21  		"PAYLOAD-CLASS",
    22  		"STATUS",
    23  		"TYPE",
    24  		"ID",
    25  		"TAGS", // TODO(ericsnow) Chane this to "LABELS"?
    26  	}
    27  
    28  	tabularHeader = strings.Join(tabularColumns, "\t") + "\t"
    29  	tabularRow    = strings.Repeat("%s\t", len(tabularColumns))
    30  )
    31  
    32  // FormatTabular returns a tabular summary of payloads.
    33  func FormatTabular(value interface{}) ([]byte, error) {
    34  	payloads, valueConverted := value.([]FormattedPayload)
    35  	if !valueConverted {
    36  		return nil, errors.Errorf("expected value of type %T, got %T", payloads, value)
    37  	}
    38  
    39  	// TODO(ericsnow) sort the rows first?
    40  
    41  	var out bytes.Buffer
    42  	// To format things into columns.
    43  	tw := tabwriter.NewWriter(&out, 0, 1, 1, ' ', 0)
    44  
    45  	// Write the header.
    46  	fmt.Fprintln(tw, tabularSection)
    47  	fmt.Fprintln(tw, tabularHeader)
    48  
    49  	// Print each payload to its own row.
    50  	for _, payload := range payloads {
    51  		// tabularColumns must be kept in sync with these.
    52  		fmt.Fprintf(tw, tabularRow+"\n",
    53  			payload.Unit,
    54  			payload.Machine,
    55  			payload.Class,
    56  			payload.Status,
    57  			payload.Type,
    58  			payload.ID,
    59  			strings.Join(payload.Labels, " "),
    60  		)
    61  	}
    62  	tw.Flush()
    63  
    64  	return out.Bytes(), nil
    65  }