Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

[jest-docblock] add docblock.print() #4517

Merged
merged 9 commits into from
Sep 28, 2017
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion packages/jest-docblock/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ Pragmas can also take arguments:
`jest-docblock` can:
* extract the docblock from some code as a string
* parse a docblock string's pragmas into an object
* print an object and some comments back to a string

## Installation
```sh
Expand All @@ -56,13 +57,15 @@ const code = `
}
`;

const { extract, parse } = require("jest-docblock");
const { extract, parse, print } = require("jest-docblock");

const docblock = extract(code);
console.log(docblock); // "/**\n * Everything is awesome!\n * \n * @everything is:awesome\n * @flow\n */"

const pragmas = parse(docblock);
console.log(pragmas); // { everything: "is:awesome", flow: "" }

console.log(print(pragmas, "hi!")) // /**\n * hi!\n *\n * @everything is:awesome\n * @flow\n */;
```

## API Documentation
Expand All @@ -72,3 +75,9 @@ Extracts a docblock from some file contents. Returns the docblock contained in `

### `parse(docblock: string): {[key: string]: string}`
Parses the pragmas in a docblock string into an object whose keys are the pragma tags and whose values are the arguments to those pragmas.

### `parseWithComments(docblock: string): { comments: string, pragmas: {[key: string]: string} }`
Similar to `parse` except this method also returns the comments from the docblock. Useful when used with `print()`.

### `print(object: {[key: string]: string}, comments?: string): string`
Prints an object of key-value pairs back into a docblock. If `comments` are provided, they will be positioned on the top of the docblock.
127 changes: 127 additions & 0 deletions packages/jest-docblock/src/__tests__/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -213,4 +213,131 @@ describe('docblock', () => {
providesModule: 'apple/banana',
});
});

it('extracts comments from docblock', () => {
const code =
'/**' +
os.EOL +
' * hello world' +
os.EOL +
' * @flow yes' +
os.EOL +
' */';
expect(docblock.parseWithComments(code)).toEqual({
comments: 'hello world',
pragmas: {flow: 'yes'},
});
});

it('extracts multiline comments from docblock', () => {
const code =
'/**' +
os.EOL +
' * hello' +
os.EOL +
' * world' +
os.EOL +
' * @flow yes' +
os.EOL +
' */';
expect(docblock.parseWithComments(code)).toEqual({
comments: 'hello\nworld',
pragmas: {flow: 'yes'},
});
});

it('extracts comments from beginning and end of docblock', () => {
const code =
'/**' +
os.EOL +
' * hello' +
os.EOL +
' * @flow yes' +
os.EOL +
' * ' +
os.EOL +
' * world' +
os.EOL +
' */';
expect(docblock.parseWithComments(code)).toEqual({
comments: 'hello\n\nworld',
pragmas: {flow: 'yes'},
});
});

it('prints docblocks with no keys as empty string', () => {
const object = {};
expect(docblock.print(object)).toEqual('');
});

it('prints docblocks with one key on one line', () => {
const object = {flow: ''};
expect(docblock.print(object)).toEqual('/** @flow */');
});

it('prints docblocks with multiple keys on multiple lines', () => {
const object = {
flow: '',
format: '',
};
expect(docblock.print(object)).toEqual(
'/**' + os.EOL + ' * @flow' + os.EOL + ' * @format' + os.EOL + ' */',
);
});

it('prints docblocks with values', () => {
const object = {
flow: 'foo',
providesModule: 'x/y/z',
};
expect(docblock.print(object)).toEqual(
'/**' +
os.EOL +
' * @flow foo' +
os.EOL +
' * @providesModule x/y/z' +
os.EOL +
' */',
);
});

it('prints docblocks with comments', () => {
const object = {flow: 'foo'};
const comments = 'hello';
expect(docblock.print(object, comments)).toEqual(
'/**' +
os.EOL +
' * hello' +
os.EOL +
' *' +
os.EOL +
' * @flow foo' +
os.EOL +
' */',
);
});

it('prints docblocks with comments and no keys', () => {
const object = {};
const comments = 'Copyright 2004-present Facebook. All Rights Reserved.';
expect(docblock.print(object, comments)).toEqual(
'/**' + os.EOL + ' * ' + comments + os.EOL + ' */',
);
});

it('prints docblocks with multiline comments', () => {
const object = {};
const comments = 'hello' + os.EOL + 'world';
expect(docblock.print(object, comments)).toEqual(
'/**' + os.EOL + ' * hello' + os.EOL + ' * world' + os.EOL + ' */',
);
});

it('prints docblocks that are parseable', () => {
const object = {a: 'b', c: ''};
const comments = 'hello world!';
const formatted = docblock.print(object, comments);
const parsed = docblock.parse(formatted);
expect(parsed).toEqual(object);
});
});
61 changes: 56 additions & 5 deletions packages/jest-docblock/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
* @flow
*/

const os = require('os');
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should use import


const commentEndRe = /\*\/$/;
const commentStartRe = /^\/\*\*/;
const docblockRe = /^\s*(\/\*\*?(.|\r?\n)*?\*\/)/;
Expand All @@ -16,14 +18,21 @@ const ltrimRe = /^\s*/;
const multilineRe = /(?:^|\r?\n) *(@[^\r\n]*?) *\r?\n *([^@\r\n\s][^@\r\n]+?) *\r?\n/g;
const propertyRe = /(?:^|\r?\n) *@(\S+) *([^\r\n]*)/g;
const stringStartRe = /(\r?\n|^) *\*/g;
const lineStartRe = /(?:\r?\n|^) */g;
const wsRe = /[\t ]+/g;

function extract(contents: string): string {
export function extract(contents: string): string {
const match = contents.match(docblockRe);
return match ? match[0].replace(ltrimRe, '') || '' : '';
}

function parse(docblock: string): {[key: string]: string} {
export function parse(docblock: string): {[key: string]: string} {
return parseWithComments(docblock).pragmas;
}

export function parseWithComments(
docblock: string,
): {comments: string, pragmas: {[key: string]: string}} {
docblock = docblock
.replace(commentStartRe, '')
.replace(commentEndRe, '')
Expand All @@ -40,12 +49,54 @@ function parse(docblock: string): {[key: string]: string} {
docblock = docblock.trim();

const result = Object.create(null);
const comments = docblock.replace(propertyRe, '').replace(lineStartRe, '\n');
let match;
while ((match = propertyRe.exec(docblock))) {
result[match[1]] = match[2];
}
return result;
return {comments: comments.trim(), pragmas: result};
}

export function print(
object: {[key: string]: string} = {},
comments: string = '',
): string {
const head = '/**';
const start = ' *';
const tail = ' */';

const keys = Object.keys(object);
const line = os.EOL;

const printedObject = keys
.map(key => start + ' ' + printKeyValue(key, object[key]) + line)
.join('');

if (!comments) {
if (keys.length === 0) {
return '';
}
if (keys.length === 1) {
return `${head} ${printKeyValue(keys[0], object[keys[0]])}${tail}`;
}
}

const printedComments =
comments
.split(os.EOL)
Copy link
Member

@SimenB SimenB Sep 20, 2017

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can we detect the original EOL in the comment instead (https://www.npmjs.com/package/detect-newline)? People might use LF even if they're on Windows (e.g. airbnb eslint config requires LF regardless of OS)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should I do the same for the existing parse, which has a hard-coded \n?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think that makes sense, yeah 🙂

.map(textLine => `${start} ${textLine}`)
.join(os.EOL) + os.EOL;

return (
head +
line +
(comments ? printedComments : '') +
(comments && keys.length ? start + line : '') +
printedObject +
tail
);
}

exports.extract = extract;
exports.parse = parse;
function printKeyValue(key, value) {
return `@${key} ${value}`.trim();
}