Skip to content

Commit

Permalink
feat(husky): force to update moved file links (mdn#31269)
Browse files Browse the repository at this point in the history
  • Loading branch information
OnkarRuikar authored and dipikabh committed Jan 17, 2024
1 parent abdba3f commit 6a314b1
Show file tree
Hide file tree
Showing 4 changed files with 49 additions and 41 deletions.
5 changes: 2 additions & 3 deletions .github/workflows/auto-cleanup-bot.yml
Original file line number Diff line number Diff line change
Expand Up @@ -31,13 +31,12 @@ jobs:
yarn content fix-flaws
yarn fix:md
yarn fix:fm
node scripts/update-moved-file-links.js
- name: Create PR with only fixable issues
if: success()
uses: peter-evans/create-pull-request@v5
with:
commit-message: "chore: auto-fix Markdownlint, Prettier, front-matter, redirects issues"
commit-message: "chore: auto-fix Markdownlint, Prettier, and front-matter issues"
branch: markdownlint-auto-cleanup
title: "fix: auto-cleanup by bot"
author: mdn-bot <[email protected]>
Expand All @@ -49,7 +48,7 @@ jobs:
if: failure()
uses: peter-evans/create-pull-request@v5
with:
commit-message: "chore: auto-fix Markdownlint issues"
commit-message: "chore: auto-fix Markdownlint, Prettier, and front-matter issues"
branch: markdownlint-auto-cleanup
title: "fix: auto-cleanup by bot"
author: mdn-bot <[email protected]>
Expand Down
1 change: 1 addition & 0 deletions .lintstagedrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
"*.md": [
"markdownlint-cli2 --fix",
"node scripts/front-matter_linter.js --fix true",
"node scripts/update-moved-file-links.js --check",
"prettier --write"
],
"tests/**/*.*": "yarn test:front-matter-linter",
Expand Down
81 changes: 44 additions & 37 deletions scripts/update-moved-file-links.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,18 @@
import fs from "node:fs/promises";
import path from "node:path";
import { execGit, getRootDir, walkSync, isImagePath } from "./utils.js";
import {
execGit,
getRootDir,
walkSync,
isImagePath,
IMG_RX,
SLUG_RX,
} from "./utils.js";

const SLUG_RX = /(?<=\nslug: ).*?$/gm;
const HELP_MSG =
"Usage:\n\t" +
"node scripts/update-moved-file-links.js\n\t" +
"node scripts/update-moved-file-links.js [movedFromPath] [movedToPath]\n";
"node scripts/update-moved-file-links.js --check\n";

/**
* Try to get slug for an image from file path
Expand All @@ -26,43 +32,37 @@ export async function getImageSlug(imagePath, root) {
}
}

let movedFiles = [];
const rootDir = getRootDir();
const argLength = process.argv.length;
let movedFiles = [];
let isCheckOnly = false;

if (process.argv[2] === "--help" || process.argv[2] === "-h") {
console.error(HELP_MSG);
process.exit(0);
} else if (argLength === 2 && argLength > 3) {
console.error(HELP_MSG);
process.exit(1);
} else if (argLength === 3) {
movedFiles.push({ from: process.argv[2], to: process.argv[3] });
} else {
// git log --name-status --pretty=format:"" --since "1 day ago" --diff-filter=R
let result = execGit(
[
"log",
"--name-status",
"--pretty=format:",
'--since="1 day ago"',
"--diff-filter=R",
],
{ cwd: "." },
);
} else if (process.argv[2] === "--check") {
isCheckOnly = true;
}

if (result.trim()) {
movedFiles.push(
...result
.split("\n")
.filter((line) => line.trim() !== "" && line.includes("files/en-us"))
.map((line) => line.replaceAll(/files\/en-us\/|\/index.md/gm, ""))
.map((line) => line.split(/\s/))
.map((tuple) => {
return { from: tuple[1], to: tuple[2] };
}),
);
}
// get staged and unstaged changes
const result = execGit(["status", "--short", "--porcelain"], { cwd: "." });
if (result.trim()) {
movedFiles.push(
...result
.split("\n")
.filter(
(line) =>
/^\s*RM?\s+/gi.test(line) &&
line.includes("files/en-us") &&
(IMG_RX.test(line) || line.includes("index.md")),
)
.map((line) =>
line.replaceAll(/^\s*RM?\s+|files\/en-us\/|\/index.md/gm, ""),
)
.map((line) => line.split(/ -> /))
.map((tuple) => {
return { from: tuple[0], to: tuple[1] };
}),
);
}

if (movedFiles.length < 1) {
Expand Down Expand Up @@ -99,7 +99,7 @@ movedFiles = (
)
).filter((e) => !!e);

console.log(`Number of moved files to consider: ${movedFiles.length}`);
console.log("Moved files:", movedFiles);

let totalNo = 0;
let updatedNo = 0;
Expand All @@ -108,7 +108,7 @@ for await (const filePath of walkSync(getRootDir())) {
try {
totalNo++;
const content = await fs.readFile(filePath, "utf-8");
let updated = new String(content);
let updated = String(content);
for (const moved of movedFiles) {
// [text](link)
updated = updated.replaceAll(`${moved.from})`, `${moved.to})`);
Expand All @@ -124,7 +124,14 @@ for await (const filePath of walkSync(getRootDir())) {
updated = updated.replaceAll(`${moved.from}'`, `${moved.to}'`);
}

if (content !== updated) {
if (content !== updated.valueOf()) {
if (isCheckOnly) {
console.error(
"File(s) have been moved. " +
"Run 'node scripts/update-moved-file-links.js' to update references.",
);
process.exit(1);
}
updatedNo++;
await fs.writeFile(filePath, updated);
}
Expand Down
3 changes: 2 additions & 1 deletion scripts/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@ import fs from "node:fs/promises";
import path from "node:path";
import childProcess from "node:child_process";

const IMG_RX = /(\.png|\.jpg|\.svg|\.gif)$/gim;
export const IMG_RX = /(\.png|\.jpg|\.svg|\.gif)$/gim;
export const SLUG_RX = /(?<=\nslug: ).*?$/gm;

export async function* walkSync(dir) {
const files = await fs.readdir(dir, { withFileTypes: true });
Expand Down

0 comments on commit 6a314b1

Please sign in to comment.