|
| 1 | +#!/usr/bin/env bash |
| 2 | +# |
| 3 | +# SPDX-License-Identifier: Apache-2.0 |
| 4 | +# |
| 5 | +# Copyright The original authors |
| 6 | +# |
| 7 | +# Licensed under the Apache Software License version 2.0, available at http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | + |
| 10 | +set -euo pipefail |
| 11 | + |
| 12 | +# Patches HTML files on the gh-pages branch for SEO: |
| 13 | +# |
| 14 | +# - Versioned doc directories ([0-9]*/, latest/): inject a <link rel="canonical"> |
| 15 | +# pointing to the equivalent page under /latest/, so Google indexes only the |
| 16 | +# current release. |
| 17 | +# - dev/: inject <meta name="robots" content="noindex, follow"> since dev docs |
| 18 | +# are unstable and should not appear in search results. |
| 19 | +# - Versioned API directories (api/[0-9]*/, api/latest/): inject a canonical |
| 20 | +# pointing to /api/latest/. |
| 21 | +# - api/dev/: inject noindex. |
| 22 | +# |
| 23 | +# Idempotent — files that already contain the relevant tag are skipped. |
| 24 | +# |
| 25 | +# Usage: patch-seo.sh <site-url> |
| 26 | +# Run from the root of a gh-pages checkout. |
| 27 | +# Example: patch-seo.sh https://hardwood-hq.github.io |
| 28 | + |
| 29 | +SITE_URL="${1:?Usage: patch-seo.sh <site-url>}" |
| 30 | +SITE_URL="${SITE_URL%/}" # strip trailing slash |
| 31 | + |
| 32 | +patched=0 |
| 33 | + |
| 34 | +inject_canonical() { |
| 35 | + local dir="$1" base_path="$2" |
| 36 | + |
| 37 | + while IFS= read -r file; do |
| 38 | + # Derive the relative path within the version directory |
| 39 | + rel_path="${file#"$dir"}" |
| 40 | + canonical="${SITE_URL}/${base_path}${rel_path}" |
| 41 | + sed -i "s|</head>|<link rel=\"canonical\" href=\"${canonical}\" />\n</head>|" "$file" |
| 42 | + patched=$((patched + 1)) |
| 43 | + done < <(grep -rL 'rel="canonical"' "$dir" --include="*.html" || true) |
| 44 | +} |
| 45 | + |
| 46 | +inject_noindex() { |
| 47 | + local dir="$1" |
| 48 | + |
| 49 | + while IFS= read -r file; do |
| 50 | + sed -i 's|</head>|<meta name="robots" content="noindex, follow">\n</head>|' "$file" |
| 51 | + patched=$((patched + 1)) |
| 52 | + done < <(grep -rL 'name="robots"' "$dir" --include="*.html" || true) |
| 53 | +} |
| 54 | + |
| 55 | +# Prose docs: canonical for versioned + latest, noindex for dev |
| 56 | +for dir in [0-9]*/ latest/; do |
| 57 | + [ -d "$dir" ] || continue |
| 58 | + inject_canonical "$dir" "latest/" |
| 59 | +done |
| 60 | + |
| 61 | +if [ -d "dev/" ]; then |
| 62 | + inject_noindex "dev/" |
| 63 | +fi |
| 64 | + |
| 65 | +# API docs: canonical for versioned + latest, noindex for dev |
| 66 | +for dir in api/[0-9]*/ api/latest/; do |
| 67 | + [ -d "$dir" ] || continue |
| 68 | + inject_canonical "$dir" "api/latest/" |
| 69 | +done |
| 70 | + |
| 71 | +if [ -d "api/dev/" ]; then |
| 72 | + inject_noindex "api/dev/" |
| 73 | +fi |
| 74 | + |
| 75 | +echo "patch-seo: patched $patched file(s)" |
0 commit comments