Skip to content

Commit

Permalink
Merge pull request #36 from davidovich/24-output-version
Browse files Browse the repository at this point in the history
output version info in json format
  • Loading branch information
davidovich authored May 19, 2019
2 parents 82c7d41 + 6fa90a2 commit bf871a9
Showing 1 changed file with 49 additions and 1 deletion.
50 changes: 49 additions & 1 deletion cmd/root.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
package cmd

import (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"runtime/debug"

"github.com/gobuffalo/packr/v2"
"github.com/spf13/cobra"
Expand All @@ -28,6 +30,7 @@ type mainCmd struct {
// CreateRoot creates the root command
func createRootCmd(driver summon.Interface) *cobra.Command {
cmdName := filepath.Base(os.Args[0])
var showVersion bool

main := &mainCmd{
driver: driver,
Expand All @@ -37,7 +40,7 @@ func createRootCmd(driver summon.Interface) *cobra.Command {
Use: cmdName + " [file to summon]",
Short: cmdName + " main command",
Args: func(cmd *cobra.Command, args []string) error {
if main.copyAll {
if main.copyAll || showVersion {
return nil
}
if len(args) < 1 {
Expand All @@ -50,6 +53,17 @@ func createRootCmd(driver summon.Interface) *cobra.Command {
},
RunE: func(cmd *cobra.Command, args []string) error {
main.out = cmd.OutOrStdout()
if showVersion {
v, ok := makeVersion()
if !ok {
fmt.Fprintln(cmd.OutOrStderr(), "Missing build info")
return nil
}
enc := json.NewEncoder(main.out)
enc.SetIndent("", " ")
enc.Encode(v)
return nil
}
if !main.copyAll {
filename := args[0]
main.filename = filename
Expand Down Expand Up @@ -78,6 +92,7 @@ func createRootCmd(driver summon.Interface) *cobra.Command {
rootCmd.Flags().BoolVarP(&main.copyAll, "all", "a", false, "restitute all data")
rootCmd.Flags().BoolVar(&main.raw, "raw", false, "output without any template rendering")
rootCmd.Flags().StringVarP(&main.dest, "out", "o", config.OutputDir, "destination directory, or '-' for stdout")
rootCmd.Flags().BoolVarP(&showVersion, "version", "v", false, "output data version info and exit")

rootCmd.AddCommand(newListCmd(driver))
rootCmd.AddCommand(newRunCmd(driver))
Expand Down Expand Up @@ -111,3 +126,36 @@ func Execute(box *packr.Box) error {
rootCmd := createRootCmd(s)
return rootCmd.Execute()
}

type versionDesc struct {
Exe string `json:"exe,omitempty"`
Mod string `json:"mod"`
Version string `json:"version"`
}
type versionInfo struct {
Assets versionDesc `json:"assets"`
Lib versionDesc `json:"lib"`
}

func makeVersion() (v versionInfo, ok bool) {
bi, ok := debug.ReadBuildInfo()
if !ok {
return v, false
}
v = versionInfo{
Lib: versionDesc{},
Assets: versionDesc{
Mod: bi.Main.Path,
Version: bi.Main.Version,
Exe: os.Args[0],
},
}
for _, d := range bi.Deps {
if d.Path == "github.com/davidovich/summon" {
v.Lib.Mod = d.Path
v.Lib.Version = d.Version
break
}
}
return v, true
}

0 comments on commit bf871a9

Please sign in to comment.