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