Recreating Go Module 'commit' paths
I’m spending some time trying to better understand best practices for Golang Modules and when used with GitHub’s Dependabot.
One practice I’m pursuing is to not (GitHub) Release Go Modules in separate repos that form part of a single application. In my scenario, I chose to not use a monorepo and so I have an application smeared across multiple repos. See GitHub help with dependency management
If a Module is not Released (on GithUb) then the go tooling versions the repo as:
[REPO-PATH] v0.0.0-[COMMIT-DATE]-[COMMIT-HASH]
In my test, a require value is:
v0.0.0-20210927170438-e7aa41e4107b
However, If you browse GitHub, dates aren’t simply to manipulate in the UI. In this case, if I browse a commit (e7aa41e4107b8c28f99cadfe55b831380730e808), I get e.g.:
committed 37 minutes ago
And, if I hover over that time, I get:
Sep 27, 10:04 AM PDT
GitHub’s REST API for Commits does include the commit date:
TOKEN="..."
OWNER="..."
REPO="..."
HASH="e7aa41e4107b8c28f99cadfe55b831380730e808"
curl \
--silent \
--request GET \
--header "Authorization: Bearer ${TOKEN}" \
https://api.github.com/repos/${OWNER}/${REPO}/git/commits/${HASH}
Yields:
{
"sha": "e7aa41e4107b8c28f99cadfe55b831380730e808",
"author": {
"name": "DazWilkin",
"date": "2021-09-27T17:04:38Z"
},
"committer": {
"name": "DazWilkin",
"date": "2021-09-27T17:04:38Z"
},
}
NOTE Edited for clarity and to redact
NOTE
dates are here Zulu’d which is coordinated universal time which is what Golang Modules uses.
We want to extract one of the date values.
jq is my preferred JSON processor:
jq -r .committer.date
And, the final step is to format the date value as Golang Modules wants with no punctuation and grab the 1st 12 digits of the hash
There are multiple ways to trim the date value in bash:
| tr --delete : \
| tr --delete - \
| tr --delete T \
| tr --delete Z
# Or my preference
| sed 's|:||g;s|-||g;s|T||g;s|Z||g'
The 12-character sha is most easily ${HASH::12} yielding:
TOKEN="..."
OWNER="..."
REPO="..."
HASH="e7aa41e4107b8c28f99cadfe55b831380730e808"
DATE=$(curl \
--silent \
--request GET \
--header "Authorization: Bearer ${TOKEN}" \
https://api.github.com/repos/${OWNER}/${REPO}/git/commits/${HASH} \
| jq -r .committer.date \
| sed 's|:||g;s|-||g;s|T||g;s|Z||g')
printf "github.com/${OWNER}/${REPO} v0.0.0-${DATE}-${HASH::12}"
HTH!