Skip to content

Commit 6f2090e

Browse files
committed
Move the monorepo example into workflows/
The 171-line per-workspace workflow lived only in docs/ci-cd.md, where no linter checked it. It's now a template alongside the others, covered by actionlint, zizmor and the pin test, and the guide links to it.
1 parent 18fc901 commit 6f2090e

5 files changed

Lines changed: 235 additions & 192 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,9 @@
1616
command doesn't update the required check until the pull request workflow runs
1717
again, and how to pin the `socketdev/cli` image to a release. The guide's own
1818
examples pin their actions to commits.
19+
- The per-workspace monorepo example moved from the CI guide to
20+
[`workflows/github-actions-monorepo.yml`](workflows/github-actions-monorepo.yml),
21+
so it's linted and kept current with the other examples. The guide links to it.
1922

2023
## 2.14.0
2124

‎README.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -205,7 +205,7 @@ JSON:
205205

206206
Prebuilt workflow examples:
207207

208-
- GitHub Actions for [pull requests](https://github.com/SocketDev/socket-python-cli/blob/main/workflows/github-actions.yml), [pushes](https://github.com/SocketDev/socket-python-cli/blob/main/workflows/github-actions-push.yml), and [ignore commands](https://github.com/SocketDev/socket-python-cli/blob/main/workflows/github-actions-comments.yml)
208+
- GitHub Actions for [pull requests](https://github.com/SocketDev/socket-python-cli/blob/main/workflows/github-actions.yml), [pushes](https://github.com/SocketDev/socket-python-cli/blob/main/workflows/github-actions-push.yml), and [ignore commands](https://github.com/SocketDev/socket-python-cli/blob/main/workflows/github-actions-comments.yml), or [per-workspace monorepo scans](https://github.com/SocketDev/socket-python-cli/blob/main/workflows/github-actions-monorepo.yml)
209209
- [Buildkite](https://github.com/SocketDev/socket-python-cli/blob/main/workflows/buildkite.yml)
210210
- [GitLab CI](https://github.com/SocketDev/socket-python-cli/blob/main/workflows/gitlab-ci.yml)
211211
- [Bitbucket Pipelines](https://github.com/SocketDev/socket-python-cli/blob/main/workflows/bitbucket-pipelines.yml)

‎docs/ci-cd.md‎

Lines changed: 9 additions & 178 deletions
Original file line numberDiff line numberDiff line change
@@ -182,185 +182,16 @@ logical graph. If root workspace metadata governs most or all of the repository,
182182
smaller coverage-preserving split may not be representable with `--sub-path` alone.
183183

184184
Also define `SOCKETCLI_VERSION` as the exact package version validated for the
185-
workflow. The workflow below logs that version, uses full Git history for reliable
186-
base/head selection, creates one matrix job (and therefore one graph and baseline)
187-
per selected workspace, and fails closed on CLI/API/timeout failures. It uses API
185+
workflow. The [monorepo workflow](../workflows/github-actions-monorepo.yml) logs
186+
that version, uses full Git history for reliable base/head selection, creates one
187+
matrix job (and therefore one graph and baseline) per selected workspace, and
188+
fails closed on CLI/API/timeout failures. It uses API
188189
SCM mode plus `--enable-diff` because parallel `--scm github` jobs can race while
189190
updating the same PR comments; the matrix checks and report links are the gate.
190191

191-
```yaml
192-
name: Socket Security
193-
194-
on:
195-
pull_request:
196-
types: [opened, synchronize, reopened]
197-
push:
198-
branches: [main]
199-
200-
permissions:
201-
contents: read
202-
203-
jobs:
204-
select-workspaces:
205-
runs-on: ubuntu-latest
206-
outputs:
207-
count: ${{ steps.select.outputs.count }}
208-
matrix: ${{ steps.select.outputs.matrix }}
209-
steps:
210-
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
211-
with:
212-
fetch-depth: 0
213-
persist-credentials: false
214-
215-
- id: select
216-
name: Select changed workspaces
217-
env:
218-
WORKSPACES_JSON: ${{ vars.SOCKET_MONOREPO_WORKSPACES_JSON }}
219-
BASE_SHA: ${{ github.event.pull_request.base.sha || github.event.before }}
220-
HEAD_SHA: ${{ github.event.pull_request.head.sha || github.sha }}
221-
shell: bash
222-
run: |
223-
python - <<'PY'
224-
import fnmatch
225-
import json
226-
import os
227-
import re
228-
import subprocess
229-
230-
workspaces = json.loads(os.environ["WORKSPACES_JSON"])
231-
if not isinstance(workspaces, list):
232-
raise SystemExit("SOCKET_MONOREPO_WORKSPACES_JSON must be a JSON array")
233-
234-
base = os.environ["BASE_SHA"]
235-
head = os.environ["HEAD_SHA"]
236-
if not base or set(base) == {"0"}:
237-
base = subprocess.check_output(
238-
["git", "rev-parse", f"{head}^"], text=True
239-
).strip()
240-
changed_output = subprocess.check_output(
241-
["git", "diff", "--name-only", "-z", base, head]
242-
)
243-
changed = [
244-
item.decode("utf-8", "surrogateescape")
245-
for item in changed_output.split(b"\0")
246-
if item
247-
]
248-
249-
selected = []
250-
for workspace in workspaces:
251-
name = workspace.get("name", "")
252-
sub_paths = workspace.get("sub_paths") or []
253-
watch_globs = workspace.get("watch_globs") or []
254-
if not re.fullmatch(r"[A-Za-z0-9._-]+", name):
255-
raise SystemExit(f"Invalid workspace name: {name!r}")
256-
if not sub_paths or any(
257-
not isinstance(path, str)
258-
or path.startswith("/")
259-
or ".." in path.split("/")
260-
for path in sub_paths
261-
):
262-
raise SystemExit(f"Invalid sub_paths for workspace {name!r}")
263-
if not watch_globs:
264-
watch_globs = [
265-
pattern
266-
for path in sub_paths
267-
for pattern in (
268-
["*"]
269-
if path.strip("/") in ("", ".")
270-
else [path.rstrip("/"), f"{path.rstrip('/')}/*"]
271-
)
272-
]
273-
if any(
274-
fnmatch.fnmatchcase(path, pattern)
275-
for path in changed
276-
for pattern in watch_globs
277-
):
278-
selected.append({"name": name, "sub_paths": sub_paths})
279-
280-
matrix = json.dumps({"include": selected}, separators=(",", ":"))
281-
with open(os.environ["GITHUB_OUTPUT"], "a", encoding="utf-8") as output:
282-
output.write(f"count={len(selected)}\n")
283-
output.write(f"matrix={matrix}\n")
284-
PY
285-
286-
scan-workspace:
287-
needs: select-workspaces
288-
if: needs.select-workspaces.outputs.count != '0'
289-
timeout-minutes: 20
290-
strategy:
291-
fail-fast: false
292-
matrix: ${{ fromJSON(needs.select-workspaces.outputs.matrix) }}
293-
name: Socket scan (${{ matrix.name }})
294-
runs-on: ubuntu-latest
295-
steps:
296-
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
297-
with:
298-
fetch-depth: 0
299-
persist-credentials: false
300-
301-
- uses: actions/setup-python@6d4fd22b20465ccc0f7354476588e8df7c9ca0e0 # v7.1.0
302-
with:
303-
python-version: '3.12'
304-
305-
- name: Install pinned Socket CLI
306-
env:
307-
SOCKETCLI_VERSION: ${{ vars.SOCKETCLI_VERSION }}
308-
run: |
309-
python -m pip install "socketsecurity==$SOCKETCLI_VERSION"
310-
socketcli --version
311-
312-
- name: Scan workspace
313-
env:
314-
SOCKET_SECURITY_API_KEY: ${{ secrets.SOCKET_SECURITY_API_KEY }}
315-
PR_NUMBER: ${{ github.event.pull_request.number || 0 }}
316-
WORKSPACE_NAME: ${{ matrix.name }}
317-
SUB_PATHS_JSON: ${{ toJSON(matrix.sub_paths) }}
318-
shell: bash
319-
run: |
320-
set +e
321-
args=(
322-
--target-path "$GITHUB_WORKSPACE"
323-
--workspace-name "$WORKSPACE_NAME"
324-
--enable-diff
325-
--pr-number "$PR_NUMBER"
326-
--exit-code-on-api-error 3
327-
--report-link-file socket-report-link.txt
328-
--summary-file socket-summary.txt
329-
)
330-
while IFS= read -r sub_path; do
331-
args+=(--sub-path "$sub_path")
332-
done < <(jq -r '.[]' <<<"$SUB_PATHS_JSON")
333-
334-
socketcli "${args[@]}" 2>&1 | tee socket-output.log
335-
code=${PIPESTATUS[0]}
336-
337-
{
338-
echo "## Socket scan: $WORKSPACE_NAME"
339-
if [ -s socket-report-link.txt ]; then
340-
echo "[View the report]($(cat socket-report-link.txt))"
341-
fi
342-
if [ -s socket-summary.txt ]; then
343-
echo '```'
344-
cat socket-summary.txt
345-
echo '```'
346-
fi
347-
} >> "$GITHUB_STEP_SUMMARY"
348-
349-
exit "$code"
350-
351-
socket-security:
352-
if: always()
353-
needs: [select-workspaces, scan-workspace]
354-
runs-on: ubuntu-latest
355-
steps:
356-
- name: Enforce matrix result
357-
env:
358-
SELECT_RESULT: ${{ needs.select-workspaces.result }}
359-
SCAN_RESULT: ${{ needs.scan-workspace.result }}
360-
run: |
361-
test "$SELECT_RESULT" = success
362-
[[ "$SCAN_RESULT" = success || "$SCAN_RESULT" = skipped ]]
363-
```
192+
Copy it to `.github/workflows/` in place of the [PR workflow](../workflows/github-actions.yml)
193+
and require its `socket-security` job, the aggregate gate. It reports a result
194+
even when no workspace changed, so the required check never stays pending.
364195

365196
Each configuration object may intentionally contain several `sub_paths` when
366197
those directories are one logical dependency graph. To split backend resolution,
@@ -369,7 +200,7 @@ when the Socket organization requires API workspace association; it is not a sca
369200
scope control. Use `--save-submitted-files-list` in a non-required canary to verify
370201
the exact manifests selected before adopting workspace-level scans as a merge gate.
371202

372-
The job has an explicit 20-minute total budget. Tune that value from observed
203+
Its scan job has an explicit 20-minute total budget. Tune that value from observed
373204
workspace-level latency after the split; a five-minute cap can still be too close
374205
to a slow request plus local startup. The CLI's `--timeout` is different: it
375206
defaults to 1,200 seconds **per API request**. If an operator adds GNU `timeout`,
@@ -706,7 +537,7 @@ listed thinly or not at all.
706537

707538
Prebuilt examples in this repo:
708539

709-
- GitHub Actions for [pull requests](../workflows/github-actions.yml), [pushes](../workflows/github-actions-push.yml), and [ignore commands](../workflows/github-actions-comments.yml)
540+
- GitHub Actions for [pull requests](../workflows/github-actions.yml), [pushes](../workflows/github-actions-push.yml), and [ignore commands](../workflows/github-actions-comments.yml), or [per-workspace monorepo scans](../workflows/github-actions-monorepo.yml)
710541
- [`../workflows/buildkite.yml`](../workflows/buildkite.yml)
711542
- [`../workflows/gitlab-ci.yml`](../workflows/gitlab-ci.yml)
712543
- [`../workflows/bitbucket-pipelines.yml`](../workflows/bitbucket-pipelines.yml)

‎tests/unit/test_workflow_templates.py‎

Lines changed: 31 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@ def test_the_templates_exist():
3838
"github-actions.yml",
3939
"github-actions-push.yml",
4040
"github-actions-comments.yml",
41+
"github-actions-monorepo.yml",
4142
}
4243

4344

@@ -63,16 +64,33 @@ def test_examples_use_the_same_commit_as_ci(path):
6364
assert not stale, "update these to the commit .github/workflows uses: " + "; ".join(stale)
6465

6566

66-
def test_only_the_pull_request_workflow_reports_the_required_check():
67-
"""GitHub counts a skipped job as passing, so the required check needs its own workflow."""
68-
pr_workflow = (ROOT / "workflows" / "github-actions.yml").read_text()
69-
on_block = re.search(r"^on:\n((?:[ \t]+.*\n|\n)*)", pr_workflow, re.M).group(1)
70-
triggers = re.findall(r"^ (\w+):", on_block, re.M)
71-
assert triggers == ["pull_request"]
72-
for path in TEMPLATES:
73-
names = re.findall(r"^ ([\w-]+):\n|^ name: ([\w-]+)$", path.read_text(), re.M)
74-
reported = {job or name for job, name in names}
75-
if path.name == "github-actions.yml":
76-
assert "socket-security" in reported
77-
else:
78-
assert "socket-security" not in reported, f"{path.name} reports the required check name"
67+
def _triggers(text):
68+
on_block = re.search(r"^on:\n((?:[ \t]+.*\n|\n)*)", text, re.M).group(1)
69+
return re.findall(r"^ (\w+):", on_block, re.M), on_block
70+
71+
72+
def _reports_required_check(text):
73+
names = re.findall(r"^ ([\w-]+):\n|^ name: ([\w-]+)$", text, re.M)
74+
return "socket-security" in {job or name for job, name in names}
75+
76+
77+
def test_the_pull_request_workflow_owns_the_required_check():
78+
"""GitHub counts a skipped job as passing, so the required check needs a PR-only workflow."""
79+
text = (ROOT / "workflows" / "github-actions.yml").read_text()
80+
assert _triggers(text)[0] == ["pull_request"]
81+
assert _reports_required_check(text)
82+
83+
84+
@pytest.mark.parametrize("name", ["github-actions-push.yml", "github-actions-comments.yml"])
85+
def test_companion_workflows_never_report_the_required_check(name):
86+
assert not _reports_required_check((ROOT / "workflows" / name).read_text())
87+
88+
89+
def test_the_monorepo_gate_always_reports_and_never_runs_on_every_push():
90+
"""The alternative workflow's gate must not be skipped or reported by branch pushes."""
91+
text = (ROOT / "workflows" / "github-actions-monorepo.yml").read_text()
92+
gate = re.search(r"^ socket-security:\n((?: .*\n|\n)*)", text, re.M).group(1)
93+
assert re.search(r"^ if: always\(\)$", gate, re.M)
94+
triggers, on_block = _triggers(text)
95+
assert "pull_request" in triggers
96+
assert "'**'" not in on_block and '"**"' not in on_block

0 commit comments

Comments
 (0)