| 1 |
package base |
| 2 |
|
| 3 |
// This file contains aspects principally related to GitHub workflows |
| 4 |
|
| 5 |
import ( |
| 6 |
encjson "encoding/json" |
| 7 |
"list" |
| 8 |
"strings" |
| 9 |
"strconv" |
| 10 |
|
| 11 |
"github.com/SchemaStore/schemastore/src/schemas/json" |
| 12 |
) |
| 13 |
|
| 14 |
bashWorkflow: json.#Workflow & { |
| 15 |
jobs: [string]: defaults: run: shell: "bash" |
| 16 |
} |
| 17 |
|
| 18 |
installGo: { |
| 19 |
#setupGo: json.#step & { |
| 20 |
name: "Install Go" |
| 21 |
uses: "actions/setup-go@v5" |
| 22 |
with: { |
| 23 |
// We do our own caching in setupGoActionsCaches. |
| 24 |
cache: false |
| 25 |
"go-version": string |
| 26 |
} |
| 27 |
} |
| 28 |
|
| 29 |
// Why set GOTOOLCHAIN here? As opposed to an environment variable |
| 30 |
// elsewhere? No perfect answer to this question but here is the thinking: |
| 31 |
// |
| 32 |
// Setting the variable here localises it with the installation of Go. Doing |
| 33 |
// it elsewhere creates distance between the two steps which are |
| 34 |
// intrinsically related. And it's also hard to do: "when we use this step, |
| 35 |
// also ensure that we establish an environment variable in the job for |
| 36 |
// GOTOOLCHAIN". |
| 37 |
// |
| 38 |
// Environment variables can only be set at a workflow, job or step level. |
| 39 |
// Given we currently use a matrix strategy which varies the Go version, |
| 40 |
// that rules out using an environment variable based approach, because the |
| 41 |
// Go version is only available at runtime via GitHub actions provided |
| 42 |
// context. Whether we should instead be templating multiple workflows (i.e. |
| 43 |
// exploding the matrix ourselves) is a different question, but one that |
| 44 |
// has performance implications. |
| 45 |
// |
| 46 |
// So as clumsy as it is to use a step "template" that includes more than |
| 47 |
// one step, it's the best option available to us for now. |
| 48 |
[ |
| 49 |
#setupGo, |
| 50 |
|
| 51 |
{ |
| 52 |
json.#step & { |
| 53 |
name: "Set common go env vars" |
| 54 |
run: """ |
| 55 |
go env -w GOTOOLCHAIN=local |
| 56 |
|
| 57 |
# Dump env for good measure |
| 58 |
go env |
| 59 |
""" |
| 60 |
} |
| 61 |
}, |
| 62 |
] |
| 63 |
} |
| 64 |
|
| 65 |
checkoutCode: { |
| 66 |
#actionsCheckout: json.#step & { |
| 67 |
name: "Checkout code" |
| 68 |
uses: "actions/checkout@v4" |
| 69 |
|
| 70 |
// "pull_request" builds will by default use a merge commit, |
| 71 |
// testing the PR's HEAD merged on top of the master branch. |
| 72 |
// For consistency with Gerrit, avoid that merge commit entirely. |
| 73 |
// This doesn't affect builds by other events like "push", |
| 74 |
// since github.event.pull_request is unset so ref remains empty. |
| 75 |
with: { |
| 76 |
ref: "${{ github.event.pull_request.head.sha }}" |
| 77 |
"fetch-depth": 0 // see the docs below |
| 78 |
} |
| 79 |
} |
| 80 |
|
| 81 |
[ |
| 82 |
#actionsCheckout, |
| 83 |
|
| 84 |
// Restore modified times to work around https://go.dev/issues/58571, |
| 85 |
// as otherwise we would get lots of unnecessary Go test cache misses. |
| 86 |
// Note that this action requires actions/checkout to use a fetch-depth of 0. |
| 87 |
// Since this is a third-party action which runs arbitrary code, |
| 88 |
// we pin a commit hash for v2 to be in control of code updates. |
| 89 |
// Also note that git-restore-mtime does not update all directories, |
| 90 |
// per the bug report at https://github.com/MestreLion/git-tools/issues/47, |
| 91 |
// so we first reset all directory timestamps to a static time as a fallback. |
| 92 |
// TODO(mvdan): May be unnecessary once the Go bug above is fixed. |
| 93 |
json.#step & { |
| 94 |
name: "Reset git directory modification times" |
| 95 |
run: "touch -t 202211302355 $(find * -type d)" |
| 96 |
}, |
| 97 |
json.#step & { |
| 98 |
name: "Restore git file modification times" |
| 99 |
uses: "chetan/git-restore-mtime-action@075f9bc9d159805603419d50f794bd9f33252ebe" |
| 100 |
}, |
| 101 |
|
| 102 |
{ |
| 103 |
json.#step & { |
| 104 |
name: "Try to extract \(dispatchTrailer)" |
| 105 |
id: dispatchTrailerStepID |
| 106 |
run: """ |
| 107 |
x="$(git log -1 --pretty='%(trailers:key=\(dispatchTrailer),valueonly)')" |
| 108 |
if [[ "$x" == "" ]] |
| 109 |
then |
| 110 |
# Some steps rely on the presence or otherwise of the Dispatch-Trailer. |
| 111 |
# We know that we don't have a Dispatch-Trailer in this situation, |
| 112 |
# hence we use the JSON value null in order to represent that state. |
| 113 |
# This means that GitHub expressions can determine whether a Dispatch-Trailer |
| 114 |
# is present or not by checking whether the fromJSON() result of the |
| 115 |
# output from this step is the JSON value null or not. |
| 116 |
x=null |
| 117 |
fi |
| 118 |
echo "\(_dispatchTrailerDecodeStepOutputVar)<<EOD" >> $GITHUB_OUTPUT |
| 119 |
echo "$x" >> $GITHUB_OUTPUT |
| 120 |
echo "EOD" >> $GITHUB_OUTPUT |
| 121 |
""" |
| 122 |
} |
| 123 |
}, |
| 124 |
|
| 125 |
// Safety nets to flag if we ever have a Dispatch-Trailer slip through the |
| 126 |
// net and make it to master |
| 127 |
json.#step & { |
| 128 |
name: "Check we don't have \(dispatchTrailer) on a protected branch" |
| 129 |
if: "\(isProtectedBranch) && \(containsDispatchTrailer)" |
| 130 |
run: """ |
| 131 |
echo "\(_dispatchTrailerVariable) contains \(dispatchTrailer) but we are on a protected branch" |
| 132 |
false |
| 133 |
""" |
| 134 |
}, |
| 135 |
] |
| 136 |
} |
| 137 |
|
| 138 |
earlyChecks: json.#step & { |
| 139 |
name: "Early git and code sanity checks" |
| 140 |
run: *"go run cuelang.org/go/internal/ci/[email protected]" | string |
| 141 |
} |
| 142 |
|
| 143 |
curlGitHubAPI: { |
| 144 |
#tokenSecretsKey: *botGitHubUserTokenSecretsKey | string |
| 145 |
|
| 146 |
#""" |
| 147 |
curl -s -L -H "Accept: application/vnd.github+json" -H "Authorization: Bearer ${{ secrets.\#(#tokenSecretsKey) }}" -H "X-GitHub-Api-Version: 2022-11-28" |
| 148 |
"""# |
| 149 |
} |
| 150 |
|
| 151 |
setupGoActionsCaches: { |
| 152 |
// #readonly determines whether we ever want to write the cache back. The |
| 153 |
// writing of a cache back (for any given cache key) should only happen on a |
| 154 |
// protected branch. But running a workflow on a protected branch often |
| 155 |
// implies that we want to skip the cache to ensure we catch flakes early. |
| 156 |
// Hence the concept of clearing the testcache to ensure we catch flakes |
| 157 |
// early can be defaulted based on #readonly. In the general case the two |
| 158 |
// concepts are orthogonal, hence they are kept as two parameters, even |
| 159 |
// though in our case we could get away with a single parameter that |
| 160 |
// encapsulates our needs. |
| 161 |
#readonly: *false | bool |
| 162 |
#cleanTestCache: *!#readonly | bool |
| 163 |
#goVersion: string |
| 164 |
#additionalCacheDirs: [...string] |
| 165 |
#os: string |
| 166 |
|
| 167 |
let goModCacheDirID = "go-mod-cache-dir" |
| 168 |
let goCacheDirID = "go-cache-dir" |
| 169 |
|
| 170 |
// cacheDirs is a convenience variable that includes |
| 171 |
// GitHub expressions that represent the directories |
| 172 |
// that participate in Go caching. |
| 173 |
let cacheDirs = list.Concat([[ |
| 174 |
"${{ steps.\(goModCacheDirID).outputs.dir }}/cache/download", |
| 175 |
"${{ steps.\(goCacheDirID).outputs.dir }}", |
| 176 |
], #additionalCacheDirs]) |
| 177 |
|
| 178 |
let cacheRestoreKeys = "\(#os)-\(#goVersion)" |
| 179 |
|
| 180 |
let cacheStep = json.#step & { |
| 181 |
with: { |
| 182 |
path: strings.Join(cacheDirs, "\n") |
| 183 |
|
| 184 |
// GitHub actions caches are immutable. Therefore, use a key which is |
| 185 |
// unique, but allow the restore to fallback to the most recent cache. |
| 186 |
// The result is then saved under the new key which will benefit the |
| 187 |
// next build. Restore keys are only set if the step is restore. |
| 188 |
key: "\(cacheRestoreKeys)-${{ github.run_id }}" |
| 189 |
"restore-keys": cacheRestoreKeys |
| 190 |
} |
| 191 |
} |
| 192 |
|
| 193 |
let readWriteCacheExpr = "(\(isProtectedBranch) || \(isTestDefaultBranch))" |
| 194 |
|
| 195 |
// pre is the list of steps required to establish and initialise the correct |
| 196 |
// caches for Go-based workflows. |
| 197 |
[ |
| 198 |
// TODO: once https://github.com/actions/setup-go/issues/54 is fixed, |
| 199 |
// we could use `go env` outputs from the setup-go step. |
| 200 |
json.#step & { |
| 201 |
name: "Get go mod cache directory" |
| 202 |
id: goModCacheDirID |
| 203 |
run: #"echo "dir=$(go env GOMODCACHE)" >> ${GITHUB_OUTPUT}"# |
| 204 |
}, |
| 205 |
json.#step & { |
| 206 |
name: "Get go build/test cache directory" |
| 207 |
id: goCacheDirID |
| 208 |
run: #"echo "dir=$(go env GOCACHE)" >> ${GITHUB_OUTPUT}"# |
| 209 |
}, |
| 210 |
|
| 211 |
// Only if we are not running in readonly mode do we want a step that |
| 212 |
// uses actions/cache (read and write). Even then, the use of the write |
| 213 |
// step should be predicated on us running on a protected branch. Because |
| 214 |
// it's impossible for anything else to write such a cache. |
| 215 |
if !#readonly { |
| 216 |
cacheStep & { |
| 217 |
if: readWriteCacheExpr |
| 218 |
uses: "actions/cache@v4" |
| 219 |
} |
| 220 |
}, |
| 221 |
|
| 222 |
cacheStep & { |
| 223 |
// If we are readonly, there is no condition on when we run this step. |
| 224 |
// It should always be run, becase there is no alternative. But if we |
| 225 |
// are not readonly, then we need to predicate this step on us not |
| 226 |
// being on a protected branch. |
| 227 |
if !#readonly { |
| 228 |
if: "! \(readWriteCacheExpr)" |
| 229 |
} |
| 230 |
|
| 231 |
uses: "actions/cache/restore@v4" |
| 232 |
}, |
| 233 |
|
| 234 |
if #cleanTestCache { |
| 235 |
// All tests on protected branches should skip the test cache. The |
| 236 |
// canonical way to do this is with -count=1. However, we want the |
| 237 |
// resulting test cache to be valid and current so that subsequent CLs |
| 238 |
// in the trybot repo can leverage the updated cache. Therefore, we |
| 239 |
// instead perform a clean of the testcache. |
| 240 |
// |
| 241 |
// Critically we only want to do this in the main repo, not the trybot |
| 242 |
// repo. |
| 243 |
json.#step & { |
| 244 |
if: "github.repository == '\(githubRepositoryPath)' && (\(isProtectedBranch) || github.ref == 'refs/heads/\(testDefaultBranch)')" |
| 245 |
run: "go clean -testcache" |
| 246 |
} |
| 247 |
}, |
| 248 |
] |
| 249 |
} |
| 250 |
|
| 251 |
// isProtectedBranch is an expression that evaluates to true if the |
| 252 |
// job is running as a result of pushing to one of protectedBranchPatterns. |
| 253 |
// It would be nice to use the "contains" builtin for simplicity, |
| 254 |
// but array literals are not yet supported in expressions. |
| 255 |
isProtectedBranch: { |
| 256 |
#trailers: [...string] |
| 257 |
"((" + strings.Join([for branch in protectedBranchPatterns { |
| 258 |
(_matchPattern & {variable: "github.ref", pattern: "refs/heads/\(branch)"}).expr |
| 259 |
}], " || ") + ") && (! \(containsDispatchTrailer)))" |
| 260 |
} |
| 261 |
|
| 262 |
// isTestDefaultBranch is an expression that evaluates to true if |
| 263 |
// the job is running on the testDefaultBranch |
| 264 |
isTestDefaultBranch: "(github.ref == 'refs/heads/\(testDefaultBranch)')" |
| 265 |
|
| 266 |
// #isReleaseTag creates a GitHub expression, based on the given release tag |
| 267 |
// pattern, that evaluates to true if called in the context of a workflow that |
| 268 |
// is part of a release. |
| 269 |
isReleaseTag: { |
| 270 |
(_matchPattern & {variable: "github.ref", pattern: "refs/tags/\(releaseTagPattern)"}).expr |
| 271 |
} |
| 272 |
|
| 273 |
checkGitClean: json.#step & { |
| 274 |
name: "Check that git is clean at the end of the job" |
| 275 |
if: "always()" |
| 276 |
run: "test -z \"$(git status --porcelain)\" || (git status; git diff; false)" |
| 277 |
} |
| 278 |
|
| 279 |
repositoryDispatch: json.#step & { |
| 280 |
#githubRepositoryPath: *githubRepositoryPath | string |
| 281 |
#botGitHubUserTokenSecretsKey: *botGitHubUserTokenSecretsKey | string |
| 282 |
#arg: _ |
| 283 |
|
| 284 |
_curlGitHubAPI: curlGitHubAPI & {#tokenSecretsKey: #botGitHubUserTokenSecretsKey, _} |
| 285 |
|
| 286 |
name: string |
| 287 |
run: #""" |
| 288 |
\#(_curlGitHubAPI) --fail --request POST --data-binary \#(strconv.Quote(encjson.Marshal(#arg))) https://api.github.com/repos/\#(#githubRepositoryPath)/dispatches |
| 289 |
"""# |
| 290 |
} |
| 291 |
|
| 292 |
// dispatchTrailer is the trailer that we use to pass information in a commit |
| 293 |
// when triggering workflow events in other GitHub repos. |
| 294 |
// |
| 295 |
// NOTE: keep this consistent with gerritstatusupdater parsing logic. |
| 296 |
dispatchTrailer: "Dispatch-Trailer" |
| 297 |
|
| 298 |
// dispatchTrailerStepID is the ID of the step that attempts |
| 299 |
// to extract a Dispatch-Trailer value from the commit at HEAD |
| 300 |
dispatchTrailerStepID: strings.Replace(dispatchTrailer, "-", "", -1) |
| 301 |
|
| 302 |
// _dispatchTrailerDecodeStepOutputVar is the name of the output |
| 303 |
// variable int he dispatchTrailerStepID step |
| 304 |
_dispatchTrailerDecodeStepOutputVar: "value" |
| 305 |
|
| 306 |
// dispatchTrailerExpr is a GitHub expression that can be dereferenced |
| 307 |
// to get values from the JSON-decded Dispatch-Trailer value that |
| 308 |
// is extracted during the dispatchTrailerStepID step. |
| 309 |
dispatchTrailerExpr: "fromJSON(steps.\(dispatchTrailerStepID).outputs.\(_dispatchTrailerDecodeStepOutputVar))" |
| 310 |
|
| 311 |
// containsDispatchTrailer returns a GitHub expression that looks at the commit |
| 312 |
// message of the head commit of the event that triggered the workflow, an |
| 313 |
// expression that returns true if the commit message associated with that head |
| 314 |
// commit contains dispatchTrailer. |
| 315 |
// |
| 316 |
// Note that this logic does not 100% match the answer that would be returned by: |
| 317 |
// |
| 318 |
// git log --pretty=%(trailers:key=Dispatch-Trailer,valueonly) |
| 319 |
// |
| 320 |
// GitHub expressions are incredibly limited in their capabilities: |
| 321 |
// |
| 322 |
// https://docs.github.com/en/actions/learn-github-actions/expressions |
| 323 |
// |
| 324 |
// There is not even a regular expression matcher. Hence the logic is a best-efforts |
| 325 |
// approximation of the logic employed by git log. |
| 326 |
containsDispatchTrailer: { |
| 327 |
#type?: string |
| 328 |
|
| 329 |
// If we have a value for #type, then match against that value. |
| 330 |
// Otherwise the best we can do is match against: |
| 331 |
// |
| 332 |
// Dispatch-Trailer: {"type:} |
| 333 |
// |
| 334 |
let _typeCheck = [if #type != _|_ {#type + "\""}, ""][0] |
| 335 |
""" |
| 336 |
(contains(\(_dispatchTrailerVariable), '\n\(dispatchTrailer): {"type":"\(_typeCheck)')) |
| 337 |
""" |
| 338 |
} |
| 339 |
|
| 340 |
containsTrybotTrailer: containsDispatchTrailer & { |
| 341 |
#type: trybot.key |
| 342 |
_ |
| 343 |
} |
| 344 |
|
| 345 |
containsUnityTrailer: containsDispatchTrailer & { |
| 346 |
#type: unity.key |
| 347 |
_ |
| 348 |
} |
| 349 |
|
| 350 |
_dispatchTrailerVariable: "github.event.head_commit.message" |