Skip to content

Commit

Permalink
do not commit generated content to VCS
Browse files Browse the repository at this point in the history
This removes `markdown-magic` and replaces its functionality with the built-in data capabilities of 11ty.

The TOC, `--help` output, and source files are now all done via global data scripts in `docs/_data`.

When building documentation, we will no longer get changes to e.g., `docs/index.md` because of the automatically generated content.
  • Loading branch information
boneskull committed May 15, 2020
1 parent c0137eb commit e0754bb
Show file tree
Hide file tree
Showing 11 changed files with 152 additions and 583 deletions.
1 change: 1 addition & 0 deletions .eslintrc.yml
Expand Up @@ -27,6 +27,7 @@ overrides:
- test/integration/options/watch.spec.js
- test/integration/helpers.js
- lib/growl.js
- docs/_data/**/*.js
parserOptions:
ecmaVersion: 2018
env:
Expand Down
2 changes: 1 addition & 1 deletion docs/README.md
Expand Up @@ -34,7 +34,7 @@ _So you wanna build the site?_
cp: docs/_dist/_headers: No such file or directory
```

- See `package-scripts.js` for details on what the builds are actually doing; especially see [markdown-magic](https://npm.im/markdown-magic) for how we're dynamically inserting information into `docs/index.md`.
- See `package-scripts.js` for details on what the builds are actually doing.

## License

Expand Down
52 changes: 52 additions & 0 deletions docs/_data/files.js
@@ -0,0 +1,52 @@
'use strict';

const {resolve, relative, dirname} = require('path');
const {promises: fs} = require('fs');

const PROJECT_ROOT_DIR = resolve(__dirname, '..', '..');
const FILES = [
{
slug: 'simplereporter',
path: require.resolve('../../test/integration/fixtures/simple-reporter.js'),
header: '// my-reporter.js'
}
];

const HEADER = '```js\n';
const FOOTER = '```\n';

const loadFile = async (path, {header} = {}) => {
const relativeDir = relative(dirname(path), PROJECT_ROOT_DIR);
let content = await fs.readFile(path, 'utf-8');
// replace relative paths in `require()` to root with "mocha".
// might not work in the general case. not gonna parse an AST for this
// e.g. `require('../../lib/foo')` => `require('mocha/lib/foo')`
// also trim any trailing whitespace
content = content
.replace(
new RegExp(`require\\(['"]${relativeDir}(.*?)['"]\\)`, 'g'),
"require('mocha$1')"
)
.trim();
return `${HEADER}${header}\n\n${content}${FOOTER}`;
};

/**
* Loads files from disk (see `FILES` above) to be shown as data.
* Used for embedding sources directly into pages
*/
module.exports = async () => {
const files = await Promise.all(
FILES.map(async ({path, header, slug}) => {
const content = await loadFile(path, {header});
return {slug, content};
})
);
return files.reduce(
(files, {slug, content}) => ({
...files,
[slug]: content
}),
{}
);
};
21 changes: 21 additions & 0 deletions docs/_data/toc.js
@@ -0,0 +1,21 @@
'use strict';

const markdownToc = require('markdown-toc');
const {readFileSync} = require('fs');
const {resolve} = require('path');

const IGNORED_HEADINGS_REGEXP = /Features|Table of Contents|Backers|Sponsors/i;
const DOCUMENT_PATH = resolve(__dirname, '..', 'index.md');

module.exports = () => {
const doc = readFileSync(DOCUMENT_PATH, 'utf-8');
return markdownToc(doc, {
slugify: require('uslug'),
firsth1: false,
bullets: '-',
maxdepth: 2,
// if filter is supplied, maxdepth is apparently ignored,
// so we have to do it ourselves.
filter: (str, ele) => ele.lvl < 2 && !IGNORED_HEADINGS_REGEXP.test(str)
}).content;
};
21 changes: 21 additions & 0 deletions docs/_data/usage.js
@@ -0,0 +1,21 @@
'use strict';

const stripAnsi = require('strip-ansi');
const {resolve} = require('path');
const {execSync} = require('child_process');

const executable = require.resolve('../../bin/mocha');
const flag = '--help';

/**
* Return the output of `mocha --help` for display
*/
module.exports = () => {
return stripAnsi(
String(
execSync(`"${process.execPath}" ${executable} ${flag}`, {
cwd: resolve(__dirname, '..')
})
).trim()
);
};
65 changes: 1 addition & 64 deletions docs/api-tutorials/custom-reporter.md
Expand Up @@ -6,70 +6,7 @@ For example, if `mocha-foo-reporter` was published to the npm registry, you coul

If you're looking to get started quickly, here's an example of a custom reporter:

<!-- AUTO-GENERATED-CONTENT:START (file:src=../../test/integration/fixtures/simple-reporter.js&header=// my-reporter.js)' -->

```js
// my-reporter.js
'use strict';

const Mocha = require('mocha');
const {
EVENT_RUN_BEGIN,
EVENT_RUN_END,
EVENT_TEST_FAIL,
EVENT_TEST_PASS,
EVENT_SUITE_BEGIN,
EVENT_SUITE_END
} = Mocha.Runner.constants;

// this reporter outputs test results, indenting two spaces per suite
class MyReporter {
constructor(runner) {
this._indents = 0;
const stats = runner.stats;

runner
.once(EVENT_RUN_BEGIN, () => {
console.log('start');
})
.on(EVENT_SUITE_BEGIN, () => {
this.increaseIndent();
})
.on(EVENT_SUITE_END, () => {
this.decreaseIndent();
})
.on(EVENT_TEST_PASS, test => {
// Test#fullTitle() returns the suite name(s)
// prepended to the test title
console.log(`${this.indent()}pass: ${test.fullTitle()}`);
})
.on(EVENT_TEST_FAIL, (test, err) => {
console.log(
`${this.indent()}fail: ${test.fullTitle()} - error: ${err.message}`
);
})
.once(EVENT_RUN_END, () => {
console.log(`end: ${stats.passes}/${stats.passes + stats.failures} ok`);
});
}

indent() {
return Array(this._indents).join(' ');
}

increaseIndent() {
this._indents++;
}

decreaseIndent() {
this._indents--;
}
}

module.exports = MyReporter;
```

<!-- AUTO-GENERATED-CONTENT:END -->
{{ files.simplereporter }}

To use this reporter, execute `mocha --reporter /path/to/my-reporter.js`.

Expand Down
131 changes: 5 additions & 126 deletions docs/index.md
Expand Up @@ -8,12 +8,12 @@ Mocha is a feature-rich JavaScript test framework running on [Node.js][] and in

<nav class="badges">
<a href="https://gitter.im/mochajs/mocha"><img src="/images/join-chat.svg" alt="Gitter"></a>
<a href="#backers"><img src="//opencollective.com/mochajs/backers/badge.svg" alt="OpenCollective backers"></a>
<a href="#sponsors"><img src="//opencollective.com/mochajs/sponsors/badge.svg" alt="OpenCollective sponsors"></a>
<a href="#backers"><img src="//opencollective.com/mochajs/backers/badge.svg" alt="OpenCollective backers"></a>
</nav>

{% include backers.md %}
{% include sponsors.md %}
{% include backers.md %}

## Features

Expand Down Expand Up @@ -49,39 +49,7 @@ Mocha is a feature-rich JavaScript test framework running on [Node.js][] and in

## Table of Contents

<!-- AUTO-GENERATED-CONTENT:START (toc:maxdepth=2&bullets=-) -->

- [Installation](#installation)
- [Getting Started](#getting-started)
- [Run Cycle Overview](#run-cycle-overview)
- [Detects Multiple Calls to `done()`](#detects-multiple-calls-to-done)
- [Assertions](#assertions)
- [Asynchronous Code](#asynchronous-code)
- [Synchronous Code](#synchronous-code)
- [Arrow Functions](#arrow-functions)
- [Hooks](#hooks)
- [Pending Tests](#pending-tests)
- [Exclusive Tests](#exclusive-tests)
- [Inclusive Tests](#inclusive-tests)
- [Retry Tests](#retry-tests)
- [Dynamically Generating Tests](#dynamically-generating-tests)
- [Timeouts](#timeouts)
- [Diffs](#diffs)
- [Command-Line Usage](#command-line-usage)
- [Interfaces](#interfaces)
- [Reporters](#reporters)
- [Node.JS native ESM support](#nodejs-native-esm-support)
- [Running Mocha in the Browser](#running-mocha-in-the-browser)
- [Desktop Notification Support](#desktop-notification-support)
- [Configuring Mocha (Node.js)](#configuring-mocha-nodejs)
- [The `test/` Directory](#the-test-directory)
- [Error Codes](#error-codes)
- [Editor Plugins](#editor-plugins)
- [Examples](#examples)
- [Testing Mocha](#testing-mocha)
- [More Information](#more-information)

<!-- AUTO-GENERATED-CONTENT:END -->
{{ toc }}

## Installation

Expand Down Expand Up @@ -820,92 +788,9 @@ Mocha supports the `err.expected` and `err.actual` properties of any thrown `Ass

## Command-Line Usage

<!-- AUTO-GENERATED-CONTENT:START (usage:executable=bin/mocha) -->

```text
mocha [spec..]
Run tests with Mocha
Commands
mocha inspect [spec..] Run tests with Mocha [default]
mocha init <path> create a client-side Mocha setup at <path>
Rules & Behavior
--allow-uncaught Allow uncaught errors to propagate [boolean]
--async-only, -A Require all tests to use a callback (async) or
return a Promise [boolean]
--bail, -b Abort ("bail") after first test failure [boolean]
--check-leaks Check for global variable leaks [boolean]
--delay Delay initial execution of root suite [boolean]
--exit Force Mocha to quit after tests complete [boolean]
--forbid-only Fail if exclusive test(s) encountered [boolean]
--forbid-pending Fail if pending test(s) encountered [boolean]
--global, --globals List of allowed global variables [array]
--retries Retry failed tests this many times [number]
--slow, -s Specify "slow" test threshold (in milliseconds)
[string] [default: 75]
--timeout, -t, --timeouts Specify test timeout threshold (in milliseconds)
[string] [default: 2000]
--ui, -u Specify user interface [string] [default: "bdd"]
Reporting & Output
--color, -c, --colors Force-enable color output [boolean]
--diff Show diff on failure
[boolean] [default: true]
--full-trace Display full stack traces [boolean]
--growl, -G Enable Growl notifications [boolean]
--inline-diffs Display actual/expected differences
inline within each string [boolean]
--reporter, -R Specify reporter to use
[string] [default: "spec"]
--reporter-option, --reporter-options, Reporter-specific options
-O (<k=v,[k1=v1,..]>) [array]
Configuration
--config Path to config file [string] [default: (nearest rc file)]
--package Path to package.json for config [string]
File Handling
--extension File extension(s) to load
[array] [default: ["js","cjs","mjs"]]
--file Specify file(s) to be loaded prior to root suite
execution [array] [default: (none)]
--ignore, --exclude Ignore file(s) or glob pattern(s)
[array] [default: (none)]
--recursive Look for tests in subdirectories [boolean]
--require, -r Require module [array] [default: (none)]
--sort, -S Sort test files [boolean]
--watch, -w Watch files in the current working directory for changes
[boolean]
--watch-files List of paths or globs to watch [array]
--watch-ignore List of paths or globs to exclude from watching
[array] [default: ["node_modules",".git"]]
Test Filters
--fgrep, -f Only run tests containing this string [string]
--grep, -g Only run tests matching this string or regexp [string]
--invert, -i Inverts --grep and --fgrep matches [boolean]
Positional Arguments
spec One or more files, directories, or globs to test
[array] [default: ["test"]]
Other Options
--help, -h Show usage information & exit [boolean]
--version, -V Show version number & exit [boolean]
--list-interfaces List built-in user interfaces & exit [boolean]
--list-reporters List built-in reporters & exit [boolean]
Mocha Resources
Chat: https://gitter.im/mochajs/mocha
GitHub: https://github.com/mochajs/mocha.git
Docs: https://mochajs.org/
```

<!-- AUTO-GENERATED-CONTENT:END -->
{{ usage }}
```

### `--allow-uncaught`

Expand Down Expand Up @@ -1969,9 +1854,3 @@ or the [source](https://github.com/mochajs/mocha/blob/master/lib/mocha.js).
[wallaby.js]: https://wallabyjs.com/
[yargs-configobject-extends]: http://yargs.js.org/docs/#api-configobject-extends-keyword
[zsh-globbing]: http://zsh.sourceforge.net/Doc/Release/Expansion.html#Recursive-Globbing

<!-- AUTO-GENERATED-CONTENT:START (manifest:template=[gitter]: ${gitter}) -->

[gitter]: https://gitter.im/mochajs/mocha

<!-- AUTO-GENERATED-CONTENT:END -->

0 comments on commit e0754bb

Please sign in to comment.