knative.dev/pkg@v0.0.0-20260602142205-ac97e43f6622/changeset/commit.go (about)

     1  /*
     2  Copyright 2022 The Knative 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 changeset
    18  
    19  import (
    20  	"regexp"
    21  	"runtime/debug"
    22  	"strconv"
    23  	"sync"
    24  )
    25  
    26  const Unknown = "unknown"
    27  
    28  var (
    29  	shaRegexp = regexp.MustCompile(`^[a-f0-9]{40,64}$`)
    30  	rev       string
    31  	once      sync.Once
    32  
    33  	readBuildInfo = debug.ReadBuildInfo
    34  )
    35  
    36  // Get returns the 'vcs.revision' property from the embedded build information
    37  // If there is no embedded information 'unknown' will be returned
    38  //
    39  // The result will have a '-dirty' suffix if the workspace was not clean
    40  func Get() string {
    41  	once.Do(func() {
    42  		if rev == "" {
    43  			rev = get()
    44  		}
    45  		// It has been set through ldflags, do nothing
    46  	})
    47  
    48  	return rev
    49  }
    50  
    51  func get() string {
    52  	info, ok := readBuildInfo()
    53  	if !ok {
    54  		return Unknown
    55  	}
    56  
    57  	var revision string
    58  	var modified bool
    59  
    60  	for _, s := range info.Settings {
    61  		switch s.Key {
    62  		case "vcs.revision":
    63  			revision = s.Value
    64  		case "vcs.modified":
    65  			modified, _ = strconv.ParseBool(s.Value)
    66  		}
    67  	}
    68  
    69  	if revision == "" {
    70  		return Unknown
    71  	}
    72  
    73  	if shaRegexp.MatchString(revision) {
    74  		revision = revision[:7]
    75  	}
    76  
    77  	if modified {
    78  		revision += "-dirty"
    79  	}
    80  
    81  	return revision
    82  }