github.com/containerd/nerdctl@v1.7.7/pkg/version/version.go (about)

     1  /*
     2     Copyright The containerd Authors.
     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 version
    18  
    19  import (
    20  	"runtime/debug"
    21  	"strconv"
    22  )
    23  
    24  var (
    25  	// Version is filled via Makefile
    26  	Version = ""
    27  	// Revision is filled via Makefile
    28  	Revision = ""
    29  )
    30  
    31  const unknown = "<unknown>"
    32  
    33  func GetVersion() string {
    34  	if Version != "" {
    35  		return Version
    36  	}
    37  	/*
    38  	 * go install example.com/cmd/foo@vX.Y.Z: bi.Main.Version="vX.Y.Z",                               vcs.revision is unset
    39  	 * go install example.com/cmd/foo@latest: bi.Main.Version="vX.Y.Z",                               vcs.revision is unset
    40  	 * go install example.com/cmd/foo@master: bi.Main.Version="vX.Y.Z-N.yyyyMMddhhmmss-gggggggggggg", vcs.revision is unset
    41  	 * go install ./cmd/foo:                  bi.Main.Version="(devel)", vcs.revision="gggggggggggggggggggggggggggggggggggggggg"
    42  	 *                                        vcs.time="yyyy-MM-ddThh:mm:ssZ", vcs.modified=("false"|"true")
    43  	 */
    44  	if bi, ok := debug.ReadBuildInfo(); ok {
    45  		if bi.Main.Version != "" && bi.Main.Version != "(devel)" {
    46  			return bi.Main.Version
    47  		}
    48  	}
    49  	return unknown
    50  }
    51  
    52  func GetRevision() string {
    53  	if Revision != "" {
    54  		return Revision
    55  	}
    56  	if bi, ok := debug.ReadBuildInfo(); ok {
    57  		var (
    58  			vcsRevision string
    59  			vcsModified bool
    60  		)
    61  		for _, f := range bi.Settings {
    62  			switch f.Key {
    63  			case "vcs.revision":
    64  				vcsRevision = f.Value
    65  			case "vcs.modified":
    66  				vcsModified, _ = strconv.ParseBool(f.Value)
    67  			}
    68  		}
    69  		if vcsRevision == "" {
    70  			return unknown
    71  		}
    72  		rev := vcsRevision
    73  		if vcsModified {
    74  			rev += ".m"
    75  		}
    76  		return rev
    77  	}
    78  	return unknown
    79  }