github.com/gsquire/gb@v0.4.4-0.20161112235727-3982dc872064/cmd/gb/info.go (about)

     1  package main
     2  
     3  import (
     4  	"fmt"
     5  	"path/filepath"
     6  	"runtime"
     7  	"strings"
     8  
     9  	"github.com/constabulary/gb"
    10  	"github.com/constabulary/gb/cmd"
    11  )
    12  
    13  func init() {
    14  	registerCommand(&cmd.Command{
    15  		Name:      "info",
    16  		UsageLine: `info [var ...]`,
    17  		Short:     "info returns information about this project",
    18  		Long: `
    19  info prints gb environment information.
    20  
    21  Values:
    22  
    23  	GB_PROJECT_DIR
    24  		The root of the gb project.
    25  	GB_SRC_PATH
    26  		The list of gb project source directories.
    27  	GB_PKG_DIR
    28  		The path of the gb project's package cache.
    29  	GB_BIN_SUFFIX
    30  		The suffix applied any binary written to $GB_PROJECT_DIR/bin
    31  	GB_GOROOT
    32  		The value of runtime.GOROOT for the Go version that built this copy of gb.
    33  
    34  info returns 0 if the project is well formed, and non zero otherwise.
    35  If one or more variable names is given as arguments, info prints the 
    36  value of each named variable on its own line.
    37  `,
    38  		Run:           info,
    39  		SkipParseArgs: true,
    40  		AddFlags:      addBuildFlags,
    41  	})
    42  }
    43  
    44  func info(ctx *gb.Context, args []string) error {
    45  	env := makeenv(ctx)
    46  	// print values for env variables when args are provided
    47  	if len(args) > 0 {
    48  		for _, arg := range args {
    49  			// print each var on its own line, blank line for each invalid variables
    50  			fmt.Println(findenv(env, arg))
    51  		}
    52  		return nil
    53  	}
    54  	// print all variable when no args are provided
    55  	for _, v := range env {
    56  		fmt.Printf("%s=\"%s\"\n", v.name, v.val)
    57  	}
    58  	return nil
    59  }
    60  
    61  // joinlist joins path elements using the os specific separator.
    62  // TODO(dfc) it probably gets this wrong on windows in some circumstances.
    63  func joinlist(paths ...string) string {
    64  	return strings.Join(paths, string(filepath.ListSeparator))
    65  }
    66  
    67  type envvar struct {
    68  	name, val string
    69  }
    70  
    71  func findenv(env []envvar, name string) string {
    72  	for _, e := range env {
    73  		if e.name == name {
    74  			return e.val
    75  		}
    76  	}
    77  	return ""
    78  }
    79  
    80  func makeenv(ctx *gb.Context) []envvar {
    81  	return []envvar{
    82  		{"GB_PROJECT_DIR", ctx.Projectdir()},
    83  		{"GB_SRC_PATH", joinlist(
    84  			filepath.Join(ctx.Projectdir(), "src"),
    85  			filepath.Join(ctx.Projectdir(), "vendor", "src"),
    86  		)},
    87  		{"GB_PKG_DIR", ctx.Pkgdir()},
    88  		{"GB_BIN_SUFFIX", ctx.Suffix()},
    89  		{"GB_GOROOT", runtime.GOROOT()},
    90  	}
    91  }