github.com/mhilton/juju-juju@v0.0.0-20150901100907-a94dd2c73455/cmd/juju/status/output_oneline.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  
    11  	"github.com/juju/errors"
    12  	"github.com/juju/juju/cmd/juju/common"
    13  )
    14  
    15  // FormatOneline returns a brief list of units and their subordinates.
    16  // Subordinates will be indented 2 spaces and listed under their
    17  // superiors.
    18  func FormatOneline(value interface{}) ([]byte, error) {
    19  	return formatOneline(value, func(out *bytes.Buffer, format, uName string, u unitStatus, level int) {
    20  		fmt.Fprintf(out, format,
    21  			uName,
    22  			u.PublicAddress,
    23  			u.AgentState,
    24  		)
    25  	})
    26  }
    27  
    28  // FormatOnelineV2 returns a brief list of units and their subordinates.
    29  // Subordinates will be indented 2 spaces and listed under their
    30  // superiors. This format works with version 2 of the CLI.
    31  func FormatOnelineV2(value interface{}) ([]byte, error) {
    32  	return formatOneline(value, func(out *bytes.Buffer, format, uName string, u unitStatus, level int) {
    33  		status := fmt.Sprintf(
    34  			"agent:%s, workload:%s",
    35  			u.AgentStatusInfo.Current,
    36  			u.WorkloadStatusInfo.Current,
    37  		)
    38  		fmt.Fprintf(out, format,
    39  			uName,
    40  			u.PublicAddress,
    41  			status,
    42  		)
    43  	})
    44  }
    45  
    46  type onelinePrintf func(out *bytes.Buffer, format, uName string, u unitStatus, level int)
    47  
    48  func formatOneline(value interface{}, printf onelinePrintf) ([]byte, error) {
    49  	fs, valueConverted := value.(formattedStatus)
    50  	if !valueConverted {
    51  		return nil, errors.Errorf("expected value of type %T, got %T", fs, value)
    52  	}
    53  	var out bytes.Buffer
    54  
    55  	pprint := func(uName string, u unitStatus, level int) {
    56  		var fmtPorts string
    57  		if len(u.OpenedPorts) > 0 {
    58  			fmtPorts = fmt.Sprintf(" %s", strings.Join(u.OpenedPorts, ", "))
    59  		}
    60  		format := indent("\n", level*2, "- %s: %s (%v)"+fmtPorts)
    61  		printf(&out, format, uName, u, level)
    62  	}
    63  
    64  	for _, svcName := range common.SortStringsNaturally(stringKeysFromMap(fs.Services)) {
    65  		svc := fs.Services[svcName]
    66  		for _, uName := range common.SortStringsNaturally(stringKeysFromMap(svc.Units)) {
    67  			unit := svc.Units[uName]
    68  			pprint(uName, unit, 0)
    69  			recurseUnits(unit, 1, pprint)
    70  		}
    71  	}
    72  
    73  	return out.Bytes(), nil
    74  }