github.com/rivy-go/git-changelog@v0.0.0-20240424224517-b86e6ab57773/cmd/git-changelog/version-go1.18.go (about)

     1  //go:build go1.18
     2  // +build go1.18
     3  
     4  package main
     5  
     6  import (
     7  	"runtime/debug"
     8  )
     9  
    10  // ref: [Go 1.18 debug/buildinfo features](https://shibumi.dev/posts/go-18-feature) @@ <https://archive.is/4LeZV>
    11  // ref: [How to include Git version information in Go](https://blog.carlmjohnson.net/post/2023/golang-git-hash-how-to) @@ <https://archive.is/SmRbl>
    12  // ref: <https://stackoverflow.com/questions/71642366/how-do-you-read-debug-vcs-version-info-from-a-go-1-18-binary> @@ <https://archive.is/CF6yk>
    13  
    14  // `debug.BuildInfo` is available from Go 1.12
    15  // `debug.BuildSetting` with VCS info is available from Go 1.18
    16  
    17  func version_impl(option FnVersionOptions) string {
    18  	var hashAbbrevLength = option.HashAbbrevLength
    19  	if info, ok := debug.ReadBuildInfo(); ok {
    20  		if info.Main.Version != "" && (info.Main.Version != "(devel)" /* a local build */) {
    21  			// info.Main.Version == VERSION for builds via `go install ...@VERSION`
    22  			return info.Main.Version
    23  		}
    24  		var revisionHash = ""
    25  		var isDirty = false
    26  		for _, kv := range info.Settings {
    27  			if kv.Value == "" {
    28  				continue
    29  			}
    30  			switch kv.Key {
    31  			case "vcs.revision":
    32  				revisionHash = kv.Value[:hashAbbrevLength]
    33  			case "vcs.modified":
    34  				isDirty = kv.Value == "true"
    35  			}
    36  
    37  		}
    38  		var suffix = "-" + revisionHash
    39  		if isDirty {
    40  			suffix += "-dirty"
    41  		}
    42  		return Version + suffix
    43  	}
    44  
    45  	return Version + "+"
    46  }