id: scheduled-markdown-link-audit
namespace: company.team
description: Audit external HTTP(S) links in Markdown from a public GitHub
repository. Save HTTP absence and uncertain-result reports separately, without
running repository code.
inputs:
- id: repository
type: STRING
defaults: https://github.com/kestra-io/blueprints.git
- id: branch
type: STRING
defaults: main
- id: markdown_glob
type: STRING
defaults: README.md
triggers:
- id: weekly
type: io.kestra.plugin.core.trigger.Schedule
cron: 17 7 * * 1
disabled: true
tasks:
- id: validate_repository
type: io.kestra.plugin.scripts.shell.Commands
taskRunner:
type: io.kestra.plugin.core.runner.Process
env:
REPOSITORY: '{{ inputs.repository }}'
inputFiles:
validate.py: "import os,re
url=os.environ['REPOSITORY']
if not
re.fullmatch(r'https://github\\.com/[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+(?:\
\\.git)?',url):
\ raise ValueError('This example only audits public github.com
repositories over HTTPS')\n"
commands:
- python3 validate.py
- id: audit
type: io.kestra.plugin.core.flow.WorkingDirectory
tasks:
- id: clone
type: io.kestra.plugin.git.Clone
url: '{{ inputs.repository }}'
branch: '{{ inputs.branch }}'
directory: repository
cloneSubmodules: false
- id: scan
type: io.kestra.plugin.scripts.shell.Commands
taskRunner:
type: io.kestra.plugin.core.runner.Process
env:
MARKDOWN_GLOB: '{{ inputs.markdown_glob }}'
commands:
- lychee --version | grep -Fx "lychee 0.24.2"
- python3 select_files.py
- cd repository; set +e; lychee --config /dev/null --no-progress
--exclude-all-private --include-mail=false --exclude "^file:"
--max-concurrency 2 --max-retries 0 --timeout 15 --format json
--files-from markdown-files.txt > ../lychee.json; result=$?; set -e;
test "$result" -eq 0 -o "$result" -eq 2; test -s ../lychee.json
outputFiles:
- lychee.json
inputFiles:
select_files.py: "import glob,json,os
from pathlib import Path
root=Path('repository').resolve()
pattern=os.environ['MARKDOWN_GLOB']
if pattern.startswith(('/', '-')) or '..' in Path(pattern).parts or
'\\n' in pattern:
\ raise ValueError('Use a relative Markdown glob without parent
traversal')
selected=[]
for name in sorted(glob.glob(str(root/pattern),recursive=True)):
\ path=Path(name)
\ if not path.is_file() or path.suffix.lower() not in
('.md','.markdown'):continue
\ if path.is_symlink() or not
path.resolve().is_relative_to(root):
\ raise ValueError('Markdown files must stay inside the
checkout, without symlinks')
\ if path.stat().st_size>1_000_000:raise ValueError('Markdown
file exceeds 1 MB; narrow the scope')
\ selected.append(str(path.relative_to(root)))
if not selected:raise ValueError('No Markdown files matched; an
empty scan is not success')
if len(selected)>50:raise ValueError('More than 50 files matched;
narrow the scope')
Path('repository/markdown-files.txt').write_text('\\n'.join(selecte\
d)+'\\n')
print('Selected',len(selected),'Markdown files')\n"
- id: report
type: io.kestra.plugin.scripts.shell.Commands
taskRunner:
type: io.kestra.plugin.core.runner.Process
inputFiles:
summarize.py: "import json
from pathlib import Path
raw = json.loads(Path('lychee.json').read_text())
confirmed, uncertain = [], []
for source, entries in raw.get('error_map', {}).items():
\ for entry in entries:
\ status = entry.get('status', {})
\ code = status.get('code')
\ text = status.get('text', '')
\ item = {'source': source, 'url': entry['url'], 'status':
text, 'line': entry.get('span', {}).get('line')}
\ # Only explicit absence is actionable. Auth, throttling and
server/network
\ # errors need a later check, not a declaration that the
link is dead.
\ if code in (404, 410) or (entry['url'].startswith('file:')
and 'File not found' in text):
\ confirmed.append(item)
\ else:
\ uncertain.append(item)
for source, entries in raw.get('timeout_map', {}).items():
\ for entry in entries:
\ uncertain.append({'source': source, 'url': entry['url'],
'status': 'timeout', 'line': entry.get('span', {}).get('line')})
report = {'checked': raw.get('total', 0), 'successful':
raw.get('successful', 0), 'excluded': raw.get('excludes', 0),
'needs_fix': confirmed, 'needs_recheck': uncertain}
confirmed.sort(key=lambda x:(x['source'],x['line'] or 0,x['url']))
uncertain.sort(key=lambda x:(x['source'],x['line'] or 0,x['url']))
Path('link-audit.json').write_text(json.dumps(report, indent=2))
lines = ['# Markdown link audit', '', f\"Checked:
{report['checked']}; successful: {report['successful']}; excluded:
{report['excluded']}\", '', '## Links to inspect (HTTP 404/410 or
missing local files)' ]
for title, items in [('Links to inspect', confirmed), ('Needs a
recheck (not labelled broken)', uncertain)]:
\ if title != 'Links to inspect': lines += ['', '## ' + title]
\ lines.extend(f\"- {x['source']}:{x['line']}: {x['url']}
({x['status']})\" for x in items)
\ if not items: lines.append('- None')
Path('link-audit.md').write_text('\\n'.join(lines) + '\\n')
print('::' + json.dumps({'outputs': {'missing_count':
len(confirmed), 'recheck_count': len(uncertain), 'checked_count':
report['checked']}}) + '::')\n"
lychee.json: '{{ outputs.scan.outputFiles[''lychee.json''] }}'
commands:
- python3 summarize.py
outputFiles:
- link-audit.json
- link-audit.md
- id: missing_links
type: io.kestra.plugin.core.flow.If
condition: '{{ outputs.report.vars.missing_count > 0 }}'
then:
- id: review_missing
type: io.kestra.plugin.core.log.Log
message: 'HTTP 404/410 responses: {{ outputs.report.vars.missing_count }}.
Inspect the report before changing links; servers can mask access
errors as 404. No issues or notifications were posted.'
else:
- id: review_uncertain
type: io.kestra.plugin.core.log.Log
message: 'No confirmed missing links. Results needing a recheck: {{
outputs.report.vars.recheck_count }}. Excluded links are not proof of
success.'
outputs:
- id: report_json
type: FILE
required: false
value: '{{ outputs.report.outputFiles[''link-audit.json''] ?? null }}'
- id: report_markdown
type: FILE
required: false
value: '{{ outputs.report.outputFiles[''link-audit.md''] ?? null }}'
- id: missing_count
type: INT
required: false
value: '{{ outputs.report.vars.missing_count ?? 0 }}'
- id: recheck_count
type: INT
required: false
value: '{{ outputs.report.vars.recheck_count ?? 0 }}'