github.com/opentofu/opentofu@v1.7.1/internal/command/jsonformat/computed/renderers/string.go (about)

     1  // Copyright (c) The OpenTofu Authors
     2  // SPDX-License-Identifier: MPL-2.0
     3  // Copyright (c) 2023 HashiCorp, Inc.
     4  // SPDX-License-Identifier: MPL-2.0
     5  
     6  package renderers
     7  
     8  import (
     9  	"bytes"
    10  	"encoding/json"
    11  	"fmt"
    12  	"strings"
    13  
    14  	"github.com/opentofu/opentofu/internal/command/jsonformat/computed"
    15  )
    16  
    17  type evaluatedString struct {
    18  	String string
    19  	Json   interface{}
    20  
    21  	IsMultiline bool
    22  	IsNull      bool
    23  }
    24  
    25  func evaluatePrimitiveString(value interface{}, opts computed.RenderHumanOpts) evaluatedString {
    26  	if value == nil {
    27  		return evaluatedString{
    28  			String: opts.Colorize.Color("[dark_gray]null[reset]"),
    29  			IsNull: true,
    30  		}
    31  	}
    32  
    33  	str := value.(string)
    34  
    35  	if strings.HasPrefix(str, "{") || strings.HasPrefix(str, "[") {
    36  		var jv interface{}
    37  		decoder := json.NewDecoder(bytes.NewBufferString(str))
    38  		decoder.UseNumber()
    39  		if err := decoder.Decode(&jv); err == nil {
    40  			return evaluatedString{
    41  				String: str,
    42  				Json:   jv,
    43  			}
    44  		}
    45  	}
    46  
    47  	if strings.Contains(str, "\n") {
    48  		return evaluatedString{
    49  			String:      strings.TrimSpace(str),
    50  			IsMultiline: true,
    51  		}
    52  	}
    53  
    54  	return evaluatedString{
    55  		String: str,
    56  	}
    57  }
    58  
    59  func (e evaluatedString) RenderSimple() string {
    60  	if e.IsNull {
    61  		return e.String
    62  	}
    63  	return fmt.Sprintf("%q", e.String)
    64  }