Skip to content

Commit 9aac78c

Browse files
authored
Custom extension mapping (#14)
* Make code type mapping from extensions customizable * Update build artifacts * 0.5.0 * Remove pnpm-lock. We use npm in this package.
1 parent 91b1e54 commit 9aac78c

32 files changed

+233
-78
lines changed

lib/cjs/actions/check.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ const consts_1 = require("./consts");
2222
* Compare the digest of the best practices against the stored digest to
2323
* see if the docs need to be updated.
2424
*/
25-
const checkAction = ({ srcPath, generatedPath }) => __awaiter(void 0, void 0, void 0, function* () {
25+
const checkAction = (_a) => __awaiter(void 0, [_a], void 0, function* ({ srcPath, generatedPath }) {
2626
const bestPractices = yield (0, parse_1.getAllBestPractices)(srcPath);
2727
const currentDigest = (0, digest_1.getBestPracticesDigest)(bestPractices);
2828
const previousDigest = yield getPreviousBestPracticesDigest(generatedPath);

lib/cjs/actions/write.js

Lines changed: 18 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -12,9 +12,12 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
1212
return (mod && mod.__esModule) ? mod : { "default": mod };
1313
};
1414
Object.defineProperty(exports, "__esModule", { value: true });
15-
exports.getBestPracticeFileLines = exports.SPECIAL_META_KEYS = exports.writeBestPractices = void 0;
15+
exports.SPECIAL_META_KEYS = exports.writeBestPractices = void 0;
16+
exports.default = writeAction;
17+
exports.getBestPracticeFileLines = getBestPracticeFileLines;
1618
const promises_1 = require("fs/promises");
1719
const path_1 = __importDefault(require("path"));
20+
const codeType_1 = require("../utils/codeType");
1821
const digest_1 = require("../utils/digest");
1922
const fs_1 = require("../utils/fs");
2023
const parse_1 = require("../utils/parse");
@@ -24,31 +27,31 @@ const consts_1 = require("./consts");
2427
/**
2528
* Generate best practices from source and write them out.
2629
*/
27-
function writeAction({ srcPath, docsPath, generatedPath, codeUrl, options, }) {
28-
return __awaiter(this, void 0, void 0, function* () {
30+
function writeAction(_a) {
31+
return __awaiter(this, arguments, void 0, function* ({ srcPath, docsPath, generatedPath, codeUrl, extensionMappings, options, }) {
32+
const codeTypeMap = (0, codeType_1.buildCodeTypeMap)(extensionMappings !== null && extensionMappings !== void 0 ? extensionMappings : []);
2933
const allBestPractices = yield (0, parse_1.getAllBestPractices)(srcPath);
3034
let filteredBestPractices;
3135
if (docsPath) {
3236
// It's OK if the generatedPath is within docsPath, because we'll completely replace
3337
// the generated path next. This is a feature not a bug.
34-
const usedIds = yield (0, replace_1.replaceAllBestPracticesInDocs)(docsPath, allBestPractices, (bestPractice) => getBestPracticeCodeLines(bestPractice, codeUrl));
38+
const usedIds = yield (0, replace_1.replaceAllBestPracticesInDocs)(docsPath, allBestPractices, (bestPractice) => getBestPracticeCodeLines(bestPractice, codeUrl, codeTypeMap));
3539
// If a best practice was written out to a static file, do not also include it in the
3640
// generated output
3741
filteredBestPractices = allBestPractices.filter((bp) => !usedIds.has(bp.getMeta('id')));
3842
}
3943
else {
4044
filteredBestPractices = allBestPractices;
4145
}
42-
yield (0, exports.writeBestPractices)(generatedPath, filteredBestPractices, codeUrl, options);
46+
yield (0, exports.writeBestPractices)(generatedPath, filteredBestPractices, codeUrl, codeTypeMap, options);
4347
yield writeBestPracticesDigest(generatedPath, (0, digest_1.getBestPracticesDigest)(allBestPractices));
4448
return filteredBestPractices;
4549
});
4650
}
47-
exports.default = writeAction;
4851
/**
4952
* Writes best practices out to Markdown doc files.
5053
*/
51-
const writeBestPractices = (contentDir, bestPractices, codeUrl, options) => __awaiter(void 0, void 0, void 0, function* () {
54+
const writeBestPractices = (contentDir, bestPractices, codeUrl, codeTypeMap, options) => __awaiter(void 0, void 0, void 0, function* () {
5255
try {
5356
yield (0, promises_1.rm)(contentDir, { recursive: true });
5457
}
@@ -57,15 +60,15 @@ const writeBestPractices = (contentDir, bestPractices, codeUrl, options) => __aw
5760
}
5861
yield (0, promises_1.mkdir)(contentDir);
5962
for (const bestPractice of bestPractices) {
60-
yield writeBestPracticeToFile(contentDir, bestPractice, codeUrl, options);
63+
yield writeBestPracticeToFile(contentDir, bestPractice, codeUrl, codeTypeMap, options);
6164
}
6265
});
6366
exports.writeBestPractices = writeBestPractices;
6467
exports.SPECIAL_META_KEYS = new Set(['title', 'subtitle', 'description']);
6568
/**
6669
* Write a best practice to a markdown file.
6770
*/
68-
const writeBestPracticeToFile = (dir, bestPractice, codeUrl, options) => __awaiter(void 0, void 0, void 0, function* () {
71+
const writeBestPracticeToFile = (dir, bestPractice, codeUrl, codeTypeMap, options) => __awaiter(void 0, void 0, void 0, function* () {
6972
const { filepath, filename } = bestPractice.getFileInfo();
7073
const dirpath = path_1.default.join(dir, ...filepath);
7174
const fullpath = path_1.default.join(dirpath, filename);
@@ -78,7 +81,7 @@ const writeBestPracticeToFile = (dir, bestPractice, codeUrl, options) => __await
7881
yield (0, promises_1.mkdir)(dirpath, { recursive: true });
7982
}
8083
fd = yield (0, promises_1.open)(fullpath, 'a');
81-
for (const line of getBestPracticeFileLines(bestPractice, codeUrl, Object.assign({ writeTitle }, options))) {
84+
for (const line of getBestPracticeFileLines(bestPractice, codeUrl, codeTypeMap, Object.assign({ writeTitle }, options))) {
8285
yield (0, fs_1.writeLine)(fd, line);
8386
}
8487
}
@@ -89,7 +92,7 @@ const writeBestPracticeToFile = (dir, bestPractice, codeUrl, options) => __await
8992
/**
9093
* Generate best practice lines.
9194
*/
92-
function* getBestPracticeFileLines(bestPractice, codeUrl, { writeTitle = true, writeExtraMeta = false }) {
95+
function* getBestPracticeFileLines(bestPractice, codeUrl, codeTypeMap, { writeTitle = true, writeExtraMeta = false }) {
9396
if (writeTitle) {
9497
yield '---';
9598
yield `title: ${bestPractice.getTitle()}`;
@@ -118,16 +121,16 @@ function* getBestPracticeFileLines(bestPractice, codeUrl, { writeTitle = true, w
118121
}
119122
yield '';
120123
}
121-
for (const line of getBestPracticeCodeLines(bestPractice, codeUrl)) {
124+
for (const line of getBestPracticeCodeLines(bestPractice, codeUrl, codeTypeMap)) {
122125
yield line;
123126
}
124127
}
125-
exports.getBestPracticeFileLines = getBestPracticeFileLines;
126-
const getBestPracticeCodeLines = (bestPractice, codeUrl) => {
128+
const getBestPracticeCodeLines = (bestPractice, codeUrl, codeTypeMap) => {
127129
const { sourceFilename, startLine, endLine } = bestPractice;
128130
const url = `${codeUrl}/${sourceFilename}#L${startLine}-L${endLine}`;
131+
const codeType = codeTypeMap(bestPractice.getFileType());
129132
return [
130-
`\`\`\`${bestPractice.getFileType()}`,
133+
`\`\`\`${codeType}`,
131134
...(0, string_1.unindent)(bestPractice.codeLines),
132135
'```',
133136
`From [${sourceFilename} lines ${startLine}-${endLine}](${url})`,

lib/cjs/best-practices.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ const main = () => {
2121
.option('-d, --docs-path <docsPath>')
2222
.requiredOption('-g, --generated-path <generatedPath>')
2323
.requiredOption('-u, --code-url <codeUrl>')
24+
.option('-m, --extension-mappings <mappings...>', 'e.g. jsx:js to map jsx to js')
2425
.action((args) => {
2526
(0, write_1.default)(Object.assign(Object.assign({}, args), { options: {} }));
2627
});

lib/cjs/index.js

Lines changed: 17 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -15,13 +15,23 @@ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (
1515
}) : function(o, v) {
1616
o["default"] = v;
1717
});
18-
var __importStar = (this && this.__importStar) || function (mod) {
19-
if (mod && mod.__esModule) return mod;
20-
var result = {};
21-
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22-
__setModuleDefault(result, mod);
23-
return result;
24-
};
18+
var __importStar = (this && this.__importStar) || (function () {
19+
var ownKeys = function(o) {
20+
ownKeys = Object.getOwnPropertyNames || function (o) {
21+
var ar = [];
22+
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23+
return ar;
24+
};
25+
return ownKeys(o);
26+
};
27+
return function (mod) {
28+
if (mod && mod.__esModule) return mod;
29+
var result = {};
30+
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31+
__setModuleDefault(result, mod);
32+
return result;
33+
};
34+
})();
2535
var __importDefault = (this && this.__importDefault) || function (mod) {
2636
return (mod && mod.__esModule) ? mod : { "default": mod };
2737
};

lib/cjs/types/actions/write.d.ts

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import BestPractice from '../BestPractice';
2+
import { type CodeTypeMapper } from '../utils/codeType';
23
type WriteOptions = {
34
writeExtraMeta?: boolean;
45
};
@@ -7,16 +8,17 @@ type WriteArgs = {
78
docsPath?: string;
89
generatedPath: string;
910
codeUrl: string;
11+
extensionMappings?: string[];
1012
options: WriteOptions;
1113
};
1214
/**
1315
* Generate best practices from source and write them out.
1416
*/
15-
export default function writeAction({ srcPath, docsPath, generatedPath, codeUrl, options, }: WriteArgs): Promise<BestPractice[]>;
17+
export default function writeAction({ srcPath, docsPath, generatedPath, codeUrl, extensionMappings, options, }: WriteArgs): Promise<BestPractice[]>;
1618
/**
1719
* Writes best practices out to Markdown doc files.
1820
*/
19-
export declare const writeBestPractices: (contentDir: string, bestPractices: BestPractice[], codeUrl: string, options: WriteOptions) => Promise<void>;
21+
export declare const writeBestPractices: (contentDir: string, bestPractices: BestPractice[], codeUrl: string, codeTypeMap: CodeTypeMapper, options: WriteOptions) => Promise<void>;
2022
export declare const SPECIAL_META_KEYS: Set<string>;
2123
type WriteBestPracticeOptions = {
2224
writeTitle?: boolean;
@@ -25,6 +27,6 @@ type WriteBestPracticeOptions = {
2527
/**
2628
* Generate best practice lines.
2729
*/
28-
export declare function getBestPracticeFileLines(bestPractice: BestPractice, codeUrl: string, { writeTitle, writeExtraMeta }: WriteBestPracticeOptions): Generator<string>;
30+
export declare function getBestPracticeFileLines(bestPractice: BestPractice, codeUrl: string, codeTypeMap: CodeTypeMapper, { writeTitle, writeExtraMeta }: WriteBestPracticeOptions): Generator<string>;
2931
export {};
3032
//# sourceMappingURL=write.d.ts.map

lib/cjs/types/actions/write.d.ts.map

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

lib/cjs/types/utils/codeType.d.ts

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
export type CodeTypeMapper = (ext: string) => string;
2+
/**
3+
* Convert a list of mappings to a function to map file extension to code type.
4+
*
5+
* E.g. if you want files with a .tsx extension to have a ts code type for examples you could
6+
*
7+
* buildCodeTypeMap(['tsx:ts', 'jsx:js'])
8+
*/
9+
export declare const buildCodeTypeMap: (mappings?: string[]) => CodeTypeMapper;
10+
//# sourceMappingURL=codeType.d.ts.map

lib/cjs/types/utils/codeType.d.ts.map

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

lib/cjs/types/utils/fs.d.ts

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
/// <reference types="node" />
21
import { type FileHandle } from 'fs/promises';
32
/**
43
* Asynchronously walks through a directory structure and yields filenames.

lib/cjs/types/utils/fs.d.ts.map

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

lib/cjs/types/utils/replace.d.ts.map

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

lib/cjs/utils/codeType.js

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
"use strict";
2+
Object.defineProperty(exports, "__esModule", { value: true });
3+
exports.buildCodeTypeMap = void 0;
4+
/**
5+
* Convert a list of mappings to a function to map file extension to code type.
6+
*
7+
* E.g. if you want files with a .tsx extension to have a ts code type for examples you could
8+
*
9+
* buildCodeTypeMap(['tsx:ts', 'jsx:js'])
10+
*/
11+
const buildCodeTypeMap = (mappings = []) => {
12+
const map = Object.fromEntries(mappings.map((value) => value.split(':')));
13+
return (ext) => map[ext] || ext;
14+
};
15+
exports.buildCodeTypeMap = buildCodeTypeMap;

lib/cjs/utils/fs.js

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ var __asyncDelegator = (this && this.__asyncDelegator) || function (o) {
2424
var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {
2525
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
2626
var g = generator.apply(thisArg, _arguments || []), i, q = [];
27-
return i = {}, verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i;
27+
return i = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i;
2828
function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; }
2929
function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } }
3030
function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
@@ -34,7 +34,8 @@ var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _ar
3434
function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
3535
};
3636
Object.defineProperty(exports, "__esModule", { value: true });
37-
exports.isDocFile = exports.isCodeFile = exports.writeFileLines = exports.readFileLines = exports.pathExists = exports.writeLine = exports.walk = void 0;
37+
exports.isDocFile = exports.isCodeFile = exports.writeFileLines = exports.readFileLines = exports.pathExists = exports.writeLine = void 0;
38+
exports.walk = walk;
3839
const fs_1 = require("fs");
3940
const promises_1 = require("fs/promises");
4041
const promises_2 = require("fs/promises");
@@ -43,8 +44,8 @@ const path_1 = require("path");
4344
* Asynchronously walks through a directory structure and yields filenames.
4445
* Uses a depth-first search pattern.
4546
*/
46-
function walk(dir, context = '') {
47-
return __asyncGenerator(this, arguments, function* walk_1() {
47+
function walk(dir_1) {
48+
return __asyncGenerator(this, arguments, function* walk_1(dir, context = '') {
4849
const entries = yield __await((0, promises_2.readdir)(dir, { withFileTypes: true }));
4950
for (const entry of entries) {
5051
if (entry.isDirectory()) {
@@ -57,7 +58,6 @@ function walk(dir, context = '') {
5758
}
5859
});
5960
}
60-
exports.walk = walk;
6161
/**
6262
* Writes text to a file descriptor, adding a trailing newline.
6363
*/

0 commit comments

Comments
 (0)