Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add flag to include descriptions as comments #25

Open
wants to merge 1 commit into
base: trunk
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
/tfvar
profile.cov
dist/
42 changes: 27 additions & 15 deletions cmd/cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,15 @@ import (
)

const (
flagAutoAssign = "auto-assign"
flagDebug = "debug"
flagEnvVar = "env-var"
flagNoDefault = "ignore-default"
flagResource = "resource"
flagVar = "var"
flagVarFile = "var-file"
flagWorkspace = "workspace"
flagAutoAssign = "auto-assign"
flagDebug = "debug"
flagDescsAsComments = "descs-as-comments"
flagEnvVar = "env-var"
flagNoDefault = "ignore-default"
flagResource = "resource"
flagVar = "var"
flagVarFile = "var-file"
flagWorkspace = "workspace"
)

// New returns a new instance of cobra.Command for tfvar. Usage:
Expand Down Expand Up @@ -50,6 +51,7 @@ one would write it in variable definitions files (.tfvars).
rootCmd.PersistentFlags().BoolP(flagAutoAssign, "a", false, `Use values from environment variables TF_VAR_* and
variable definitions files e.g. terraform.tfvars[.json] *.auto.tfvars[.json]`)
rootCmd.PersistentFlags().BoolP(flagDebug, "d", false, "Print debug log on stderr")
rootCmd.PersistentFlags().BoolP(flagDescsAsComments, "c", false, "Include variable descriptions as comments.")
rootCmd.PersistentFlags().BoolP(flagEnvVar, "e", false, "Print output in export TF_VAR_image_id=ami-abc123 format")
rootCmd.PersistentFlags().BoolP(flagResource, "r", false, "Print output in Terraform Enterprise (tfe) provider's tfe_variable resource format")
rootCmd.PersistentFlags().BoolP(flagWorkspace, "w", false, "Print output variables as payloads for Workspace Variables API")
Expand Down Expand Up @@ -179,21 +181,31 @@ func (r *runner) rootRunE(cmd *cobra.Command, args []string) error {
return err
}

writer := tfvar.WriteAsTFVars
var writer func(w io.Writer, vars []tfvar.Variable) error

if isEnvVar {
r.log.Debug("Print outputs in environment variables format")
writer = tfvar.WriteAsEnvVars
}

if isWorkspace {
} else if isWorkspace {
r.log.Debug("Print outputs in Workspace API payload format")
writer = tfvar.WriteAsWorkspacePayload
}

if isResource {
} else if isResource {
r.log.Debug("Print outputs in tfe_resource format")
writer = tfvar.WriteAsTFEResource
} else {
r.log.Debug("Print outputs in tfvars format")
withComments, err := cmd.PersistentFlags().GetBool(flagDescsAsComments)
if err != nil {
return errors.Wrapf(err, "cmd: get flag --%s", flagDescsAsComments)
}
if withComments {
r.log.Debug("Including comments in tfvars output")
} else {
r.log.Debug("Not including comments in tfvars output")
}
writer = func(w io.Writer, vars []tfvar.Variable) error {
return tfvar.WriteAsTFVars(withComments, w, vars)
}
}
return writer(r.out, vars)
}
28 changes: 27 additions & 1 deletion pkg/tfvar/tfvar.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"encoding/json"
"fmt"
"io"
"strings"

"github.com/cockroachdb/errors"
"github.com/hashicorp/hcl/v2/hclsyntax"
Expand Down Expand Up @@ -101,18 +102,43 @@ func oneliner(original hclwrite.Tokens) hclwrite.Tokens {

// WriteAsTFVars outputs the given vars in Terraform's variable definitions format, e.g.
// region = "ap-northeast-1"
func WriteAsTFVars(w io.Writer, vars []Variable) error {
func WriteAsTFVars(withComments bool, w io.Writer, vars []Variable) error {
f := hclwrite.NewEmptyFile()
rootBody := f.Body()

for _, v := range vars {
if withComments {
comment := strings.TrimSpace(v.Description)
if len(comment) > 0 {
rootBody.AppendUnstructuredTokens(commentToTokens(comment))
}
}
rootBody.SetAttributeValue(v.Name, v.Value)
}

_, err := f.WriteTo(w)
return errors.Wrap(err, "tfvar: failed to write as tfvars")
}

func commentToTokens(comment string) hclwrite.Tokens {
lines := strings.Split(comment, "\n")
newLine := hclwrite.Token{
Type: hclsyntax.TokenNewline,
Bytes: []byte(string(hclsyntax.TokenNewline)),
}

var tokens hclwrite.Tokens
for _, line := range lines {
tokens = append(tokens, &hclwrite.Token{
Type: hclsyntax.TokenComment,
Bytes: []byte(fmt.Sprintf("# %s", line)),
})
tokens = append(tokens, &newLine)
}

return tokens
}

type workspacePayload struct {
Data workspaceData `json:"data"`
}
Expand Down
7 changes: 4 additions & 3 deletions pkg/tfvar/tfvar_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ func TestWriteAsTFVars(t *testing.T) {
sort.Slice(vars, func(i, j int) bool { return vars[i].Name < vars[j].Name })

var buf bytes.Buffer
assert.NoError(t, WriteAsTFVars(&buf, vars))
assert.NoError(t, WriteAsTFVars(true, &buf, vars))

expected := `availability_zone_names = ["us-west-1a"]
aws_amis = {
Expand All @@ -94,8 +94,9 @@ docker_ports = [{
protocol = "tcp"
}]
instance_name = "my-instance"
password = null
region = null
# the root password to use with the database
password = null
region = null
`
assert.Equal(t, expected, buf.String())
}
Expand Down