Skip to content

Commit

Permalink
Linter: New Rule (DPW005) for Code Samples
Browse files Browse the repository at this point in the history
  • Loading branch information
vincent-cai committed Sep 5, 2023
1 parent 4df9ec8 commit 379a278
Show file tree
Hide file tree
Showing 3 changed files with 61 additions and 0 deletions.
1 change: 1 addition & 0 deletions .markdownlint-cli2.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,6 @@ module.exports = {
'./.markdownlint/customRules/rules/md-images',
'./.markdownlint/customRules/rules/html-links',
'./.markdownlint/customRules/rules/md-links',
'./.markdownlint/customRules/rules/code-samples',
]
};
59 changes: 59 additions & 0 deletions .markdownlint/customRules/rules/code-samples.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
/**
* @fileOverview Custom rule for code sample validation.
*
* This rule expects MD files in the `docs` dir, and code samples files
* present as sibling directory of `docs` dir. The struct is is:
* -- project
* -- docs
* -- code-samples
* -- mdx_includes
*
* The pattern is `/{!>\s*(.+?)\s*(\[.+])?\s*!}/g` which matches:
* - {!>code-samples/messaging/code-snippets/send-a2p-sms.rb!}
* - {!> code-samples/messaging/code-snippets/send-a2p-sms.rb !}
* - {!> code-samples/messaging/code-snippets/send-a2p-sms.py !}
* - {!> code-samples/messaging/code-snippets/send-a2p-sms.php [ln:2-]!}
* - {!> mdx_includes/rcv-sdk-quick-start-js.md !}
*/
const { pathToFileURL } = require("url");
const fs = require("fs");
const path = require("path");
const { addError } = require("../helpers");

module.exports = {
names: ["DPW005"],
description: "Code samples validation",
tags: ["custom"],
function: function rule(params, onError) {
const pattern = /{!>\s*(.+?)\s*(\[.+])?\s*!}/g;
const rootPath = params.name.split("/docs/")[0];

params.tokens
.filter((token) => {
return (
token.type === "inline" ||
token.type === "fence" ||
token.type === "code_block"
);
})
.forEach((token) => {
let match;

while ((match = pattern.exec(token.content)) !== null) {
const fileName = match[1];

if (!fileName) {
addError(onError, token.lineNumber, `Code sample is empty`);
} else {
const filePath = path.join(rootPath, fileName);
const fileUrl = pathToFileURL(filePath);

if (!fs.existsSync(fileUrl)) {
const detail = `Not Exist: "${fileName}"`;
addError(onError, token.lineNumber, detail);
}
}
}
});
},
};
1 change: 1 addition & 0 deletions .markdownlint/rules/ci.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -14,4 +14,5 @@ module.exports = {
"DPW002": true,
"DPW003": true,
"DPW004": true,
"DPW005": true,
};

0 comments on commit 379a278

Please sign in to comment.