Skip to content

Commit

Permalink
cmd: Introduce version JSON output (hashicorp#386)
Browse files Browse the repository at this point in the history
  • Loading branch information
radeksimko authored Jan 29, 2021
1 parent 19fcbf2 commit 1176437
Show file tree
Hide file tree
Showing 2 changed files with 74 additions and 0 deletions.
68 changes: 68 additions & 0 deletions internal/cmd/version_command.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
package cmd

import (
"encoding/json"
"flag"
"fmt"
"strings"

"github.com/mitchellh/cli"
)

type VersionOutput struct {
Version string `json:"version"`
}

type VersionCommand struct {
Ui cli.Ui
Version string

jsonOutput bool
}

func (c *VersionCommand) flags() *flag.FlagSet {
fs := defaultFlagSet("version")

fs.BoolVar(&c.jsonOutput, "json", false, "output the version information as a JSON object")

fs.Usage = func() { c.Ui.Error(c.Help()) }

return fs
}

func (c *VersionCommand) Run(args []string) int {
f := c.flags()
if err := f.Parse(args); err != nil {
c.Ui.Error(fmt.Sprintf("Error parsing command-line flags: %s", err))
return 1
}

if c.jsonOutput {
output := VersionOutput{
Version: c.Version,
}
jsonOutput, err := json.MarshalIndent(output, "", " ")
if err != nil {
c.Ui.Error(fmt.Sprintf("\nError marshalling JSON: %s", err))
return 1
}
c.Ui.Output(string(jsonOutput))
return 0
}

c.Ui.Output(string(c.Version))
return 0
}

func (c *VersionCommand) Help() string {
helpText := `
Usage: terraform-ls version [-json]
` + c.Synopsis() + "\n\n" + helpForFlags(c.flags())

return strings.TrimSpace(helpText)
}

func (c *VersionCommand) Synopsis() string {
return "Displays the version of the language server"
}
6 changes: 6 additions & 0 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,12 @@ func main() {
Ui: ui,
}, nil
},
"version": func() (cli.Command, error) {
return &cmd.VersionCommand{
Ui: ui,
Version: VersionString(),
}, nil
},
}

exitStatus, err := c.Run()
Expand Down

0 comments on commit 1176437

Please sign in to comment.