-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathaction.yml
More file actions
445 lines (390 loc) · 16.5 KB
/
Copy pathaction.yml
File metadata and controls
445 lines (390 loc) · 16.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
# Copyright 2023 Chainguard, Inc.
# SPDX-License-Identifier: Apache-2.0
name: 'Update the image digest'
description: 'Update the image digest when have a mutating tag'
inputs:
working-dir:
description: Working directory to run the digestabot, to run in a specific path, if not set will run from the root
required: false
default: .
include-files:
description: Files (names or globs, comma-separated) that will be scanned for digest updates.
required: false
default: '*.yaml,*.yml,Dockerfile*,Makefile*,*.sh,*.tf,*.tfvars'
token:
description: 'GITHUB_TOKEN or a `repo` scoped Personal Access Token (PAT)'
required: true
default: ${{ github.token }}
signoff:
description: 'Add `Signed-off-by` line by the committer at the end of the commit log message.'
default: false
author:
description: >
The author name and email address in the format `Display Name <email@address.com>`.
Defaults to the user who triggered the workflow run.
default: '${{ github.actor }} <${{ github.actor_id }}+${{ github.actor }}@users.noreply.github.com>'
committer:
description: >
The committer name and email address in the format `Display Name <email@address.com>`.
Defaults to the GitHub Actions bot user.
default: 'github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>'
labels-for-pr:
description: 'A comma or newline separated list of labels to be used in the pull request.'
default: automated pr, kind/cleanup, release-note-none
branch-for-pr:
description: 'The pull request branch name.'
default: 'update-digests'
title-for-pr:
description: 'The title of the pull request.'
default: 'Update images digests'
description-for-pr:
description: 'The description of the pull request.'
default: |
Update images digests
```release-note
NONE
```
commit-message:
description: 'The message to use when committing changes.'
default: 'Update images digests'
create-pr:
description: 'Create a PR or just keep the changes locally.'
default: true
use-gitsign:
description: 'Use gitsign to sign commits.'
default: 'true'
registry-map:
description: 'Comma-separated registry prefix mappings (proxy=upstream) for digest lookups. e.g. us-docker.pkg.dev/my-proj/cgr/=cgr.dev/'
required: false
default: ""
outputs:
pull_request_number:
description: "Pull Request Number"
value: ${{ steps.pull_request.outputs.pull_request_number }}
json:
description: |
The changes made by this action, in json format.
The output follows this structure:
```
{
"updates": [
{
"file": ".ko.yaml",
"image": "cgr.dev/chainguard/kubectl:latest-dev",
"digest": "sha256:d5f340d044438351413d6cb110f6f8a2abc45a7149aa53e6ade719f069fc3b0a",
"updated_digest": "sha256:cd90036b16413eed13818500ae837e6e7710a59c74144c32e1e90b0e59d22efc"
}
]
}
```
value: ${{ steps.update_files.outputs.json }}
changed_files:
description: |
A newline-separated list of files that were modified during the digest update process.
Only includes files that actually had their digests updated.
value: ${{ steps.update_files.outputs.changed_files }}
runs:
using: "composite"
steps:
- name: Install crane
shell: bash
run: |
set -euo pipefail
# Pin crane version and checksums
CRANE_VERSION="v0.21.3"
# Detect architecture
arch=$(uname -m)
if [[ "$arch" =~ (aarch64|arm64) ]]; then
arch="arm64"
EXPECTED_CHECKSUM="dabcf2aee76ca72da63b5da5137c910a6852ccff13e35628e8f0a9dd8b73f4f3"
else
arch="x86_64"
EXPECTED_CHECKSUM="46dbf12d943efa5673ab654186c5d7c1503580544de0df9325537083436fe5d0"
fi
echo "Installing crane ${CRANE_VERSION} for Linux ${arch}"
# Download crane from official GitHub releases
crane_tar="go-containerregistry_Linux_${arch}.tar.gz"
crane_url="https://github.com/google/go-containerregistry/releases/download/${CRANE_VERSION}/${crane_tar}"
curl -fsSL --retry 5 --retry-delay 1 --retry-all-errors -o "${crane_tar}" "${crane_url}"
# Verify SHA256 checksum
echo "${EXPECTED_CHECKSUM} ${crane_tar}" | sha256sum --check --strict -
# Extract directly to destination and add to PATH
mkdir -p "${HOME}/.local/bin"
tar -xzf "${crane_tar}" -C "${HOME}/.local/bin" crane
echo "${HOME}/.local/bin" >> "$GITHUB_PATH"
# Verify installation
crane version
# Clean up
rm -f "${crane_tar}"
- name: Authenticate crane
shell: bash
env:
INPUTS_TOKEN: ${{ inputs.token }}
GITHUB_ACTOR: ${{ github.actor }}
run: |
echo "$INPUTS_TOKEN" | crane auth login ghcr.io --username "$GITHUB_ACTOR" --password-stdin
- shell: bash
id: update_files
env:
INPUTS_INCLUDE_FILES: ${{ inputs.include-files }}
INPUTS_WORKING_DIR: ${{ inputs.working-dir }}
INPUTS_REGISTRY_MAP: ${{ inputs.registry-map }}
run: |
# disable the errexit github enable that by default
set +o errexit
IFS=',' read -ra PATTERNS <<< "${INPUTS_INCLUDE_FILES}"
REGISTRY_MAPPINGS=()
if [ -n "${INPUTS_REGISTRY_MAP}" ] ; then
IFS=',' read -ra REGISTRY_MAPPINGS <<< "${INPUTS_REGISTRY_MAP}"
fi
json='{}'
changed_files=()
while IFS= read -r -d '' file; do
if [[ "$file" == *testdata* ]]; then
echo "Skipping testdata ${file}"
continue
fi
# Extract all image references and their digests
mapfile -t image_lines < <(grep -i -E '[a-z0-9]+([._-][a-z0-9]+)*(/[a-z0-9]+([._-][a-z0-9]+)*)*@sha256:[a-z0-9]+' "$file" || true)
for line in "${image_lines[@]}"; do
image=$(echo "$line" | cut -d @ -f1 | rev | cut -d = -f1 | cut -d ' ' -f1 | cut -d '"' -f1 | rev | sed -e "s/^docker:\/\///" | tr -d '' | tr -d '\t')
# Extract exactly the sha256 digest (64 hex chars). Using grep -oE
# instead of cut to avoid capturing adjacent syntax characters like
# } in shell scripts (e.g. ${VAR:=image@sha256:...}") or ' in YAML
# (e.g. 'image@sha256:...'), which the old cut pipeline would include
# in the digest and then sed would delete during replacement.
digest=$(echo "$line"| grep -oE 'sha256:[a-f0-9]{64}' | head -1)
if [[ "$image" != *":"* ]]; then
echo "Image $image in file $file does not have a tag, ignoring..."
continue
fi
if [[ "$image" == *\.local:* ]]; then
echo "Skipping local registry image $image"
continue
fi
echo "Processing $image in file $file"
lookup_image="$image"
for mapping in "${REGISTRY_MAPPINGS[@]}"; do
proxy="${mapping%%=*}"
upstream="${mapping#*=}"
if [[ "$lookup_image" == "${proxy}"* ]]; then
lookup_image="${upstream}${lookup_image#"${proxy}"}"
echo " Registry mapping: querying $lookup_image instead of $image"
break
fi
done
updated_digest=
crane digest "$lookup_image" > digest.log 2> logerror.txt
if [ $? -eq 0 ]; then
updated_digest=$(cat digest.log)
else
ERRMSG="Failed to retrieve digest info for $image"
[ "$lookup_image" != "$image" ] && ERRMSG="$ERRMSG (upstream: $lookup_image)"
echo "$ERRMSG"
echo "$ERRMSG" >> "$GITHUB_STEP_SUMMARY"
cat logerror.txt >> "$GITHUB_STEP_SUMMARY"
fi
rm -f logerror.txt
rm -f digest.log
if [ "$updated_digest" != "$digest" ] && [ -n "$updated_digest" ]; then
echo "Digest $digest for image $image is different, new digest is $updated_digest, updating..."
sed -i -e "s|$image@$digest|$image@$updated_digest|g" "$file"
# Add file to changed_files array if not already present
# Quoted RHS is intentional: literal match guards against regex
# metacharacters in filenames; see docs/backlog.md for refactor note
# shellcheck disable=SC2076
if [[ ! " ${changed_files[*]} " =~ " ${file} " ]]; then
changed_files+=("$file")
fi
json=$(jq -c \
--arg file "${file}" \
--arg image "${image}" \
--arg digest "${digest}" \
--arg updated_digest "${updated_digest}" \
'.updates += [{file: $file, image: $image, digest: $digest, updated_digest: $updated_digest}]' <<<"${json}")
fi
done
done < <(
find_args=()
for i in "${!PATTERNS[@]}"; do
if [ "$i" -eq 0 ]; then
find_args+=(-name "${PATTERNS[$i]}")
else
find_args+=(-o -name "${PATTERNS[$i]}")
fi
done
find "${INPUTS_WORKING_DIR}" -type f \( "${find_args[@]}" \) -print0
)
echo "json=${json}" >> "${GITHUB_OUTPUT}"
# Output the list of changed files
if [ ${#changed_files[@]} -gt 0 ]; then
echo "changed_files<<EOF" >> "${GITHUB_OUTPUT}"
printf '%s\n' "${changed_files[@]}" >> "${GITHUB_OUTPUT}"
echo "EOF" >> "${GITHUB_OUTPUT}"
else
echo "changed_files=" >> "${GITHUB_OUTPUT}"
fi
- name: Check workspace
id: create_pr_update
env:
CREATE_PR: ${{ inputs.create-pr }}
shell: bash
working-directory: ${{ inputs.working-dir }}
run: |
git diff --stat
echo "create_pr_update=false" >> "$GITHUB_OUTPUT"
if [[ $(git diff --stat) != '' ]] && [[ "${CREATE_PR}" == 'true' ]]; then
echo "create_pr_update=true" >> "$GITHUB_OUTPUT"
echo "diff<<EOF" >> "${GITHUB_OUTPUT}"
git diff >> "${GITHUB_OUTPUT}"
echo "EOF" >> "${GITHUB_OUTPUT}"
fi
# Configure gitsign for signed commits
- uses: chainguard-dev/actions/setup-gitsign@fabe4ed3f66ceb5f8ec86ed7ae6d0c945ca362fb # v1.6.28
if: ${{ steps.create_pr_update.outputs.create_pr_update == 'true' && inputs.use-gitsign == 'true' }}
- name: Configure git credentials
if: ${{ steps.create_pr_update.outputs.create_pr_update == 'true' }}
shell: bash
env:
INPUTS_TOKEN: ${{ inputs.token }}
run: |
git config --global credential.helper store
echo "https://x-access-token:${INPUTS_TOKEN}@github.com" > ~/.git-credentials
- name: Create Pull Request
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0
if: ${{ steps.create_pr_update.outputs.create_pr_update == 'true' }}
id: pull_request
env:
COMMIT_MESSAGE: ${{ inputs.commit-message }}
PR_TITLE: ${{ inputs.title-for-pr }}
PR_BODY: ${{ inputs.description-for-pr }}
PR_DIFF: ${{ steps.create_pr_update.outputs.diff }}
PR_LABELS: ${{ inputs.labels-for-pr }}
PR_BRANCH: ${{ inputs.branch-for-pr }}
AUTHOR: ${{ inputs.author }}
COMMITTER: ${{ inputs.committer }}
SIGNOFF: ${{ inputs.signoff }}
USE_GITSIGN: ${{ inputs.use-gitsign }}
CHANGED_FILES: ${{ steps.update_files.outputs.changed_files }}
WORKING_DIR: ${{ inputs.working-dir }}
with:
github-token: ${{ inputs.token }}
script: |
const { execFileSync } = require('child_process');
try {
// Parse author and committer
const parseIdentity = (identity) => {
const match = identity.match(/^(.+?)\s*<(.+?)>$/);
if (!match) throw new Error(`Invalid identity format: ${identity}`);
return { name: match[1].trim(), email: match[2].trim() };
};
const author = parseIdentity(process.env.AUTHOR);
const committer = parseIdentity(process.env.COMMITTER);
const prBranch = process.env.PR_BRANCH;
const changedFiles = process.env.CHANGED_FILES.split('\n').filter(f => f.trim());
// Helper to run git commands
const git = (...args) => {
return execFileSync('git', args, { encoding: 'utf8' }).trim();
};
// Get base branch and create/reset PR branch
const baseBranch = git('branch', '--show-current');
let branchExists = false;
try {
git('rev-parse', '--verify', prBranch);
branchExists = true;
} catch (e) {}
if (branchExists) {
git('checkout', prBranch);
git('reset', '--hard', baseBranch);
} else {
git('checkout', '-b', prBranch);
}
// Stage changed files
for (const file of changedFiles) {
git('add', '--', file);
}
// Commit with proper author/committer
const commitArgs = ['commit', '-m', process.env.COMMIT_MESSAGE];
if (process.env.SIGNOFF === 'true') {
commitArgs.push('--signoff');
}
execFileSync('git', commitArgs, {
encoding: 'utf8',
env: {
...process.env,
GIT_AUTHOR_NAME: author.name,
GIT_AUTHOR_EMAIL: author.email,
GIT_COMMITTER_NAME: committer.name,
GIT_COMMITTER_EMAIL: committer.email,
}
});
console.log(`Committed: ${git('rev-parse', 'HEAD')}`);
// Push branch
git('push', 'origin', prBranch, '--force');
// Check if PR already exists
const { owner, repo } = context.repo;
const allPRs = await github.rest.pulls.list({
owner,
repo,
head: `${owner}:${prBranch}`,
state: 'all'
});
const openPR = allPRs.data.find(pr => pr.state === 'open');
const closedPR = allPRs.data.find(pr => pr.state === 'closed');
const labels = process.env.PR_LABELS.split(/[,\n]/).map(l => l.trim()).filter(l => l);
// Build PR body
const diffFence = '```';
const prBody = process.env.PR_BODY + '\n\n## Changes\n<details>\n\n' +
diffFence + 'diff\n' + process.env.PR_DIFF + '\n' + diffFence + '\n\n</details>';
// Helper functions
const updatePR = async (prNumber) => {
await github.rest.pulls.update({
owner,
repo,
pull_number: prNumber,
title: process.env.PR_TITLE,
body: prBody
});
};
const addLabels = async (prNumber) => {
if (labels.length > 0) {
await github.rest.issues.addLabels({ owner, repo, issue_number: prNumber, labels });
}
};
let prNumber;
if (openPR) {
// Update existing open PR
prNumber = openPR.number;
await updatePR(prNumber);
} else if (closedPR) {
// Closed PR exists (merged or just closed) - create a new PR instead of trying to reopen
console.log(`Found closed PR #${closedPR.number}, creating new PR instead`);
const { data: pr } = await github.rest.pulls.create({
owner,
repo,
head: prBranch,
base: baseBranch,
title: process.env.PR_TITLE,
body: prBody
});
prNumber = pr.number;
} else {
// No existing PR - create new one
const { data: pr } = await github.rest.pulls.create({
owner,
repo,
head: prBranch,
base: baseBranch,
title: process.env.PR_TITLE,
body: prBody
});
prNumber = pr.number;
}
// Add labels to PR
await addLabels(prNumber);
core.setOutput('pull_request_number', prNumber.toString());
console.log(`PR #${prNumber}`);
} catch (error) {
core.setFailed(`Failed to create pull request: ${error.message}`);
console.error(error);
}