github.com/niedbalski/juju@v0.0.0-20190215020005-8ff100488e47/network/debinterfaces/format.go (about)

     1  // Copyright 2017 Canonical Ltd.
     2  // Licensed under the AGPLv3, see LICENCE file for details.
     3  
     4  package debinterfaces
     5  
     6  import (
     7  	"bytes"
     8  	"strings"
     9  )
    10  
    11  // FlattenStanzas flattens all stanzas, and recursively for all
    12  // 'source' and 'source-directory' stanzas, returning a single slice.
    13  func FlattenStanzas(stanzas []Stanza) []Stanza {
    14  	result := make([]Stanza, 0)
    15  
    16  	for _, s := range stanzas {
    17  		switch v := s.(type) {
    18  		case SourceStanza:
    19  			result = append(result, v.Stanzas...)
    20  		case SourceDirectoryStanza:
    21  			result = append(result, v.Stanzas...)
    22  		default:
    23  			result = append(result, v)
    24  		}
    25  	}
    26  
    27  	return result
    28  }
    29  
    30  // FormatStanzas returns a string representing all stanzas
    31  // definitions, recursively expanding stanzas found in both source and
    32  // source-directory definitions.
    33  func FormatStanzas(stanzas []Stanza, count int) string {
    34  	var buffer bytes.Buffer
    35  
    36  	for i, s := range stanzas {
    37  		buffer.WriteString(FormatDefinition(s.Definition(), count))
    38  		buffer.WriteString("\n")
    39  		// If the current stanza is 'auto' and the next one is
    40  		// 'iface' then don't add an additional blank line
    41  		// between them.
    42  		if _, ok := stanzas[i].(AutoStanza); ok {
    43  			if i+1 < len(stanzas) {
    44  				if _, ok := stanzas[i+1].(IfaceStanza); !ok {
    45  					buffer.WriteString("\n")
    46  				}
    47  			}
    48  		} else if i+1 < len(stanzas) {
    49  			buffer.WriteString("\n")
    50  		}
    51  	}
    52  
    53  	return strings.TrimSuffix(buffer.String(), "\n")
    54  }
    55  
    56  // FormatDefinition formats the complete stanza, indenting any options
    57  // with count leading spaces.
    58  func FormatDefinition(definition []string, count int) string {
    59  	var buffer bytes.Buffer
    60  
    61  	spacer := strings.Repeat(" ", count)
    62  
    63  	for i, d := range definition {
    64  		if i == 0 {
    65  			buffer.WriteString(d)
    66  			buffer.WriteString("\n")
    67  		} else {
    68  			buffer.WriteString(spacer)
    69  			buffer.WriteString(d)
    70  			buffer.WriteString("\n")
    71  		}
    72  	}
    73  
    74  	return strings.TrimSuffix(buffer.String(), "\n")
    75  }