Skip to content

Commit

Permalink
feat(error): drop ci command and exit with error code
Browse files Browse the repository at this point in the history
Switch from yargs to commander to prepare newer versions
Improve output style
  • Loading branch information
ph1p committed Aug 4, 2020
1 parent cfdbdcd commit 37d4bd6
Show file tree
Hide file tree
Showing 8 changed files with 276 additions and 158 deletions.
11 changes: 5 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,6 @@ If no command passed it will run `generate` as default
| --rmPattern | -rm | | Pattern when removing files. You can ex- and include files. (glob pattern) |
| --partials | -p | | jsdoc2markdown partial templates (overwrites default ones) |
| --jsDocConfigPath | -c | | Path to [JsDoc Config](http://usejsdoc.org/about-configuring-jsdoc.html) (experimental) |
| --ci | - | false | Set this for your continuous integration tool. This causes errors to be thrown and not ignored. You can also use the global env variable `CI` instead |

### config.js

Expand All @@ -59,7 +58,7 @@ You can add all generated documentation files to your existing vuepress project

```bash
# First install vuepress
yarn global add vuepress
yarn global add vuepress

# Run the CLI
vuepress-jsdoc
Expand Down Expand Up @@ -154,19 +153,19 @@ The `./example` folder includes a full working vuepress-jsdoc example.

```bash
# Install dependencies
yarn
npm install

# Run the CLI
vuepress-jsdoc

# Generate docs
yarn docs
npm run docs

# Run dev server
yarn dev
npm run dev

# Generate dist folder
yarn build
npm run build
```

## Contribute
Expand Down
28 changes: 27 additions & 1 deletion bin/vuepress-jsdoc.js
Original file line number Diff line number Diff line change
@@ -1,2 +1,28 @@
#!/usr/bin/env node
require('../')();
'use strict';

const { program } = require('commander');

const { generate } = require('../cmds');
const { version } = require('../package.json');

program.version(version).description('a CLI Tool to generate markdown files for vuepress');

program
.description('Generate the md files')
.option('-s, --source <string>', 'Source folder with .js or .ts files', './src')
.option('-d, --dist <string>', 'Destination folder', './documentation')
.option('-f, --folder <string>', 'Folder inside destination folder. Gets overwritten everytime', 'code')
.option('-t, --title <string>', 'Title of your documentation', 'API')
.option('-r, --readme <string>', 'Path to your custom readme')
.option('-e, --exclude <string>', 'Pattern to exclude files/folders (Comma seperated) - *.test.js,exclude.js')
.option(
'-rm, --rmPattern [files...]',
'Pattern when removing files. You can ex- and include files. (glob pattern)',
[]
)
.option('-p, --partials [files...]', 'jsdoc2markdown partial templates (overwrites default ones)', [])
.option('-c, --jsDocConfigPath <string>', 'Path to jsdoc config')
.action(generate);

program.parse(process.argv);
90 changes: 51 additions & 39 deletions cmds/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -18,15 +18,30 @@ const statistics = {};
const statusTypes = {
success: 'green',
error: 'red',
exclude: 'blue',
exclude: 'blueBright',
empty: 'yellow'
};

const extensions = ['.ts', '.js', '.tsx', '.jsx', '.vue'];

/**A
* Add status and count to result
* @param {string} file
* @param {string} status
* @param {boolean} isFolder
*/
const addToStatistics = (file, status, isFolder = false) => {
const extension = !isFolder ? getExtension(file) : 'folder';

if (!statistics[extension]) {
statistics[extension] = Object.keys(statusTypes).reduce((before, curr) => ({ ...before, [curr]: 0 }), {});
}
statistics[extension][status]++;
};

/**
* Default command that generate md files
* @param {object} argv Arguments passed by yargs
* @param {object} argv passed arguments
*/
async function generate(argv) {
const exclude = (argv.exclude && argv.exclude.split(',')) || [argv.exclude || ''];
Expand All @@ -41,15 +56,6 @@ async function generate(argv) {
// remove docs folder, except README.md
const deletedPaths = await del([`${docsFolder}/**/*`, `!${docsFolder}/README.md`, ...rmPattern]);

const addToStatistics = (file, status, isFolder = false) => {
const extension = !isFolder ? getExtension(file) : 'folder';

if (!statistics[extension]) {
statistics[extension] = Object.keys(statusTypes).reduce((before, curr) => ({ ...before, [curr]: 0 }), {});
}
statistics[extension][status]++;
};

/**
* Read all files in directory
* @param {string} folder
Expand All @@ -72,8 +78,8 @@ async function generate(argv) {

// iterate through all files in folder
await asyncForEach(files, async file => {
if (exclude && mm.contains(`${folder}/${file}`, exclude)) {
console.log(chalk.black.bgBlue.bold(' EXCLUDE '), `${folder}/${file}`);
if (exclude && mm.contains(`${chalk.dim(folder)}/${file}`, exclude)) {
console.log(chalk.reset.inverse.bold.blueBright(' EXCLUDE '), `${chalk.dim(folder)}/${chalk.bold(file)}`);

addToStatistics(file, 'exclude');
return;
Expand All @@ -100,9 +106,12 @@ async function generate(argv) {
}

addToStatistics(file, 'success', true);
} catch (err) {
console.log(err);
console.log(chalk.yellow('cannot create folder, because it already exists'), `${folderPath}/${file}`);
} catch (error) {
console.log(error.message);
console.log(
chalk.yellow('cannot create folder, because it already exists'),
`${chalk.dim(folderPath)}/${file}`
);

addToStatistics(file, 'error', true);
}
Expand All @@ -114,11 +123,7 @@ async function generate(argv) {
});

// read files from subfolder
await readFiles(
`${folder}/${file}`,
depth + 1,
tree.filter(treeItem => file === treeItem.name)[0].children
);
await readFiles(`${folder}/${file}`, depth + 1, tree.filter(treeItem => file === treeItem.name)[0].children);
}
// Else branch accessed when file is not a folder
else {
Expand Down Expand Up @@ -147,17 +152,15 @@ async function generate(argv) {
const isConfigExclude = error.message.includes('no input files');

console.log(
chalk.black.bgRed.bold(isConfigExclude ? ' EXCLUDE BY CONFIG ' : ' ERROR '),
`${folder}/${file} -> ${folderPath}/${fileName}.md`
chalk.reset.inverse.bold.red(isConfigExclude ? ' EXCLUDE BY CONFIG ' : ' ERROR '),
`${chalk.dim(folder)}/${chalk.bold(file)} \u2192 ${chalk.dim(folderPath)}/${chalk.bold(
fileName + '.md'
)}`
);

if (!isConfigExclude) {
console.log(error.message);

if (process.env.CI || argv.ci) {
throw new Error(error);
}

addToStatistics(file, 'error');
}
}
Expand All @@ -166,7 +169,12 @@ async function generate(argv) {
if (mdFileData) {
const { frontmatter, attributes } = parseVuepressComment(fileData);

console.log(chalk.black.bgGreen.bold(' SUCCESS '), `${folder}/${file} -> ${folderPath}/${fileName}.md`);
console.log(
chalk.reset.inverse.bold.green(' SUCCESS '),
`${chalk.dim(folder)}/${chalk.bold(file)} \u2192 ${chalk.dim(folderPath)}/${chalk.bold(
fileName + '.md'
)}`
);

let fileContent = '---\n';

Expand Down Expand Up @@ -201,7 +209,12 @@ async function generate(argv) {

addToStatistics(file, 'success');
} else {
console.log(chalk.black.bgYellow.bold(' EMPTY '), `${folder}/${file} -> ${folderPath}/${fileName}.md`);
console.log(
chalk.reset.inverse.bold.yellow(' EMPTY '),
`${chalk.dim(folder)}/${chalk.bold(file)} \u2192 ${chalk.dim(folderPath)}/${chalk.bold(
fileName + '.md'
)}`
);

addToStatistics(file, 'empty');
}
Expand All @@ -214,11 +227,7 @@ async function generate(argv) {
if (error.code === 'ENOENT') {
console.log('cannot find source folder');
} else {
console.log(error);
}

if (process.env.CI || argv.ci) {
throw new Error(error);
console.log(error.message);
}
}
};
Expand Down Expand Up @@ -263,13 +272,13 @@ async function generate(argv) {

const resultTime = (Math.abs(startTime - +new Date()) / 1000).toFixed(2);

//
const maxExtLength = Math.max.apply(
null,
Object.keys(statistics).map(w => w.length)
);
// get longest type string
const maxExtLength = Math.max.apply(null, Object.keys(statistics).map(w => w.length));

console.log(`\n${Array(maxExtLength + maxExtLength / 2).join('-')}`);

const errorCount = Object.keys(statistics).reduce((b, c) => b + statistics[c].error, 0);
// iterate trough stats
Object.entries(statistics)
.sort()
.forEach(([extension, types]) => {
Expand All @@ -286,7 +295,10 @@ async function generate(argv) {
)}| ${content} - ${total} total`
);
});

console.log(`${Array(maxExtLength + maxExtLength / 2).join('-')}\nTime: ${resultTime}s\n`);

process.exit(errorCount ? 1 : 0);
});
}

Expand Down
8 changes: 4 additions & 4 deletions example/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,17 @@

```bash
# Install dependencies
yarn
npm install

# Run the CLI
vuepress-jsdoc

# Generate docs
yarn run docs
npm run docs

# Run dev server
yarn run dev
npm run dev

# Generate dist folder
yarn run build
npm run build
```
2 changes: 1 addition & 1 deletion helpers/vue-docgen-to-markdown.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ function generateTags({ tags }) {
}

function fileContent() {
let contentArray = [];
const contentArray = [];
let line = 0;

return {
Expand Down
79 changes: 0 additions & 79 deletions index.js

This file was deleted.

Loading

0 comments on commit 37d4bd6

Please sign in to comment.