Skip to content

Commit

Permalink
Merge pull request #632 from shawnthompson/list-pages
Browse files Browse the repository at this point in the history
List changed pages to review
  • Loading branch information
shawnthompson authored Sep 10, 2024
2 parents 5c5dbb7 + 844e593 commit 5a68610
Show file tree
Hide file tree
Showing 4 changed files with 163 additions and 3 deletions.
115 changes: 115 additions & 0 deletions .eleventy.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,19 @@
const fs = require('fs');
const path = require('path');
const { execSync } = require('child_process');
const nunjucks = require('nunjucks'); // Import Nunjucks for rendering
const markdownIt = require('markdown-it');
const markdownItAnchor = require('markdown-it-anchor');
const markdownItAttrs = require('markdown-it-attrs');
const { EleventyHtmlBasePlugin } = require('@11ty/eleventy');
const { stripHtml } = require('string-strip-html');
const beautify = require('js-beautify').html;
const { DateTime } = require('luxon');
const changedPageUrls = [];

// ANSI escape codes for blue underline
const underline = '\x1b[4m'; // Underline font
const resetColor = '\x1b[0m'; // Reset font to default

module.exports = function (eleventyConfig) {
const eleventySlugify = eleventyConfig.getFilter('slug');
Expand Down Expand Up @@ -128,11 +137,117 @@ module.exports = function (eleventyConfig) {
});
});

// Custom collection for changed pages
eleventyConfig.addCollection('changedPages', function (collectionApi) {
const changedPages = [];
collectionApi.getAll().forEach(item => {
const normalizedInputPath = path.relative('./', item.inputPath);
if (changedFilePaths.has(normalizedInputPath)) {
// Store both the URL, title, and locale for each changed page
changedPages.push({
url: item.url,
title: item.data.title || item.fileSlug, // fallback to fileSlug if no title
locale: item.data.locale || 'en' // default to 'en' if no locale is set
});
}
});
return changedPages; // Returning the changed URLs, titles, and locales for the template
});

// Add custom Markdown filter for Nunjucks
eleventyConfig.addNunjucksFilter("markdown", function (value) {
return md.render(value);
});

let changedFilesMap = new Map();
let changedFilePaths = new Set();
let gitChangedUrls = [];
let domain = 'http://localhost';
let port = '8080'; // Default port

// Detect GitHub Codespaces
if (process.env.CODESPACES && process.env.CODESPACE_NAME) {
// Use the correct format for Codespaces URLs with the .app domain
domain = `https://${process.env.CODESPACE_NAME}-${port}.app.github.dev`;
}

// Detect Netlify Deploy Preview
if (process.env.DEPLOY_URL) {
domain = process.env.DEPLOY_URL;
}

// Read the .eleventy-port file to get the correct port for local development
if (fs.existsSync('.eleventy-port')) {
port = fs.readFileSync('.eleventy-port', 'utf8').trim();
if (domain === 'http://localhost') {
domain = `${domain}:${port}`; // Apply the port for localhost
}
}

// Capture changed files before the build starts (Method 1: Eleventy watch)
eleventyConfig.on('beforeWatch', (changedFiles) => {
changedFiles.forEach(file => {
console.log(`Changed source file: ${file}`);
changedFilesMap.set(file, null); // Track the file
});
});

// Capture both committed and uncommitted changes using Git (Method 2: Git diff)
eleventyConfig.on('beforeBuild', () => {
// Fetch the `main` branch from the upstream repository directly
const upstreamUrl = 'https://github.com/gc-da11yn/gc-da11yn.github.io';

try {
execSync(`git fetch ${upstreamUrl} main:upstream-main --depth=1`);
} catch (err) {
console.error('Error fetching the upstream main branch', err);
}

// Get the diff between the current branch and `upstream-main`
const gitChangedFiles = execSync('git diff upstream-main --name-only').toString().trim().split('\n');

gitChangedFiles.forEach((file) => {
// Check if the file is contained within the 'src/main' or 'src/pages' directories
// and is an .md or .njk file
if ((file.startsWith('src/main/') || file.startsWith('src/pages/')) && (file.endsWith('.md') || file.endsWith('.njk'))) {
// Track the file
changedFilePaths.add(file);
}
});
});

// Hook into the HTML generation process (logging to the console)
eleventyConfig.addTransform("captureGeneratedUrl", function (content, outputPath) {
if (outputPath && outputPath.endsWith('.html')) {
const inputPath = path.relative('./', this.page.inputPath);

// Check if this file was changed based on Git diff
if (changedFilePaths.has(inputPath)) {
const fullUrl = `${domain}:${port}${this.page.url}`;

// Log the URL in blue and underlined
console.log(`${underline}Captured URL: ${fullUrl}${resetColor}`);

gitChangedUrls.push(fullUrl); // Store the URL to log later
}
}
return content;
});

eleventyConfig.on('afterBuild', () => {
const changedFilesCount = changedFilePaths.size;

if (changedFilesCount > 0) {
// Log summary and provide the correct link based on the environment
console.log(`\n${changedFilesCount} page(s) changed.`);
console.log(`Review the changed pages here: ${underline}${domain}/en/pages-to-review/${resetColor}\n`);
} else {
console.log('No pages to review.\n');
}

changedFilePaths.clear(); // Clear the set for the next watch cycle
});

return {
dir: {
input: "src",
Expand Down
6 changes: 3 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,9 @@
"sass-start": "sass src/_scss/base.scss _site/css/da11yn.css",
"sass-build": "sass --style=compressed src/_scss/base.scss _site/css/da11yn.css",
"watch:sass": "npm run sass-start -- --watch",
"start": "cross-env ELEVENTY_ENV=local npm-run-all sass-start serve:port --parallel watch:*",
"start-dev": "cross-env ELEVENTY_ENV=dev npm-run-all sass-start serve:port --parallel watch:*",
"start-prod": "cross-env ELEVENTY_ENV=prod npm-run-all sass-start serve:port --parallel watch:*",
"start": "cross-env ELEVENTY_WATCH=true ELEVENTY_ENV=local npm-run-all sass-start serve:port --parallel watch:*",
"start-dev": "cross-env ELEVENTY_WATCH=true ELEVENTY_ENV=dev npm-run-all sass-start serve:port --parallel watch:*",
"start-prod": "cross-env ELEVENTY_WATCH=true ELEVENTY_ENV=prod npm-run-all sass-start serve:port --parallel watch:*",
"dev": "cross-env ELEVENTY_ENV=dev npm-run-all sass-build --parallel eleventy",
"debug": "DEBUG=Eleventy* npx @11ty/eleventy",
"build": "npm-run-all sass-build eleventy"
Expand Down
22 changes: 22 additions & 0 deletions src/main/en/pages-to-review.njk
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
---
title: Pages to review
toggle: pages-a-reviser
description: On this page, you’ll find a list of pages that have been modified and require review. These changes reflect the differences between the current branch and the main branch.
---

{%- if collections.changedPages.length > 0 -%}
<p>These are changed pages that need to be reviewed:</p>
<ul>
{% for page in collections.changedPages %}
{% if page.locale != locale %}
<li><a href="{{ page.url }}" lang="{{ page.locale }}">{{ page.title }}</a></li>
{% else %}
<li><a href="{{ page.url }}">{{ page.title }}</a></li>
{% endif %}
{% endfor %}
</ul>
{%- else -%}
<p>There are no pages that have changes.</p>
{%- endif -%}

<p>If you see links to pages you haven't changed, it may be because there were changes on the <code>upstream / main</code> branch. To update your current branch to the latest, use <a href="https://www.atlassian.com/git/tutorials/rewriting-history/git-rebase"><code>git rebase</code></a>.</p>
23 changes: 23 additions & 0 deletions src/main/fr/pages-a-reviser.njk
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
---
title: Pages à réviser
toggle: pages-to-review
description: Sur cette page, vous trouverez une liste des pages qui ont été modifiées et qui nécessitent une révision. Ces modifications reflètent les différences entre la branche actuelle et la branche principale.
---

{%- if collections.changedPages.length > 0 -%}
<p>Il s'agit de pages modifiées qui doivent être révisées :</p>
<ul>
{% for page in collections.changedPages %}
{% if page.locale != locale %}
<li><a href="{{ page.url }}" lang="{{ page.locale }}">{{ page.title }}</a></li>
{% else %}
<li><a href="{{ page.url }}">{{ page.title }}</a></li>
{% endif %}
{% endfor %}

</ul>
{%- else -%}
<p>Aucune page n'a été modifiée.</p>
{%- endif -%}

<p>Si vous voyez des liens vers des pages que vous n'avez pas modifiées, c'est peut-être parce qu'il y a eu des changements sur la branche <code>upstream / main</code>. Pour mettre à jour votre branche actuelle avec les dernières modifications, utilisez <a href="https://www.atlassian.com/fr/git/tutorials/rewriting-history/git-rebase"><code>git rebase</code></a>.</p>

0 comments on commit 5a68610

Please sign in to comment.