github.com/goplus/gop@v1.2.6/env/version.go (about)

     1  /*
     2   * Copyright (c) 2021 The GoPlus Authors (goplus.org). All rights reserved.
     3   *
     4   * Licensed under the Apache License, Version 2.0 (the "License");
     5   * you may not use this file except in compliance with the License.
     6   * You may obtain a copy of the License at
     7   *
     8   *     http://www.apache.org/licenses/LICENSE-2.0
     9   *
    10   * Unless required by applicable law or agreed to in writing, software
    11   * distributed under the License is distributed on an "AS IS" BASIS,
    12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13   * See the License for the specific language governing permissions and
    14   * limitations under the License.
    15   */
    16  
    17  package env
    18  
    19  import (
    20  	"bytes"
    21  	"os"
    22  	"os/exec"
    23  	"path/filepath"
    24  	"strings"
    25  )
    26  
    27  const (
    28  	MainVersion = "1.2"
    29  )
    30  
    31  // buildVersion is the GoPlus tree's version string at build time.
    32  // This is set by the linker.
    33  var (
    34  	buildVersion string
    35  )
    36  
    37  func init() {
    38  	initEnv()
    39  }
    40  
    41  func initEnv() {
    42  	if buildVersion == "" {
    43  		initEnvByGop()
    44  		return
    45  	}
    46  	if !strings.HasPrefix(buildVersion, "v"+MainVersion+".") {
    47  		panic("gop/env: [FATAL] Invalid buildVersion: " + buildVersion)
    48  	}
    49  }
    50  
    51  func initEnvByGop() {
    52  	if fname := filepath.Base(os.Args[0]); !isGopCmd(fname) {
    53  		if ret, err := gopEnv(); err == nil {
    54  			parts := strings.SplitN(strings.TrimRight(ret, "\n"), "\n", 3)
    55  			if len(parts) == 3 {
    56  				buildVersion, buildDate, defaultGopRoot = parts[0], parts[1], parts[2]
    57  			}
    58  		}
    59  	}
    60  }
    61  
    62  var gopEnv = func() (string, error) {
    63  	var b bytes.Buffer
    64  	cmd := exec.Command("gop", "env", "GOPVERSION", "BUILDDATE", "GOPROOT")
    65  	cmd.Stdout = &b
    66  	err := cmd.Run()
    67  	return b.String(), err
    68  }
    69  
    70  // Installed checks is `gop` installed or not.
    71  // If returns false, it means `gop` is not installed or not in PATH.
    72  func Installed() bool {
    73  	return buildVersion != ""
    74  }
    75  
    76  // Version returns the GoPlus tree's version string.
    77  // It is either the commit hash and date at the time of the build or,
    78  // when possible, a release tag like "v1.0.0-rc1".
    79  func Version() string {
    80  	if buildVersion == "" {
    81  		return "v" + MainVersion + ".x"
    82  	}
    83  	return buildVersion
    84  }