Repository: knative/pkg
Pull request #2548 (2022-07-16 01:48:21)

Bump min go version to  1.18 && read build info from embedded binary
<!-- Thanks for sending a pull request! -->

Fixes: https://github.com/knative/pkg/issues/2427

<!-- 
Describe your changes here- ideally you can get that description straight from
your descriptive commit message(s)! 

- :gift: Add new feature
- :bug: Fix bug
- :broom: Update or clean up current behavior
- :wastebasket: Remove feature or internal logic
-->

- :broom: Bump go version to 1.18
- :broom: Read commit info from embedded binary 
  - https://pkg.go.dev/runtime/debug#ReadBuildInfo
  - https://tip.golang.org/doc/go1.18#go-command

This should let us drop `HEAD` and `refs` in our `kodata` folders

<!--
In addition, categorize the changes you're making using the "/kind" Prow command, example:

/kind cleanup

Supported kinds are: api-change, bug, cleanup, deprecation, removal, documentation, enhancement, performance

-->
/kind cleanup

**Release Note**

<!--
:page_facing_up: If this change has user-visible impact, write a release note in the block
below. Include the string "action required" if additional action is required of
users switching to the new release, for example in case of a breaking change.

Write as if you are speaking to users, not other Knative contributors. If this
change has no user-visible impact, no release-note is needed.
-->
```release-note
changeset.Get now reads from vcs information embedded by the golang compiler
```

knative-prow[bot]: [APPROVALNOTIFIER] This PR is **APPROVED**

This pull-request has been approved by: *<a href="https://github.com/knative/pkg/pull/2548#" title="Author self-approved">dprotaso</a>*

The full list of commands accepted by this bot can be found [here](https://go.k8s.io/bot-commands?repo=knative%2Fpkg).

The pull request process is described [here](https://git.k8s.io/community/contributors/guide/owners.md#the-code-review-process)

<details >
Needs approval from an approver in each of these files:

- ~~[OWNERS](https://github.com/knative/pkg/blob/main/OWNERS)~~ [dprotaso]

Approvers can indicate their approval by writing `/approve` in a comment
Approvers can cancel approval by writing `/approve cancel` in a comment
</details>
<!-- META={"approvers":[]} -->
dprotaso: cc @wlynch 
knative-prow[bot]: @dprotaso: The following test **failed**, say `/retest` to rerun all failed tests or `/retest-required` to rerun all mandatory failed tests:

Test name | Commit | Details | Required | Rerun command
--- | --- | --- | --- | ---
build-tests_pkg_main | d1a74c1890490dbe780c2b9bb030cac047243aa7 | [link](https://prow.knative.dev/view/gs/knative-prow/pr-logs/pull/knative_pkg/2548/build-tests_pkg_main/1548122338963230720) | true | `/test build-tests_pkg_main`

[Your PR dashboard](https://prow.knative.dev/pr).

<details>

Instructions for interacting with me using PR comments are available [here](https://git.k8s.io/community/contributors/guide/pull-requests.md).  If you have questions or suggestions related to my behavior, please file an issue against the [kubernetes/test-infra](https://github.com/kubernetes/test-infra/issues/new?title=Prow%20issue:) repository. I understand the commands that are listed [here](https://go.k8s.io/bot-commands).
</details>
<!-- test report -->
codecov[bot]: # [Codecov](https://codecov.io/gh/knative/pkg/pull/2548?src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=knative) Report
> Merging [#2548](https://codecov.io/gh/knative/pkg/pull/2548?src=pr&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=knative) (041b3d8) into [main](https://codecov.io/gh/knative/pkg/commit/418e13833beae314fd3073cfc67591263e941984?el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=knative) (418e138) will **decrease** coverage by `0.04%`.
> The diff coverage is `96.55%`.

> :exclamation: Current head 041b3d8 differs from pull request most recent head 9bd6c91. Consider uploading reports for the commit 9bd6c91 to get more accurate results

```diff
@@            Coverage Diff             @@
##             main    #2548      +/-   ##
==========================================
- Coverage   81.64%   81.60%   -0.05%     
==========================================
  Files         163      163              
  Lines        9745     9707      -38     
==========================================
- Hits         7956     7921      -35     
+ Misses       1551     1549       -2     
+ Partials      238      237       -1     
```


| [Impacted Files](https://codecov.io/gh/knative/pkg/pull/2548?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=knative) | Coverage Δ | |
|---|---|---|
| [logging/config.go](https://codecov.io/gh/knative/pkg/pull/2548/diff?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=knative#diff-bG9nZ2luZy9jb25maWcuZ28=) | `81.25% <66.66%> (ø)` | |
| [apis/contexts.go](https://codecov.io/gh/knative/pkg/pull/2548/diff?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=knative#diff-YXBpcy9jb250ZXh0cy5nbw==) | `100.00% <100.00%> (ø)` | |
| [changeset/commit.go](https://codecov.io/gh/knative/pkg/pull/2548/diff?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=knative#diff-Y2hhbmdlc2V0L2NvbW1pdC5nbw==) | `100.00% <100.00%> (+4.83%)` | :arrow_up: |
| [...k/resourcesemantics/validation/validation\_admit.go](https://codecov.io/gh/knative/pkg/pull/2548/diff?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=knative#diff-d2ViaG9vay9yZXNvdXJjZXNlbWFudGljcy92YWxpZGF0aW9uL3ZhbGlkYXRpb25fYWRtaXQuZ28=) | `93.12% <100.00%> (+0.05%)` | :arrow_up: |

------

[Continue to review full report at Codecov](https://codecov.io/gh/knative/pkg/pull/2548?src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=knative).
> **Legend** - [Click here to learn more](https://docs.codecov.io/docs/codecov-delta?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=knative)
> `Δ = absolute <relative> (impact)`, `ø = not affected`, `? = missing data`
> Powered by [Codecov](https://codecov.io/gh/knative/pkg/pull/2548?src=pr&el=footer&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=knative). Last update [f1f36a2...9bd6c91](https://codecov.io/gh/knative/pkg/pull/2548?src=pr&el=lastupdated&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=knative). Read the [comment docs](https://docs.codecov.io/docs/pull-request-comments?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=knative).

dprotaso: unit tests flaked (metrics)

cc @imjasonh for tekton pipeline downstream failure - 
dprotaso: One option is we fail silently if the `vcs.revision` is missing - which would happen in `go test` scenarios
imjasonh: > One option is we fail silently if the `vcs.revision` is missing - which would happen in `go test` scenarios or `go run somefile.go`

Or if the binaries/images are built with `-buildvcs=false`, which some downstream might want to do if, e.g., Git isn't available in the CI environment, or they want to omit source information for some other reason.

I'll prepare a PR to fix Tekton's usage though, it doesn't look like these tests need to use `changeset.Get` anyway.
dprotaso: Ok added some tweaks

- Use a sync.Once to prevent double parsing
- Support SHA256
- Allow non-SHA revision strings
knative-prow[bot]: @dprotaso: The following test **failed**, say `/retest` to rerun all failed tests or `/retest-required` to rerun all mandatory failed tests:

Test name | Commit | Details | Required | Rerun command
--- | --- | --- | --- | ---
unit-tests_pkg_main | e1dbd0ab366fe52e30c07b1d30c4d9891a14e3d3 | [link](https://prow.knative.dev/view/gs/knative-prow/pr-logs/pull/knative_pkg/2548/unit-tests_pkg_main/1548329144486465536) | true | `/test unit-tests_pkg_main`

[Your PR dashboard](https://prow.knative.dev/pr).

<details>

Instructions for interacting with me using PR comments are available [here](https://git.k8s.io/community/contributors/guide/pull-requests.md).  If you have questions or suggestions related to my behavior, please file an issue against the [kubernetes/test-infra](https://github.com/kubernetes/test-infra/issues/new?title=Prow%20issue:) repository. I understand the commands that are listed [here](https://go.k8s.io/bot-commands).
</details>
<!-- test report -->

Patch:
diff --git a/changeset/commit.go b/changeset/commit.go
index 3668dfebd..b4dcab002 100644
--- a/changeset/commit.go
+++ b/changeset/commit.go
@@ -1,5 +1,5 @@
 /*
-Copyright 2018 The Knative Authors
+Copyright 2022 The Knative Authors
 
 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
@@ -17,113 +17,66 @@ limitations under the License.
 package changeset
 
 import (
-	"bufio"
-	"fmt"
-	"io/ioutil"
-	"os"
-	"path/filepath"
+	"errors"
 	"regexp"
-	"strings"
+	"runtime/debug"
+	"strconv"
+	"sync"
 )
 
-const (
-	commitIDFile      = "HEAD"
-	koDataPathEnvName = "KO_DATA_PATH"
-	// packedRefsFile is a file containing a list of refs, used to compact the
-	// list of refs instead of storing them on the filesystem directly.
-	// See https://git-scm.com/docs/git-pack-refs
-	packedRefsFile = "packed-refs"
-)
+const Unknown = "unknown"
+
+var (
+	shaRegexp = regexp.MustCompile(`^[a-f0-9]{40,64}$`)
+	rev       string
+	err       error
+	once      sync.Once
 
-var commitIDRE = regexp.MustCompile(`^[a-f0-9]{40}$`)
+	// for testing
+	readBuildInfo = debug.ReadBuildInfo
+)
 
-// Get tries to fetch the first 7 digitals of GitHub commit ID from HEAD file in
-// KO_DATA_PATH. If it fails, it returns the error it gets.
+// Get returns the 'vcs.revision' property from the embedded build information
+// This function will return an error if value is not a valid Git SHA
+//
+// The result will have a '-dirty' suffix if the workspace was not clean
 func Get() (string, error) {
-	data, err := readFileFromKoData(commitIDFile)
-	if err != nil {
-		return "", err
+	once.Do(func() {
+		rev, err = get()
+	})
+
+	return rev, err
+}
+
+func get() (string, error) {
+	info, ok := readBuildInfo()
+	if !ok {
+		return "", errors.New("unable to read build info")
 	}
-	commitID := strings.TrimSpace(string(data))
-	if rID := strings.TrimPrefix(commitID, "ref: "); rID != commitID {
-		// First try to read from the direct ref file - e.g. refs/heads/main
-		data, err := readFileFromKoData(rID)
-		if err != nil {
-			if !os.IsNotExist(err) {
-				return "", err
-			}
-
-			// Ref file didn't exist - it might be contained in the packed-refs
-			// file.
-			var pferr error
-			data, pferr = findPackedRef(rID)
-			// Only return the sub-error if the packed-refs file exists, otherwise
-			// just let the original error return (e.g. treat it as if we didn't
-			// even attempt the operation). This is primarily to keep the error
-			// messages clean.
-			if pferr != nil {
-				if os.IsNotExist(pferr) {
-					return "", err
-				}
-				return "", pferr
-			}
+
+	var revision string
+	var modified bool
+
+	for _, s := range info.Settings {
+		switch s.Key {
+		case "vcs.revision":
+			revision = s.Value
+		case "vcs.modified":
+			modified, _ = strconv.ParseBool(s.Value)
 		}
-		commitID = strings.TrimSpace(string(data))
 	}
-	if commitIDRE.MatchString(commitID) {
-		return commitID[:7], nil
-	}
-	return "", fmt.Errorf("%q is not a valid GitHub commit ID", commitID)
-}
 
-// readFileFromKoData tries to read data as string from the file with given name
-// under KO_DATA_PATH then returns the content as string. The file is expected
-// to be wrapped into the container from /kodata by ko. If it fails, returns
-// the error it gets.
-func readFileFromKoData(filename string) ([]byte, error) {
-	f, err := koDataFile(filename)
-	if err != nil {
-		return nil, err
+	if revision == "" {
+		return Unknown, nil
 	}
-	defer f.Close()
-	return ioutil.ReadAll(f)
-}
 
-// readFileFromKoData tries to open the file with given name under KO_DATA_PATH.
-// The file is expected to be wrapped into the container from /kodata by ko.
-// If it fails, returns the error it gets.
-func koDataFile(filename string) (*os.File, error) {
-	koDataPath := os.Getenv(koDataPathEnvName)
-	if koDataPath == "" {
-		return nil, fmt.Errorf("%q does not exist or is empty", koDataPathEnvName)
+	if shaRegexp.MatchString(revision) {
+		revision = revision[:7]
 	}
-	return os.Open(filepath.Join(koDataPath, filename))
-}
 
-// findPackedRef searches the packed-ref file for ref values.
-// This can happen if the # of refs in a repo grows too much - git will try
-// and condense them into a file.
-// See https://git-scm.com/docs/git-pack-refs
-func findPackedRef(ref string) ([]byte, error) {
-	f, err := koDataFile(packedRefsFile)
-	if err != nil {
-		return nil, err
+	if modified {
+		revision += "-dirty"
 	}
-	defer f.Close()
-
-	scanner := bufio.NewScanner(f)
-	for scanner.Scan() {
-		// We only care about lines with `<commit> <ref>` pairs.
-		// Why this might happen:
-		// 1. Lines starting with ^ refer to unpeeled tag SHAs
-		// 	  (e.g. the commits pointed to by annotated tags)
-		s := strings.Split(scanner.Text(), " ")
-		if len(s) != 2 {
-			continue
-		}
-		if ref == s[1] {
-			return []byte(s[0]), nil
-		}
-	}
-	return nil, fmt.Errorf("%q ref not found in packed-refs", ref)
+
+	return revision, nil
 }
diff --git a/changeset/doc.go b/changeset/doc.go
index c56f7ebfb..9727f27d3 100644
--- a/changeset/doc.go
+++ b/changeset/doc.go
@@ -14,10 +14,6 @@ See the License for the specific language governing permissions and
 limitations under the License.
 */
 
-// Package changeset provides Knative utilities for fetching GitHub Commit ID
-// from kodata directory. It requires GitHub HEAD file to be linked into
-// Knative component source code via the following command:
-//   ln -s -r .git/HEAD ./cmd/<knative-component-name>/kodata/
-// Then ko will build this file into $KO_DATA_PATH when building the container
-// for a Knative component.
+// Package changeset returns version control info that was embedded in the
+// golang binary
 package changeset
diff --git a/go.mod b/go.mod
index 7c8b2a4a8..0ac7f65b8 100644
--- a/go.mod
+++ b/go.mod
@@ -1,6 +1,6 @@
 module knative.dev/pkg
 
-go 1.17
+go 1.18
 
 require (
 	cloud.google.com/go v0.98.0
diff --git a/go.sum b/go.sum
index 55bc5f8ab..450b82a91 100644
--- a/go.sum
+++ b/go.sum
@@ -98,7 +98,6 @@ github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6r
 github.com/bgentry/speakeasy v0.1.0/go.mod h1:+zsyZBPWlz7T6j88CTgSN5bM796AkVf0kBD4zp0CCIs=
 github.com/bketelsen/crypt v0.0.3-0.20200106085610-5cbc8cc4026c/go.mod h1:MKsuJmJgSg28kpZDP6UIiPt0e0Oz0kqKNGyRaWEPv84=
 github.com/bketelsen/crypt v0.0.4/go.mod h1:aI6NrJ0pMGgvZKL1iVgXLnfIFJtfV+bKCoqOes/6LfM=
-github.com/blang/semver v3.5.1+incompatible h1:cQNTCjp13qL8KC3Nbxr/y2Bqb63oX6wdnnjpJbkM4JQ=
 github.com/blang/semver v3.5.1+incompatible/go.mod h1:kRBLl5iJ+tD4TcOOxsy/0fnwebNt5EWlYSAyrTnjyyk=
 github.com/blang/semver/v4 v4.0.0 h1:1PFHFE6yCCTv8C1TeyNNarDzntLi7wMI5i/pzqYIsAM=
 github.com/blang/semver/v4 v4.0.0/go.mod h1:IbckMUScFkM3pff0VJDNKRiT6TG/YpiHIM2yvyW5YoQ=
@@ -112,7 +111,6 @@ github.com/census-instrumentation/opencensus-proto v0.3.0 h1:t/LhUZLVitR1Ow2YOnd
 github.com/census-instrumentation/opencensus-proto v0.3.0/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU=
 github.com/certifi/gocertifi v0.0.0-20191021191039-0944d244cd40/go.mod h1:sGbDF6GwGcLpkNXPUTkMRoywsNa/ol15pxFe6ERfguA=
 github.com/certifi/gocertifi v0.0.0-20200922220541-2c3bb06c6054/go.mod h1:sGbDF6GwGcLpkNXPUTkMRoywsNa/ol15pxFe6ERfguA=
-github.com/cespare/xxhash v1.1.0 h1:a6HrQnmkObjyL+Gs60czilIUGqrzKutQD6XZog3p+ko=
 github.com/cespare/xxhash v1.1.0/go.mod h1:XrSqR1VqqWfGrhpAt58auRo0WTKS1nRRg3ghfAqPWnc=
 github.com/cespare/xxhash/v2 v2.1.1 h1:6MnRN8NT7+YBpUIWxHtefFZOKTAPgGjpQSxqLNn0+qY=
 github.com/cespare/xxhash/v2 v2.1.1/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
@@ -617,7 +615,6 @@ github.com/yuin/goldmark v1.1.32/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9de
 github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
 github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k=
 github.com/yuin/goldmark v1.4.0/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k=
-github.com/yuin/goldmark v1.4.1/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k=
 go.etcd.io/bbolt v1.3.2/go.mod h1:IbVyRI1SCnLcuJnV2u8VeU0CEYM7e686BmAb1XKL+uU=
 go.etcd.io/bbolt v1.3.6/go.mod h1:qXsaaIqmgQH0T+OPdb99Bf+PKfBBQVAdyD6TY9G8XM4=
 go.etcd.io/etcd/api/v3 v3.5.0/go.mod h1:cbVKeC6lCfl7j/8jBhAK6aIYO9XOjdptoxU/nLQcPvs=
@@ -766,8 +763,6 @@ golang.org/x/net v0.0.0-20210525063256-abc453219eb5/go.mod h1:9nx3DQGgdP8bBQD5qx
 golang.org/x/net v0.0.0-20210805182204-aaa1db679c0d/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
 golang.org/x/net v0.0.0-20210825183410-e898025ed96a/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
 golang.org/x/net v0.0.0-20210917221730-978cfadd31cf/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
-golang.org/x/net v0.0.0-20211015210444-4f30a5c0130f/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
-golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
 golang.org/x/net v0.0.0-20211209124913-491a49abca63/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
 golang.org/x/net v0.0.0-20220225172249-27dd8689420f h1:oA4XRj0qtSt8Yo1Zms0CUlsT3KG69V2UGQWPBxujDmc=
 golang.org/x/net v0.0.0-20220225172249-27dd8689420f/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk=
@@ -872,9 +867,7 @@ golang.org/x/sys v0.0.0-20210823070655-63515b42dcdf/go.mod h1:oPkhp1MJrh7nUepCBc
 golang.org/x/sys v0.0.0-20210831042530-f4d43177bf5e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
 golang.org/x/sys v0.0.0-20210908233432-aa78b53d3365/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
 golang.org/x/sys v0.0.0-20210917161153-d61c044b1678/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
-golang.org/x/sys v0.0.0-20211019181941-9d821ace8654/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
 golang.org/x/sys v0.0.0-20211124211545-fe61309f8881/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
-golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
 golang.org/x/sys v0.0.0-20220227234510-4e6760a101f9 h1:nhht2DYV/Sn3qOayu8lM+cU1ii9sTLUeBQwQQfUHtrs=
 golang.org/x/sys v0.0.0-20220227234510-4e6760a101f9/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
 golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
diff --git a/logging/config.go b/logging/config.go
index de979368c..b0fd30e07 100644
--- a/logging/config.go
+++ b/logging/config.go
@@ -75,14 +75,14 @@ func NewLogger(configJSON string, levelOverride string, opts ...zap.Option) (*za
 }
 
 func enrichLoggerWithCommitID(logger *zap.Logger) *zap.SugaredLogger {
-	commitID, err := changeset.Get()
-	if err != nil {
-		logger.Info("Fetch GitHub commit ID from kodata failed", zap.Error(err))
+	revision, err := changeset.Get()
+	if err != nil || revision == changeset.Unknown {
+		logger.Info("Unable to read vcs.revision from binary", zap.Error(err))
 		return logger.Sugar()
 	}
 
-	// Enrich logs with GitHub commit ID.
-	return logger.With(zap.String(logkey.GitHubCommitID, commitID)).Sugar()
+	// Enrich logs with the components git revision.
+	return logger.With(zap.String(logkey.Commit, revision)).Sugar()
 
 }
 
diff --git a/logging/logkey/constants.go b/logging/logkey/constants.go
index 9e1c4d81e..1e9b6214c 100644
--- a/logging/logkey/constants.go
+++ b/logging/logkey/constants.go
@@ -59,7 +59,7 @@ const (
 	// KubernetesService is the key used to represent a Kubernetes service name in logs
 	KubernetesService = "knative.dev/k8sservice"
 
-	// GitHubCommitID is the key used to represent the GitHub Commit ID where the
-	// Knative component was built from in logs
-	GitHubCommitID = "commit"
+	// Commit is the logging key used to represent the VCS revision that the
+	// Knative component was built from
+	Commit = "commit"
 )


Test patch:
diff --git a/changeset/commit_test.go b/changeset/commit_test.go
index b1724c140..c73bc58b1 100644
--- a/changeset/commit_test.go
+++ b/changeset/commit_test.go
@@ -1,5 +1,5 @@
 /*
-Copyright 2018 The Knative Authors
+Copyright 2022 The Knative Authors
 
 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
@@ -17,87 +17,81 @@ limitations under the License.
 package changeset
 
 import (
-	"errors"
-	"fmt"
+	"runtime/debug"
+	"sync"
 	"testing"
-)
 
-const (
-	nonCommittedHeadRef = "refs/heads/non_committed_branch"
-	testCommitID        = "a2d1bdf"
+	"github.com/google/go-cmp/cmp"
 )
 
-func TestReadFile(t *testing.T) {
-	tests := []struct {
-		name                      string
-		koDataPath                string
-		koDataPathEnvDoesNotExist bool
-		want                      string
-		wantErr                   bool
-		err                       error
+func TestGet(t *testing.T) {
+
+	cases := []struct {
+		name    string
+		info    *debug.BuildInfo
+		ok      bool
+		result  string
+		wantErr string
 	}{{
-		name:       "committed branch",
-		koDataPath: "testdata",
-		want:       testCommitID,
-	}, {
-		name:       "no refs link",
-		koDataPath: "testdata/noncommitted",
-		wantErr:    true,
-		err:        fmt.Errorf("open testdata/noncommitted/%s: no such file or directory", nonCommittedHeadRef),
-	}, {
-		name:       "with refs link",
-		koDataPath: "testdata/with-refs",
-		want:       testCommitID,
-	}, {
-		name:       "with bad content",
-		koDataPath: "testdata/garbage",
-		wantErr:    true,
-		err:        fmt.Errorf(`"garbage contents" is not a valid GitHub commit ID`),
-	}, {
-		name:       "KO_DATA_PATH is empty",
-		koDataPath: "",
-		wantErr:    true,
-		err:        fmt.Errorf("%q does not exist or is empty", koDataPathEnvName),
+		name:    "info fails",
+		ok:      false,
+		wantErr: "unable to read build info",
 	}, {
-		name:                      "KO_DATA_PATH does not exist",
-		koDataPath:                "",
-		wantErr:                   true,
-		koDataPathEnvDoesNotExist: true,
-		err:                       fmt.Errorf("%q does not exist or is empty", koDataPathEnvName),
+		name:   "missing revision",
+		ok:     true,
+		info:   &debug.BuildInfo{},
+		result: Unknown,
 	}, {
-		name:       "HEAD file does not exist",
-		koDataPath: "testdata/nonexisting",
-		wantErr:    true,
-		err:        errors.New("open testdata/nonexisting/HEAD: no such file or directory"),
+		name: "SHA1 revision is truncated",
+		ok:   true,
+		info: &debug.BuildInfo{
+			Settings: []debug.BuildSetting{{
+				Key: "vcs.revision", Value: "3666ce749d32abe7be0528380c8c05a4282cb733",
+			}},
+		},
+		result: "3666ce7",
 	}, {
-		name:       "packed-ref",
-		koDataPath: "testdata/packed-refs",
-		want:       testCommitID,
+		name: "SHA256 revision is truncated",
+		ok:   true,
+		info: &debug.BuildInfo{
+			Settings: []debug.BuildSetting{{
+				Key: "vcs.revision", Value: "2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824",
+			}},
+		},
+		result: "2cf24db",
 	}, {
-		name:       "no refs with packed-ref",
-		koDataPath: "testdata/noncommited-packed-refs",
-		wantErr:    true,
-		err:        fmt.Errorf("%q ref not found in packed-refs", nonCommittedHeadRef),
+		name: "modified workspace results in -dirty suffix",
+		ok:   true,
+		info: &debug.BuildInfo{
+			Settings: []debug.BuildSetting{{
+				Key: "vcs.revision", Value: "3666ce749d32abe7be0528380c8c05a4282cb733",
+			}, {
+				Key: "vcs.modified", Value: "true",
+			}},
+		},
+		result: "3666ce7-dirty",
 	}}
-	for _, test := range tests {
-		t.Run(test.name, func(t *testing.T) {
-			if !test.koDataPathEnvDoesNotExist {
-				t.Setenv(koDataPathEnvName, test.koDataPath)
-			}
-
-			got, err := Get()
 
-			if (err != nil) != test.wantErr {
-				t.Error("Get() =", err)
+	for _, c := range cases {
+		t.Run(c.name, func(t *testing.T) {
+			once = sync.Once{}
+			readBuildInfo = func() (info *debug.BuildInfo, ok bool) {
+				return c.info, c.ok
 			}
-			if !test.wantErr {
-				if test.want != got {
-					t.Errorf("wanted %q but got %q", test.want, got)
-				}
-			} else {
-				if err == nil || err.Error() != test.err.Error() {
-					t.Errorf("wanted error %v but got: %v", test.err, err)
+
+			val, err := Get()
+			if c.wantErr == "" && err != nil {
+				t.Fatal("unexpected error", err)
+			} else if c.wantErr != "" && err != nil {
+				if diff := cmp.Diff(c.wantErr, err.Error()); diff != "" {
+					t.Fatalf("error doesn't match expected: %s", diff)
 				}
+			} else if c.wantErr != "" && err == nil {
+				t.Fatalf("expected error %q but was nil", c.wantErr)
+			}
+
+			if diff := cmp.Diff(c.result, val); diff != "" {
+				t.Errorf("result doesn't match expected: %s", diff)
 			}
 		})
 	}
diff --git a/changeset/testdata/HEAD b/changeset/testdata/HEAD
deleted file mode 100644
index 58b38ebae..000000000
--- a/changeset/testdata/HEAD
+++ /dev/null
@@ -1,1 +0,0 @@
-a2d1bdfe929516d7da141aef68631a7ee6941b2d
diff --git a/changeset/testdata/garbage/HEAD b/changeset/testdata/garbage/HEAD
deleted file mode 100644
index 0717e5553..000000000
--- a/changeset/testdata/garbage/HEAD
+++ /dev/null
@@ -1,1 +0,0 @@
-garbage contents
\ No newline at end of file
diff --git a/changeset/testdata/noncommited-packed-refs/HEAD b/changeset/testdata/noncommited-packed-refs/HEAD
deleted file mode 100644
index 89fe2d356..000000000
--- a/changeset/testdata/noncommited-packed-refs/HEAD
+++ /dev/null
@@ -1,1 +0,0 @@
-ref: refs/heads/non_committed_branch
diff --git a/changeset/testdata/noncommited-packed-refs/packed-refs b/changeset/testdata/noncommited-packed-refs/packed-refs
deleted file mode 100644
index e69de29bb..000000000
diff --git a/changeset/testdata/noncommitted/HEAD b/changeset/testdata/noncommitted/HEAD
deleted file mode 100644
index 89fe2d356..000000000
--- a/changeset/testdata/noncommitted/HEAD
+++ /dev/null
@@ -1,1 +0,0 @@
-ref: refs/heads/non_committed_branch
diff --git a/changeset/testdata/packed-refs/HEAD b/changeset/testdata/packed-refs/HEAD
deleted file mode 100644
index 19af7398c..000000000
--- a/changeset/testdata/packed-refs/HEAD
+++ /dev/null
@@ -1,1 +0,0 @@
-ref: refs/heads/foo
diff --git a/changeset/testdata/packed-refs/packed-refs b/changeset/testdata/packed-refs/packed-refs
deleted file mode 100644
index 634ca6720..000000000
--- a/changeset/testdata/packed-refs/packed-refs
+++ /dev/null
@@ -1,4 +0,0 @@
-a2d1bdfe929516d7da141aef68631a7ee6941b2d refs/tags/bar
-^51be315ed160e68627a3bc51a244ec77e470c667
-a2d1bdfe929516d7da141aef68631a7ee6941b2d refs/tags/baz
-a2d1bdfe929516d7da141aef68631a7ee6941b2d refs/heads/foo
diff --git a/changeset/testdata/with-refs/HEAD b/changeset/testdata/with-refs/HEAD
deleted file mode 100644
index b86b48fd8..000000000
--- a/changeset/testdata/with-refs/HEAD
+++ /dev/null
@@ -1,1 +0,0 @@
-ref: refs/heads/branch-name
\ No newline at end of file
diff --git a/changeset/testdata/with-refs/refs/heads/branch-name b/changeset/testdata/with-refs/refs/heads/branch-name
deleted file mode 100644
index 58b38ebae..000000000
--- a/changeset/testdata/with-refs/refs/heads/branch-name
+++ /dev/null
@@ -1,1 +0,0 @@
-a2d1bdfe929516d7da141aef68631a7ee6941b2d