id: vale-docs-style-gate
namespace: company.team
description: |
On every push to a documentation repository, lint the Markdown with Vale,
compare the alerts with the accepted baseline of the base branch kept in the
KV store, and block the merge when the push adds new error-level alerts. New
warnings are logged, and a clean run on the base branch becomes the new
baseline.
inputs:
- id: repository_url
type: STRING
defaults: "https://github.com/acme/docs.git"
displayName: "Repository URL"
description: "Git repository of the documentation. It must contain a `.vale.ini`."
- id: branch
type: STRING
defaults: "main"
displayName: "Branch"
description: "Branch that was pushed."
- id: base_branch
type: STRING
defaults: "main"
displayName: "Base Branch"
description: "Branch whose accepted alerts form the baseline. Only clean runs on
this branch update it."
- id: docs_path
type: STRING
defaults: "docs"
displayName: "Docs Path"
description: "Folder (or file) to lint, relative to the repository root."
variables:
baseline_key: "{{ ('vale-baseline-' ~ inputs.repository_url ~ '-' ~
inputs.base_branch) | slugify }}"
history_key: "{{ ('vale-history-' ~ inputs.repository_url ~ '-' ~
inputs.base_branch) | slugify }}"
triggers:
- id: on_push
type: io.kestra.plugin.core.trigger.Webhook
description: Point the docs repository's GitHub push webhook (JSON) at this
trigger. Branch deletions and non-branch refs are ignored. Shipped
disabled.
disabled: true
key: "{{ secret('VALE_GATE_WEBHOOK_KEY') }}"
when: "{{ (trigger.body.ref ?? '') contains 'refs/heads/' and not
(trigger.body.deleted ?? false) }}"
inputs:
repository_url: "{{ trigger.body.repository.clone_url }}"
branch: "{{ trigger.body.ref | replace({'refs/heads/': ''}) }}"
base_branch: "{{ trigger.body.repository.default_branch }}"
tasks:
- id: lint
type: io.kestra.plugin.core.flow.WorkingDirectory
description: Clone the pushed branch, lint it with Vale and compare the alerts
with the baseline, in one working directory.
tasks:
- id: clone
type: io.kestra.plugin.git.Clone
description: Shallow clone of the pushed branch. For a private repository add
`username` and `password` from a secret.
url: "{{ inputs.repository_url }}"
branch: "{{ inputs.branch }}"
depth: 1
- id: vale
type: io.kestra.plugin.scripts.shell.Commands
description: Run Vale 3.24.0 (official image) with the repository's own
`.vale.ini` and styles. `vale sync` installs the packages the config
lists; `--no-exit` keeps alerts from failing the task, so only a
broken config does.
containerImage: jdkato/vale:v3.24.0
commands:
- vale --version
- vale sync
- rc=0; vale --output=JSON --no-exit {{ inputs.docs_path }} >
vale.json || rc=$?; if [ $rc -ne 0 ]; then cat vale.json; exit $rc;
fi
timeout: PT10M
- id: compare_with_baseline
type: io.kestra.plugin.scripts.python.Script
description: Fingerprint every alert (rule, file, message; no line numbers, so
edits elsewhere in a file do not count as new), count them by
severity, compare the counts with the baseline, and prepare the next
point of the base branch's alert history. With no baseline yet, a run
on the base branch adopts the current alerts.
containerImage: python:3.12-slim
inputFiles:
baseline.json: "{{ kv(render(vars.baseline_key), errorOnMissing=false) | toJson }}"
history.json: "{{ kv(render(vars.history_key), errorOnMissing=false) | toJson }}"
outputFiles:
- vale.json
- baseline.json
- history.json
script: |
import collections, datetime, json
on_base = "{{ inputs.branch }}" == "{{ inputs.base_branch }}"
report = json.load(open("vale.json", encoding="utf-8")) or {}
stored = json.load(open("baseline.json", encoding="utf-8"))
current, severity, places = collections.Counter(), {}, collections.defaultdict(list)
by_severity = collections.Counter()
for path, alerts in report.items():
path = path.replace("\\", "/")
for a in alerts:
fp = f"{a['Check']}|{path}|{a['Message']}"
current[fp] += 1
severity[fp] = a["Severity"]
by_severity[a["Severity"]] += 1
places[fp].append(f"{path}:{a['Line']}")
adopted = stored is None and on_base
accepted = collections.Counter(current if adopted else (stored or {}))
new = {fp: n - accepted[fp] for fp, n in current.items() if n > accepted[fp]}
fixed = sum(n - current[fp] for fp, n in accepted.items() if n > current[fp])
def lines(level):
out = []
for fp, n in sorted(new.items()):
if severity[fp] == level:
check, path, message = fp.split("|", 2)
out.append(f"{', '.join(places[fp])}: {message} ({check}, {n} new)")
return out
new_errors, new_warnings = lines("error"), lines("warning")
json.dump(dict(current), open("baseline.json", "w", encoding="utf-8"), indent=1, sort_keys=True)
history = json.load(open("history.json", encoding="utf-8")) or []
point = {"at": datetime.datetime.now(datetime.timezone.utc).isoformat(timespec="seconds"), "branch": "{{ inputs.branch }}",
"error": by_severity["error"], "warning": by_severity["warning"], "suggestion": by_severity["suggestion"]}
json.dump((history + [point])[-30:], open("history.json", "w", encoding="utf-8"))
recent = (history + [point])[-6:]
trend = ", ".join(f"{level}s " + " -> ".join(str(p[level]) for p in recent) for level in ("error", "warning"))
print("::" + json.dumps({"outputs": {
"total": sum(current.values()), "by_severity": dict(by_severity),
"accepted": sum(min(n, accepted[fp]) for fp, n in current.items()),
"new_errors": sum(new[fp] for fp in new if severity[fp] == "error"),
"new_warnings": sum(new[fp] for fp in new if severity[fp] == "warning"),
"new_suggestions": sum(new[fp] for fp in new if severity[fp] == "suggestion"),
"fixed": fixed, "had_baseline": stored is not None, "adopted": adopted, "on_base_branch": on_base,
"error_lines": new_errors[:25], "warning_lines": new_warnings[:25],
"trend": trend, "history_points": len(history),
}}) + "::")
- id: log_summary
type: io.kestra.plugin.core.log.Log
description: Log the totals against the baseline.
message: "Vale on {{ inputs.branch }} ({{ inputs.docs_path }}): {{
outputs.compare_with_baseline.vars.total }} alert(s) {{
outputs.compare_with_baseline.vars.by_severity }}, {{
outputs.compare_with_baseline.vars.accepted }} accepted in the {{
inputs.base_branch }} baseline{{
outputs.compare_with_baseline.vars.adopted ? ' (adopted on this first
run)' : '' }}, new: {{ outputs.compare_with_baseline.vars.new_errors }}
error(s), {{ outputs.compare_with_baseline.vars.new_warnings }}
warning(s), {{ outputs.compare_with_baseline.vars.new_suggestions }}
suggestion(s); {{ outputs.compare_with_baseline.vars.fixed }} accepted
alert(s) fixed."
- id: report_new_warnings
type: io.kestra.plugin.core.flow.If
description: New warnings do not block the merge, but they are listed for the author.
condition: "{{ outputs.compare_with_baseline.vars.new_warnings > 0 }}"
then:
- id: log_new_warnings
type: io.kestra.plugin.core.log.Log
level: WARN
message: |-
{{ outputs.compare_with_baseline.vars.new_warnings }} new Vale warning(s) on {{ inputs.branch }}:{% for line in outputs.compare_with_baseline.vars.warning_lines %}
- {{ line }}{% endfor %}
- id: gate
type: io.kestra.plugin.core.flow.If
description: Block the merge on new error-level alerts. On a clean run, the base
branch's baseline is replaced with the current alerts, so fixed alerts
drop out and accepted warnings stop being reported.
condition: "{{ outputs.compare_with_baseline.vars.new_errors > 0 }}"
then:
- id: block_merge
type: io.kestra.plugin.core.execution.Fail
errorMessage: |-
Merge blocked: {{ outputs.compare_with_baseline.vars.new_errors }} new Vale error(s) on {{ inputs.branch }}{{ outputs.compare_with_baseline.vars.had_baseline ? '' : ' (no baseline for ' ~ inputs.base_branch ~ ' yet, run the gate on it first)' }}:{% for line in outputs.compare_with_baseline.vars.error_lines %}
- {{ line }}{% endfor %}
else:
- id: update_baseline
type: io.kestra.plugin.core.flow.If
condition: "{{ outputs.compare_with_baseline.vars.on_base_branch }}"
then:
- id: save_baseline
type: io.kestra.plugin.core.kv.Set
description: Store the current alert counts as the accepted baseline of the base
branch.
key: "{{ render(vars.baseline_key) }}"
value: "{{ read(outputs.compare_with_baseline.outputFiles['baseline.json']) }}"
kvType: JSON
- id: log_baseline_saved
type: io.kestra.plugin.core.log.Log
message: "Vale gate passed on {{ inputs.base_branch }}; baseline {{
render(vars.baseline_key) }} now holds {{
outputs.compare_with_baseline.vars.total }} accepted alert(s).
Trend over the last base-branch runs: {{
outputs.compare_with_baseline.vars.trend }}."
- id: save_history
type: io.kestra.plugin.core.kv.Set
description: Append this run's totals to the base branch's alert history (last
30 runs), so the trend over time stays visible.
key: "{{ render(vars.history_key) }}"
value: "{{ read(outputs.compare_with_baseline.outputFiles['history.json']) }}"
kvType: JSON
else:
- id: log_passed
type: io.kestra.plugin.core.log.Log
message: "Vale gate passed on {{ inputs.branch }}: no new error compared with
the {{ inputs.base_branch }} baseline. The baseline changes only
after the merge."
outputs:
- id: new_errors
type: INT
value: "{{ outputs.compare_with_baseline.vars.new_errors }}"
- id: report
type: FILE
value: "{{ outputs.compare_with_baseline.outputFiles['vale.json'] }}"