github.com/grailbio/base@v0.0.11/cmdutil/version.go (about)

     1  // Copyright 2018 GRAIL, Inc. All rights reserved.
     2  // Use of this source code is governed by the Apache-2.0
     3  // license that can be found in the LICENSE file.
     4  
     5  package cmdutil
     6  
     7  import (
     8  	"fmt"
     9  	"runtime"
    10  
    11  	"v.io/v23/context"
    12  	"v.io/x/lib/cmdline"
    13  	"v.io/x/ref/lib/v23cmd"
    14  )
    15  
    16  var (
    17  	version = "(missing)"
    18  	tags    = ""
    19  )
    20  
    21  func init() {
    22  	s := fmt.Sprintf("os=%s; arch=%s; %s", runtime.GOOS, runtime.GOARCH, runtime.Version())
    23  	if tags == "" {
    24  		tags = s
    25  		return
    26  	}
    27  
    28  	tags = tags + "; " + s
    29  }
    30  
    31  func printVersion(prefix string) {
    32  	fmt.Printf("%s/%v (%v)\n", prefix, version, tags)
    33  }
    34  
    35  // CreateVersionCommand creates a cmdline 'subcommand' to display version
    36  // information.
    37  //
    38  // The format of the information printed is:
    39  //
    40  //    <prefix>/<version> (<tag1>; <tag2>; ...)
    41  //
    42  // The version and tags are set at build time using something like:
    43  //
    44  //    go build -ldflags \
    45  //     "-X github.com/grailbio/base/cmdutil.version=$version \
    46  //      -X github.com/grailbio/base/cmdutil.tags=$tags"
    47  func CreateVersionCommand(name, prefix string) *cmdline.Command {
    48  	return &cmdline.Command{
    49  		Runner: RunnerFunc(func(_ *cmdline.Env, _ []string) error {
    50  			printVersion(prefix)
    51  			return nil
    52  		}),
    53  		Name:  name,
    54  		Short: "Display version information",
    55  	}
    56  }
    57  
    58  // CreateInfoCommand creates a command akin to that created by
    59  // CreatedVersionCommand but also includes the output of running each of
    60  // the supplied info closures.
    61  func CreateInfoCommand(name, prefix string, info ...func(*context.T, *cmdline.Env, []string) error) *cmdline.Command {
    62  	return &cmdline.Command{
    63  		Runner: v23cmd.RunnerFunc(func(ctx *context.T, env *cmdline.Env, args []string) error {
    64  			printVersion(prefix)
    65  			for _, ifn := range info {
    66  				if err := ifn(ctx, env, args); err != nil {
    67  					return err
    68  				}
    69  			}
    70  			return nil
    71  		}),
    72  		Name:  name,
    73  		Short: "Display version information",
    74  	}
    75  }