Skip to content

Commit

Permalink
feat: github action for validating redirects
Browse files Browse the repository at this point in the history
  • Loading branch information
stdavis committed Mar 19, 2024
1 parent 0923efe commit 22c8bc3
Show file tree
Hide file tree
Showing 2 changed files with 91 additions and 0 deletions.
41 changes: 41 additions & 0 deletions .github/workflows/push_redirects.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
name: Push to Redirects

on:
push:
paths:
- 'public/_redirects'

concurrency:
group: ${{ github.workflow }}-${{ github.head_ref || github.ref }}
cancel-in-progress: true

jobs:
validate:
name: Validate redirects
runs-on: ubuntu-latest
defaults:
run:

steps:
- name: ⬇️ Set up code
uses: actions/checkout@v4
with:
show-progress: false

- name: ⎔ Setup Node.js
uses: actions/setup-node@v4
with:
node-version: lts/*
cache: npm

- name: 🏗️ Build Site
working-directory: ./
run: |
npm install
npm run build
- name: ✔ Validate redirects
working-directory: ./src/migrations
run: |
npm install
node validate-redirects.mjs
50 changes: 50 additions & 0 deletions src/migrations/validate-redirects.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import { globSync } from 'glob';
import { open } from 'node:fs/promises';
import { join } from 'node:path';
import { validateProductPageUrl } from './utilities.mjs';

const redirectPath = join('..', '..', 'public', '_redirects');
let file = await open(redirectPath, 'r');

// get urls from built files
const fileUrls = globSync('../../dist/**/*.html', { ignore: '../../dist/404.html' }).map((path) =>
path
.replace('../../dist', '')
.replace(/index\.html$/, '')
.replace(/\/$/, ''),
);

const errors = [];
let isFirstLine = true;
for await (const line of file.readLines()) {
if (isFirstLine) {
isFirstLine = false;
continue; // Skip the first line
}

let [source, destination] = line.split(' ').filter((l) => l);

if (destination.startsWith('/')) {
destination = destination.replace(/\/$/, '');
if (!fileUrls.includes(destination)) {
const message = `destination: "${destination}" not found`;
console.error(message);
errors.push(message);
}
} else {
const response = await validateProductPageUrl(destination);
if (!response.valid) {
const message = `destination: ${destination} failed validation with message: ${response.message}`;
console.error(message);
errors.push(message);
}
}
}

file.close();

if (errors.length > 0) {
process.exit(1);
}

process.exit(0);

0 comments on commit 22c8bc3

Please sign in to comment.