Skip to content

Commit

Permalink
Insert best practices into static documentation (#2)
Browse files Browse the repository at this point in the history
* Start on functionality to write best practices into static files

* Move sample generated docs

* Get static insertion working in sample

* Update README with new flag and behavior

* Rename best practice building package script

* Do not write "static used" best practices to the generated directory

* Add comments and better error message

* Build lib

* 0.4.0
  • Loading branch information
treycucco authored Sep 6, 2023
1 parent 68231ca commit ad874d7
Show file tree
Hide file tree
Showing 55 changed files with 752 additions and 160 deletions.
51 changes: 47 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -53,17 +53,17 @@ Check out the sample project that is part of the code to see more examples.

### Limitations

- We currently do not support multiline comments.
- We currently do not support multi-line comments.
- This tool only looks at files with `.js`, `.jsx`, `.ts`, and `.tsx` extensions

## Extracting Best Practices Documentation

To extract your best practices documentation, you can invoke our CLI tool:

npx best-practices write -s src/ -d docs/best-practices -u "https://github.com/<your org>/<your repo>/tree/main"
npx best-practices write -s src/ -g docs/best-practices -u "https://github.com/<your org>/<your repo>/tree/main"

This will scan through your code in `src` and build best practices Markdown
files from your tagged code. The contents of the `-d` directory will be
files from your tagged code. The contents of the `-g` directory will be
completely overwritten, so make sure you point to a directory that doesn't
contain any manually written documentation.

Expand All @@ -75,14 +75,57 @@ your generated documentation.
You can check to see if your generated docs are out of date with your code with
the `check` subcommand:

npx best-practices check -s src/ -d docs/best-practices
npx best-practices check -s src/ -g docs/best-practices

This will gather your best practices documentation from your code and generate a
digest, and compare those to the digest that was written out the last time docs
were generated. The `check` command will exit with a status code of `1` if the
docs are out of date, making this a good command to use in a pre-commit hook or
a CI step.

## Inserting Blocks Into Static Documentation

If you'd like to insert (and keep up-to-date) some best practices into static
documentation, meaning docs that you type out yourself, and aren't completely
controlled by this tool, you can do that with specially formatted comments and
meta tags.

### In Your Code

In your code, add a `id` meta field to the documentation block:

// @BestPractice.id insertIntoStaticDocs

This id should be unique throughout your codebase, but this is not checked or
enforced by the tool. If you have multiple best practice blocks with the same ID
then the last one picked up by the tool when parsing your code will be used.

### In Static Documentation

In your static markdown documentation file, add a comment like this where you'd
like to insert a best practice:

<!-- @BestPractice.insert insertIntoStaticDocs -->
<!-- @BestPractice.end -->

It's important to have both the start and end lines, as these will be used as
boundaries of the program to know where to replace the code.

### From the Command Line

In order to write out to static docs, you'll have to point the tool at your docs
root with the `-d` command line argument.

E.g.

`npx best-practices write -s src/ -g docs/best-practices -d docs/ ...`

### Used IDs

If a best practice is inserted into static documentation, it will not be
inserted into the generated docs. It will however still be included in the
digest for checking doc freshness.

## Keeping Docs Up-to-date

There are several strategies for keeping your docs up-to-date:
Expand Down
8 changes: 4 additions & 4 deletions lib/cjs/actions/check.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,10 +22,10 @@ const consts_1 = require("./consts");
* Compare the digest of the best practices against the stored digest to
* see if the docs need to be updated.
*/
const checkAction = ({ srcPath, destPath }) => __awaiter(void 0, void 0, void 0, function* () {
const checkAction = ({ srcPath, generatedPath }) => __awaiter(void 0, void 0, void 0, function* () {
const bestPractices = yield (0, parse_1.getAllBestPractices)(srcPath);
const currentDigest = (0, digest_1.getBestPracticesDigest)(bestPractices);
const previousDigest = yield getPreviousBestPracticesDigest(destPath);
const previousDigest = yield getPreviousBestPracticesDigest(generatedPath);
if (currentDigest === previousDigest) {
return;
}
Expand All @@ -35,8 +35,8 @@ const checkAction = ({ srcPath, destPath }) => __awaiter(void 0, void 0, void 0,
/**
* Get the stored digest for best practices.
*/
const getPreviousBestPracticesDigest = (destPath) => __awaiter(void 0, void 0, void 0, function* () {
const digestPath = path_1.default.join(destPath, consts_1.DIGEST_FILENAME);
const getPreviousBestPracticesDigest = (generatedPath) => __awaiter(void 0, void 0, void 0, function* () {
const digestPath = path_1.default.join(generatedPath, consts_1.DIGEST_FILENAME);
if (!(yield (0, fs_1.pathExists)(digestPath))) {
return '';
}
Expand Down
52 changes: 35 additions & 17 deletions lib/cjs/actions/write.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,23 +12,36 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.writeBestPractice = exports.SPECIAL_META_KEYS = exports.writeBestPractices = void 0;
exports.getBestPracticeFileLines = exports.SPECIAL_META_KEYS = exports.writeBestPractices = void 0;
const promises_1 = require("fs/promises");
const path_1 = __importDefault(require("path"));
const digest_1 = require("../utils/digest");
const fs_1 = require("../utils/fs");
const parse_1 = require("../utils/parse");
const replace_1 = require("../utils/replace");
const string_1 = require("../utils/string");
const consts_1 = require("./consts");
/**
* Generate best practices from source and write them out.
*/
function writeAction({ srcPath, destPath, codeUrl, options, }) {
function writeAction({ srcPath, docsPath, generatedPath, codeUrl, options, }) {
return __awaiter(this, void 0, void 0, function* () {
const bestPractices = yield (0, parse_1.getAllBestPractices)(srcPath);
yield (0, exports.writeBestPractices)(destPath, bestPractices, codeUrl, options);
yield writeBestPracticesDigest(destPath, (0, digest_1.getBestPracticesDigest)(bestPractices));
return bestPractices;
const allBestPractices = yield (0, parse_1.getAllBestPractices)(srcPath);
let filteredBestPractices;
if (docsPath) {
// It's OK if the generatedPath is within docsPath, because we'll completely replace
// the generated path next. This is a feature not a bug.
const usedIds = yield (0, replace_1.replaceAllBestPracticesInDocs)(docsPath, allBestPractices, (bestPractice) => getBestPracticeCodeLines(bestPractice, codeUrl));
// If a best practice was written out to a static file, do not also include it in the
// generated output
filteredBestPractices = allBestPractices.filter((bp) => !usedIds.has(bp.getMeta('id')));
}
else {
filteredBestPractices = allBestPractices;
}
yield (0, exports.writeBestPractices)(generatedPath, filteredBestPractices, codeUrl, options);
yield writeBestPracticesDigest(generatedPath, (0, digest_1.getBestPracticesDigest)(allBestPractices));
return filteredBestPractices;
});
}
exports.default = writeAction;
Expand Down Expand Up @@ -65,7 +78,7 @@ const writeBestPracticeToFile = (dir, bestPractice, codeUrl, options) => __await
yield (0, promises_1.mkdir)(dirpath, { recursive: true });
}
fd = yield (0, promises_1.open)(fullpath, 'a');
for (const line of writeBestPractice(bestPractice, codeUrl, Object.assign({ writeTitle }, options))) {
for (const line of getBestPracticeFileLines(bestPractice, codeUrl, Object.assign({ writeTitle }, options))) {
yield (0, fs_1.writeLine)(fd, line);
}
}
Expand All @@ -76,7 +89,7 @@ const writeBestPracticeToFile = (dir, bestPractice, codeUrl, options) => __await
/**
* Generate best practice lines.
*/
function* writeBestPractice(bestPractice, codeUrl, { writeTitle = true, writeExtraMeta = true }) {
function* getBestPracticeFileLines(bestPractice, codeUrl, { writeTitle = true, writeExtraMeta = false }) {
if (writeTitle) {
yield '---';
yield `title: ${bestPractice.getTitle()}`;
Expand Down Expand Up @@ -105,21 +118,26 @@ function* writeBestPractice(bestPractice, codeUrl, { writeTitle = true, writeExt
}
yield '';
}
const { sourceFilename, startLine, endLine } = bestPractice;
const url = `${codeUrl}/${sourceFilename}#L${startLine}-L${endLine}`;
yield `[${sourceFilename} lines ${startLine}-${endLine}](${url})`;
yield `\`\`\`${bestPractice.getFileType()}`;
for (const line of (0, string_1.unindent)(bestPractice.codeLines)) {
for (const line of getBestPracticeCodeLines(bestPractice, codeUrl)) {
yield line;
}
yield '```';
}
exports.writeBestPractice = writeBestPractice;
exports.getBestPracticeFileLines = getBestPracticeFileLines;
const getBestPracticeCodeLines = (bestPractice, codeUrl) => {
const { sourceFilename, startLine, endLine } = bestPractice;
const url = `${codeUrl}/${sourceFilename}#L${startLine}-L${endLine}`;
return [
`\`\`\`${bestPractice.getFileType()}`,
...(0, string_1.unindent)(bestPractice.codeLines),
'```',
`From [${sourceFilename} lines ${startLine}-${endLine}](${url})`,
];
};
/**
* Write the digest for best practices.
*/
const writeBestPracticesDigest = (destPath, digest) => __awaiter(void 0, void 0, void 0, function* () {
const digestPath = path_1.default.join(destPath, consts_1.DIGEST_FILENAME);
const writeBestPracticesDigest = (generatedPath, digest) => __awaiter(void 0, void 0, void 0, function* () {
const digestPath = path_1.default.join(generatedPath, consts_1.DIGEST_FILENAME);
let fd;
try {
fd = yield (0, promises_1.open)(digestPath, 'w');
Expand Down
6 changes: 3 additions & 3 deletions lib/cjs/best-practices.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,18 +8,18 @@ const commander_1 = require("commander");
const check_1 = __importDefault(require("./actions/check"));
const write_1 = __importDefault(require("./actions/write"));
const main = () => {
commander_1.program;
commander_1.program
.command('check')
.requiredOption('-s, --src-path <srcPath>')
.requiredOption('-d, --dest-path <destPath>')
.requiredOption('-g, --generated-path <generatedPath>')
.action((args) => {
(0, check_1.default)(args);
});
commander_1.program
.command('write')
.requiredOption('-s, --src-path <srcPath>')
.requiredOption('-d, --dest-path <destPath>')
.option('-d, --docs-path <docsPath>')
.requiredOption('-g, --generated-path <generatedPath>')
.requiredOption('-u, --code-url <codeUrl>')
.action((args) => {
(0, write_1.default)(Object.assign(Object.assign({}, args), { options: {} }));
Expand Down
4 changes: 2 additions & 2 deletions lib/cjs/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,14 +26,14 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.writeBestPractice = exports.writeAction = exports.getFileBestPractices = exports.getBestPracticesDigest = exports.getAllBestPractices = exports.checkAction = exports.BestPractice = void 0;
exports.getBestPracticeFileLines = exports.writeAction = exports.getFileBestPractices = exports.getBestPracticesDigest = exports.getAllBestPractices = exports.checkAction = exports.BestPractice = void 0;
const BestPractice_1 = __importDefault(require("./BestPractice"));
exports.BestPractice = BestPractice_1.default;
const check_1 = __importDefault(require("./actions/check"));
exports.checkAction = check_1.default;
const write_1 = __importStar(require("./actions/write"));
exports.writeAction = write_1.default;
Object.defineProperty(exports, "writeBestPractice", { enumerable: true, get: function () { return write_1.writeBestPractice; } });
Object.defineProperty(exports, "getBestPracticeFileLines", { enumerable: true, get: function () { return write_1.getBestPracticeFileLines; } });
const digest_1 = require("./utils/digest");
Object.defineProperty(exports, "getBestPracticesDigest", { enumerable: true, get: function () { return digest_1.getBestPracticesDigest; } });
const parse_1 = require("./utils/parse");
Expand Down
4 changes: 2 additions & 2 deletions lib/cjs/types/actions/check.d.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
type CheckArgs = {
srcPath: string;
destPath: string;
generatedPath: string;
};
/**
* Compare the digest of the best practices against the stored digest to
* see if the docs need to be updated.
*/
declare const checkAction: ({ srcPath, destPath }: CheckArgs) => Promise<void>;
declare const checkAction: ({ srcPath, generatedPath }: CheckArgs) => Promise<void>;
export default checkAction;
//# sourceMappingURL=check.d.ts.map
2 changes: 1 addition & 1 deletion lib/cjs/types/actions/check.d.ts.map

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 4 additions & 3 deletions lib/cjs/types/actions/write.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,15 @@ type WriteOptions = {
};
type WriteArgs = {
srcPath: string;
destPath: string;
docsPath?: string;
generatedPath: string;
codeUrl: string;
options: WriteOptions;
};
/**
* Generate best practices from source and write them out.
*/
export default function writeAction({ srcPath, destPath, codeUrl, options, }: WriteArgs): Promise<BestPractice[]>;
export default function writeAction({ srcPath, docsPath, generatedPath, codeUrl, options, }: WriteArgs): Promise<BestPractice[]>;
/**
* Writes best practices out to md doc files.
*/
Expand All @@ -24,6 +25,6 @@ type WriteBestPracticeOptions = {
/**
* Generate best practice lines.
*/
export declare function writeBestPractice(bestPractice: BestPractice, codeUrl: string, { writeTitle, writeExtraMeta }: WriteBestPracticeOptions): Generator<string>;
export declare function getBestPracticeFileLines(bestPractice: BestPractice, codeUrl: string, { writeTitle, writeExtraMeta }: WriteBestPracticeOptions): Generator<string>;
export {};
//# sourceMappingURL=write.d.ts.map
2 changes: 1 addition & 1 deletion lib/cjs/types/actions/write.d.ts.map

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions lib/cjs/types/index.d.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import BestPractice from './BestPractice';
import checkAction from './actions/check';
import writeAction, { writeBestPractice } from './actions/write';
import writeAction, { getBestPracticeFileLines } from './actions/write';
import { getBestPracticesDigest } from './utils/digest';
import { getAllBestPractices, getFileBestPractices } from './utils/parse';
export { BestPractice, checkAction, getAllBestPractices, getBestPracticesDigest, getFileBestPractices, writeAction, writeBestPractice, };
export { BestPractice, checkAction, getAllBestPractices, getBestPracticesDigest, getFileBestPractices, writeAction, getBestPracticeFileLines, };
//# sourceMappingURL=index.d.ts.map
2 changes: 1 addition & 1 deletion lib/cjs/types/index.d.ts.map

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 3 additions & 0 deletions lib/cjs/types/utils/fs.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,5 +15,8 @@ export declare const writeLine: (fd: FileHandle, line: string, newline?: string)
* Checks to see if a file exists or not.
*/
export declare const pathExists: (filename: string) => Promise<boolean>;
export declare const readFileLines: (filename: string) => Promise<string[]>;
export declare const writeFileLines: (filename: string, lines: string[]) => Promise<void>;
export declare const isCodeFile: (filename: string) => boolean;
export declare const isDocFile: (filename: string) => boolean;
//# sourceMappingURL=fs.d.ts.map
2 changes: 1 addition & 1 deletion lib/cjs/types/utils/fs.d.ts.map

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion lib/cjs/types/utils/parse.d.ts.map

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading

0 comments on commit ad874d7

Please sign in to comment.