1// Copyright © 2015 Steve Francia <spf@spf13.com>.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6// http://www.apache.org/licenses/LICENSE-2.0
7//
8// Unless required by applicable law or agreed to in writing, software
9// distributed under the License is distributed on an "AS IS" BASIS,
10// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11// See the License for the specific language governing permissions and
12// limitations under the License.
13
14package cmd
15
16import (
17	"os"
18	"os/exec"
19	"path/filepath"
20	"strings"
21
22	"github.com/spf13/cobra"
23)
24
25var srcPaths []string
26
27func init() {
28	// Initialize srcPaths.
29	envGoPath := os.Getenv("GOPATH")
30	goPaths := filepath.SplitList(envGoPath)
31	if len(goPaths) == 0 {
32		// Adapted from https://github.com/Masterminds/glide/pull/798/files.
33		// As of Go 1.8 the GOPATH is no longer required to be set. Instead there
34		// is a default value. If there is no GOPATH check for the default value.
35		// Note, checking the GOPATH first to avoid invoking the go toolchain if
36		// possible.
37
38		goExecutable := os.Getenv("COBRA_GO_EXECUTABLE")
39		if len(goExecutable) <= 0 {
40			goExecutable = "go"
41		}
42
43		out, err := exec.Command(goExecutable, "env", "GOPATH").Output()
44		cobra.CheckErr(err)
45
46		toolchainGoPath := strings.TrimSpace(string(out))
47		goPaths = filepath.SplitList(toolchainGoPath)
48		if len(goPaths) == 0 {
49			cobra.CheckErr("$GOPATH is not set")
50		}
51	}
52	srcPaths = make([]string, 0, len(goPaths))
53	for _, goPath := range goPaths {
54		srcPaths = append(srcPaths, filepath.Join(goPath, "src"))
55	}
56}
57