prettier/index.js

288 lines
7.9 KiB
JavaScript
Raw Normal View History

2017-01-10 20:18:22 +03:00
"use strict";
2017-01-28 18:50:22 +03:00
const comments = require("./src/comments");
const version = require("./package.json").version;
const printAstToDoc = require("./src/printer").printAstToDoc;
Find nearest node when formatting range (#1659) * Move range extension code into helper functions * Add findNodeByOffset() helper This was adapted from https://github.com/prettier/prettier/pull/1637/commits/cbc1929c64db558b4e444500bca3d2ce1d550359 * Test extending formatted range to entire node * Fix extending formatted range to entire node * Fix style errors * Add run_file test function This makes it possible to use different options on a per-file basis, which is useful for things like range formatting tests. * Test extending the format range to nearest parseable node This means you can select the range of a `catch` clause, attempt to format it, and have the `try` formatted as well, rather than throwing an error. * Fix extending the format range to nearest parseable node This means you can select the range of a `catch` clause, attempt to format it, and have the `try` formatted as well, rather than throwing an error. * Test that external indentation is left alone when formatting a range * Preserve external indentation when formatting a range * Dedupe range formatting traversal callbacks * Simplify range formatting traversal using ast-types See https://github.com/prettier/prettier/pull/1659#issuecomment-302974798 * Make range formatting traversal more efficient There's less unnecessary parsing now. * Fix style errors * Add test where range expanding fails * Fix test where range expanding fails This makes sure that the range contains the entirety of the nodes containing each of the range's endpoints. * Add test for expanding range to beginning of line * Pass test for expanding range to beginning of line This makes it so that indentation before the range is added to the formatted range. * Don't parse/stringify AST to detect pre-range indentation See https://github.com/prettier/prettier/pull/1659#discussion_r117790671 * When formatting a range, find closest statement rather than parsing The `isStatement` implementation came from `docs/prettier.min.js`. See https://github.com/prettier/prettier/pull/1659#issuecomment-303154770 * Add test for range-formatting a FunctionDeclaration's argument object * Include FunctionDeclaration when searching for nearest node to range-format From the spec, a Program is a series of SourceElements, each of which is either a Statement or a FunctionDeclaration. See https://www.ecma-international.org/ecma-262/5.1/#sec-A.5 * Remove unnecessary try-catch See https://github.com/prettier/prettier/pull/1659#discussion_r117810096 * Add tests with multiple statements See https://github.com/prettier/prettier/pull/1659#discussion_r117810753 * Remove unnecessary arguments from findNodeByOffset() * Contract format range to ensure it starts/ends on nodes * Specify test ranges in the fixtures See https://github.com/prettier/prettier/pull/1659#discussion_r117811186 * Remove unnecessary comments from range fixtures * Remove run_file test function It's no longer used. This essentially reverts 8241216e68f2e0da997a4f558b03658d642c89a2 * Update range formatting docs Clarify that the range expands to the nearest statement, and not to the end of the line. * Don't overwrite test options when detecting range Now that multiple files share the same object again, we shouldn't be re-assigning to it. * Reuse already-read fixtures for AST_COMPARE=1 tests * Remove `run_file` global from test eslintrc * Undo package.json churn `yarn` reformatted it before, but the whitespace visually sets off the comment, so let's put it back how it was before. See https://github.com/prettier/prettier/pull/1659#discussion_r117864655 * Remove misleading comments from isSourceElement See https://github.com/prettier/prettier/pull/1659#discussion_r117865196 * Loop backwards through string instead of reversing it See https://github.com/prettier/prettier/pull/1659#discussion_r117865759 * Don't recompute indent string when formatting range See https://github.com/prettier/prettier/pull/1659#discussion_r117867268 * Rename findNodeByOffset to findNodeAtOffset "Find x by y" is the common usage for finding an `x` by a key `y`. However, since "by" has positional meaning, let's use "at" instead. See https://github.com/prettier/prettier/pull/1659#discussion_r117865121 * Always trimRight() in formatRange and explain why See https://github.com/prettier/prettier/pull/1659#discussion_r117864635 * Test formatting a range that crosses AST levels See https://github.com/prettier/prettier/pull/1659#issuecomment-303243688 * Fix formatting a range that crosses AST levels See https://github.com/prettier/prettier/pull/1659#issuecomment-303243688 * Remove unnecessary try-catch See https://github.com/prettier/prettier/pull/1659/files/e52db5e9f9ec4af599f658da03739e206dd4578c#r117878763 * Add test demonstrating range formatting indent detection * Detect alignment from text on line before range, but don't reformat it This avoids reformatting non-indentation that happens to precede the range on the same line, while still correctly indenting the range based on it. See https://github.com/prettier/prettier/pull/1659#discussion_r117881430
2017-05-23 17:43:58 +03:00
const util = require("./src/util");
const printDocToString = require("./src/doc-printer").printDocToString;
const normalizeOptions = require("./src/options").normalize;
2017-05-29 07:49:41 +03:00
const parser = require("./parser");
const printDocToDebug = require("./src/doc-debug").printDocToDebug;
2016-11-29 23:23:00 +03:00
function guessLineEnding(text) {
const index = text.indexOf("\n");
if (index >= 0 && text.charAt(index - 1) === "\r") {
return "\r\n";
}
return "\n";
}
function attachComments(text, ast, opts) {
const astComments = ast.comments;
if (astComments) {
delete ast.comments;
comments.attach(astComments, ast, text, opts);
}
ast.tokens = [];
opts.originalText = text.trimRight();
return astComments;
}
function ensureAllCommentsPrinted(astComments) {
if (!astComments) {
return;
}
for (let i = 0; i < astComments.length; ++i) {
if (astComments[i].value.trim() === "prettier-ignore") {
// If there's a prettier-ignore, we're not printing that sub-tree so we
// don't know if the comments was printed or not.
return;
}
}
astComments.forEach(comment => {
if (!comment.printed) {
throw new Error(
2017-02-16 06:56:11 +03:00
'Comment "' +
comment.value.trim() +
'" was not printed. Please report this error!'
);
}
delete comment.printed;
});
}
Add `--range-start` and `--range-end` options to format only parts of the input (#1609) * Add `--range-start` and `--range-end` options to format only parts of the input These options default to `0` and `Infinity`, respectively, so that the entire input is formatted by default. However, if either option is specified such that a node lies completely outside the resulting range, the node will be treated as if it has a `// prettier-ignore` comment. Related to https://github.com/prettier/prettier/pull/1577#issuecomment-300551179 Related to https://github.com/prettier/prettier/issues/1324 Related to https://github.com/prettier/prettier/issues/593 * printer: Extract hasPrettierIgnoreComment() helper * Move isOutsideRange() to util * Don't throw errors about comments outside range "not printing" * Remove unnecessary check from isOutsideRange() * Make --range-end exclusive This lets it use the conventional way of specifying ranges in strings. Note that if the rangeEnd in the tests is changed to 158, it will fail, but it wouldn't have failed before this change. * Change range formatting approach NOTE: This doesn't pass its test yet. Note that since we're reading the indentation from the first line, it is expected not to change. However, a semicolon is added, and the lines outside the range are not changed. The new approach is roughly: * Require that the range exactly covers an integer number of lines of the input * Detect the indentation of the line the range starts on * Format the range's substring using `printAstToDoc` * Add enough `indent`s to the doc to restore the detected indentation * Format the doc to a string with `printDocToString` * Prepend/append the original input before/after the range See https://github.com/prettier/prettier/pull/1609#issuecomment-301582273 --- Given `tests/range/range.js`, run the following: prettier tests/range/range.js --range-start 165 --range-end 246 See the range's text with: dd if=tests/range/range.js ibs=1 skip=165 count=81 2>/dev/null * Don't use default function parameters Node v4 doesn't support them. See http://node.green/#ES2015-syntax-default-function-parameters * Hackily fix indentation of range formatting See https://github.com/prettier/prettier/pull/1609#issuecomment-301625368 Also update the snapshot to reflect that the indentation actually should decrease by one space, since there were 13 spaces in the input and we round down after dividing by tabWidth. * Revert "printer: Extract hasPrettierIgnoreComment() helper" See https://github.com/prettier/prettier/pull/1609#discussion_r116804853 This reverts commit 62bf068ca98f69d4a7fd0ae188b3554d409eee8d. * Test automatically using the beginning of the rangeStart line and same for the end See https://github.com/prettier/prettier/pull/1609#issuecomment-301862076 * Fix automatically using the beginning of the rangeStart line and same for the end See https://github.com/prettier/prettier/pull/1609#issuecomment-301862076 * Propagate breaks after adding an indentation-triggering hardline See https://github.com/prettier/prettier/pull/1609/files/c1a61ebde8be73414c0a54bde3f323ac24295715#r116805581 * Extract getAlignmentSize(), use instead of countIndents() See https://github.com/prettier/prettier/pull/1609/files/c1a61ebde8be73414c0a54bde3f323ac24295715#r116804694 * Extract addAlignmentToDoc(), use instead of addIndentsToDoc() See https://github.com/prettier/prettier/pull/1609/files/c1a61ebde8be73414c0a54bde3f323ac24295715#r116804694 * Document that --range-start and --range-end include the entire line * Fix rangeStart calculation Before, it was incorrectly resulting in 1 when the originally provided value was 0 * Extract formatRange() helper function * Move getAlignmentSize() from printer to util This addresses https://github.com/prettier/prettier/pull/1609#discussion_r117636241 * Move addAlignmentToDoc() from printer to doc-builders This addresses https://github.com/prettier/prettier/pull/1609#discussion_r117636251
2017-05-21 20:14:13 +03:00
function format(text, opts, addAlignmentSize) {
addAlignmentSize = addAlignmentSize || 0;
Find nearest node when formatting range (#1659) * Move range extension code into helper functions * Add findNodeByOffset() helper This was adapted from https://github.com/prettier/prettier/pull/1637/commits/cbc1929c64db558b4e444500bca3d2ce1d550359 * Test extending formatted range to entire node * Fix extending formatted range to entire node * Fix style errors * Add run_file test function This makes it possible to use different options on a per-file basis, which is useful for things like range formatting tests. * Test extending the format range to nearest parseable node This means you can select the range of a `catch` clause, attempt to format it, and have the `try` formatted as well, rather than throwing an error. * Fix extending the format range to nearest parseable node This means you can select the range of a `catch` clause, attempt to format it, and have the `try` formatted as well, rather than throwing an error. * Test that external indentation is left alone when formatting a range * Preserve external indentation when formatting a range * Dedupe range formatting traversal callbacks * Simplify range formatting traversal using ast-types See https://github.com/prettier/prettier/pull/1659#issuecomment-302974798 * Make range formatting traversal more efficient There's less unnecessary parsing now. * Fix style errors * Add test where range expanding fails * Fix test where range expanding fails This makes sure that the range contains the entirety of the nodes containing each of the range's endpoints. * Add test for expanding range to beginning of line * Pass test for expanding range to beginning of line This makes it so that indentation before the range is added to the formatted range. * Don't parse/stringify AST to detect pre-range indentation See https://github.com/prettier/prettier/pull/1659#discussion_r117790671 * When formatting a range, find closest statement rather than parsing The `isStatement` implementation came from `docs/prettier.min.js`. See https://github.com/prettier/prettier/pull/1659#issuecomment-303154770 * Add test for range-formatting a FunctionDeclaration's argument object * Include FunctionDeclaration when searching for nearest node to range-format From the spec, a Program is a series of SourceElements, each of which is either a Statement or a FunctionDeclaration. See https://www.ecma-international.org/ecma-262/5.1/#sec-A.5 * Remove unnecessary try-catch See https://github.com/prettier/prettier/pull/1659#discussion_r117810096 * Add tests with multiple statements See https://github.com/prettier/prettier/pull/1659#discussion_r117810753 * Remove unnecessary arguments from findNodeByOffset() * Contract format range to ensure it starts/ends on nodes * Specify test ranges in the fixtures See https://github.com/prettier/prettier/pull/1659#discussion_r117811186 * Remove unnecessary comments from range fixtures * Remove run_file test function It's no longer used. This essentially reverts 8241216e68f2e0da997a4f558b03658d642c89a2 * Update range formatting docs Clarify that the range expands to the nearest statement, and not to the end of the line. * Don't overwrite test options when detecting range Now that multiple files share the same object again, we shouldn't be re-assigning to it. * Reuse already-read fixtures for AST_COMPARE=1 tests * Remove `run_file` global from test eslintrc * Undo package.json churn `yarn` reformatted it before, but the whitespace visually sets off the comment, so let's put it back how it was before. See https://github.com/prettier/prettier/pull/1659#discussion_r117864655 * Remove misleading comments from isSourceElement See https://github.com/prettier/prettier/pull/1659#discussion_r117865196 * Loop backwards through string instead of reversing it See https://github.com/prettier/prettier/pull/1659#discussion_r117865759 * Don't recompute indent string when formatting range See https://github.com/prettier/prettier/pull/1659#discussion_r117867268 * Rename findNodeByOffset to findNodeAtOffset "Find x by y" is the common usage for finding an `x` by a key `y`. However, since "by" has positional meaning, let's use "at" instead. See https://github.com/prettier/prettier/pull/1659#discussion_r117865121 * Always trimRight() in formatRange and explain why See https://github.com/prettier/prettier/pull/1659#discussion_r117864635 * Test formatting a range that crosses AST levels See https://github.com/prettier/prettier/pull/1659#issuecomment-303243688 * Fix formatting a range that crosses AST levels See https://github.com/prettier/prettier/pull/1659#issuecomment-303243688 * Remove unnecessary try-catch See https://github.com/prettier/prettier/pull/1659/files/e52db5e9f9ec4af599f658da03739e206dd4578c#r117878763 * Add test demonstrating range formatting indent detection * Detect alignment from text on line before range, but don't reformat it This avoids reformatting non-indentation that happens to precede the range on the same line, while still correctly indenting the range based on it. See https://github.com/prettier/prettier/pull/1659#discussion_r117881430
2017-05-23 17:43:58 +03:00
const ast = parser.parse(text, opts);
const formattedRangeOnly = formatRange(text, opts, ast);
Add `--range-start` and `--range-end` options to format only parts of the input (#1609) * Add `--range-start` and `--range-end` options to format only parts of the input These options default to `0` and `Infinity`, respectively, so that the entire input is formatted by default. However, if either option is specified such that a node lies completely outside the resulting range, the node will be treated as if it has a `// prettier-ignore` comment. Related to https://github.com/prettier/prettier/pull/1577#issuecomment-300551179 Related to https://github.com/prettier/prettier/issues/1324 Related to https://github.com/prettier/prettier/issues/593 * printer: Extract hasPrettierIgnoreComment() helper * Move isOutsideRange() to util * Don't throw errors about comments outside range "not printing" * Remove unnecessary check from isOutsideRange() * Make --range-end exclusive This lets it use the conventional way of specifying ranges in strings. Note that if the rangeEnd in the tests is changed to 158, it will fail, but it wouldn't have failed before this change. * Change range formatting approach NOTE: This doesn't pass its test yet. Note that since we're reading the indentation from the first line, it is expected not to change. However, a semicolon is added, and the lines outside the range are not changed. The new approach is roughly: * Require that the range exactly covers an integer number of lines of the input * Detect the indentation of the line the range starts on * Format the range's substring using `printAstToDoc` * Add enough `indent`s to the doc to restore the detected indentation * Format the doc to a string with `printDocToString` * Prepend/append the original input before/after the range See https://github.com/prettier/prettier/pull/1609#issuecomment-301582273 --- Given `tests/range/range.js`, run the following: prettier tests/range/range.js --range-start 165 --range-end 246 See the range's text with: dd if=tests/range/range.js ibs=1 skip=165 count=81 2>/dev/null * Don't use default function parameters Node v4 doesn't support them. See http://node.green/#ES2015-syntax-default-function-parameters * Hackily fix indentation of range formatting See https://github.com/prettier/prettier/pull/1609#issuecomment-301625368 Also update the snapshot to reflect that the indentation actually should decrease by one space, since there were 13 spaces in the input and we round down after dividing by tabWidth. * Revert "printer: Extract hasPrettierIgnoreComment() helper" See https://github.com/prettier/prettier/pull/1609#discussion_r116804853 This reverts commit 62bf068ca98f69d4a7fd0ae188b3554d409eee8d. * Test automatically using the beginning of the rangeStart line and same for the end See https://github.com/prettier/prettier/pull/1609#issuecomment-301862076 * Fix automatically using the beginning of the rangeStart line and same for the end See https://github.com/prettier/prettier/pull/1609#issuecomment-301862076 * Propagate breaks after adding an indentation-triggering hardline See https://github.com/prettier/prettier/pull/1609/files/c1a61ebde8be73414c0a54bde3f323ac24295715#r116805581 * Extract getAlignmentSize(), use instead of countIndents() See https://github.com/prettier/prettier/pull/1609/files/c1a61ebde8be73414c0a54bde3f323ac24295715#r116804694 * Extract addAlignmentToDoc(), use instead of addIndentsToDoc() See https://github.com/prettier/prettier/pull/1609/files/c1a61ebde8be73414c0a54bde3f323ac24295715#r116804694 * Document that --range-start and --range-end include the entire line * Fix rangeStart calculation Before, it was incorrectly resulting in 1 when the originally provided value was 0 * Extract formatRange() helper function * Move getAlignmentSize() from printer to util This addresses https://github.com/prettier/prettier/pull/1609#discussion_r117636241 * Move addAlignmentToDoc() from printer to doc-builders This addresses https://github.com/prettier/prettier/pull/1609#discussion_r117636251
2017-05-21 20:14:13 +03:00
if (formattedRangeOnly) {
return formattedRangeOnly;
}
const astComments = attachComments(text, ast, opts);
Add `--range-start` and `--range-end` options to format only parts of the input (#1609) * Add `--range-start` and `--range-end` options to format only parts of the input These options default to `0` and `Infinity`, respectively, so that the entire input is formatted by default. However, if either option is specified such that a node lies completely outside the resulting range, the node will be treated as if it has a `// prettier-ignore` comment. Related to https://github.com/prettier/prettier/pull/1577#issuecomment-300551179 Related to https://github.com/prettier/prettier/issues/1324 Related to https://github.com/prettier/prettier/issues/593 * printer: Extract hasPrettierIgnoreComment() helper * Move isOutsideRange() to util * Don't throw errors about comments outside range "not printing" * Remove unnecessary check from isOutsideRange() * Make --range-end exclusive This lets it use the conventional way of specifying ranges in strings. Note that if the rangeEnd in the tests is changed to 158, it will fail, but it wouldn't have failed before this change. * Change range formatting approach NOTE: This doesn't pass its test yet. Note that since we're reading the indentation from the first line, it is expected not to change. However, a semicolon is added, and the lines outside the range are not changed. The new approach is roughly: * Require that the range exactly covers an integer number of lines of the input * Detect the indentation of the line the range starts on * Format the range's substring using `printAstToDoc` * Add enough `indent`s to the doc to restore the detected indentation * Format the doc to a string with `printDocToString` * Prepend/append the original input before/after the range See https://github.com/prettier/prettier/pull/1609#issuecomment-301582273 --- Given `tests/range/range.js`, run the following: prettier tests/range/range.js --range-start 165 --range-end 246 See the range's text with: dd if=tests/range/range.js ibs=1 skip=165 count=81 2>/dev/null * Don't use default function parameters Node v4 doesn't support them. See http://node.green/#ES2015-syntax-default-function-parameters * Hackily fix indentation of range formatting See https://github.com/prettier/prettier/pull/1609#issuecomment-301625368 Also update the snapshot to reflect that the indentation actually should decrease by one space, since there were 13 spaces in the input and we round down after dividing by tabWidth. * Revert "printer: Extract hasPrettierIgnoreComment() helper" See https://github.com/prettier/prettier/pull/1609#discussion_r116804853 This reverts commit 62bf068ca98f69d4a7fd0ae188b3554d409eee8d. * Test automatically using the beginning of the rangeStart line and same for the end See https://github.com/prettier/prettier/pull/1609#issuecomment-301862076 * Fix automatically using the beginning of the rangeStart line and same for the end See https://github.com/prettier/prettier/pull/1609#issuecomment-301862076 * Propagate breaks after adding an indentation-triggering hardline See https://github.com/prettier/prettier/pull/1609/files/c1a61ebde8be73414c0a54bde3f323ac24295715#r116805581 * Extract getAlignmentSize(), use instead of countIndents() See https://github.com/prettier/prettier/pull/1609/files/c1a61ebde8be73414c0a54bde3f323ac24295715#r116804694 * Extract addAlignmentToDoc(), use instead of addIndentsToDoc() See https://github.com/prettier/prettier/pull/1609/files/c1a61ebde8be73414c0a54bde3f323ac24295715#r116804694 * Document that --range-start and --range-end include the entire line * Fix rangeStart calculation Before, it was incorrectly resulting in 1 when the originally provided value was 0 * Extract formatRange() helper function * Move getAlignmentSize() from printer to util This addresses https://github.com/prettier/prettier/pull/1609#discussion_r117636241 * Move addAlignmentToDoc() from printer to doc-builders This addresses https://github.com/prettier/prettier/pull/1609#discussion_r117636251
2017-05-21 20:14:13 +03:00
const doc = printAstToDoc(ast, opts, addAlignmentSize);
opts.newLine = guessLineEnding(text);
const str = printDocToString(doc, opts);
ensureAllCommentsPrinted(astComments);
Find nearest node when formatting range (#1659) * Move range extension code into helper functions * Add findNodeByOffset() helper This was adapted from https://github.com/prettier/prettier/pull/1637/commits/cbc1929c64db558b4e444500bca3d2ce1d550359 * Test extending formatted range to entire node * Fix extending formatted range to entire node * Fix style errors * Add run_file test function This makes it possible to use different options on a per-file basis, which is useful for things like range formatting tests. * Test extending the format range to nearest parseable node This means you can select the range of a `catch` clause, attempt to format it, and have the `try` formatted as well, rather than throwing an error. * Fix extending the format range to nearest parseable node This means you can select the range of a `catch` clause, attempt to format it, and have the `try` formatted as well, rather than throwing an error. * Test that external indentation is left alone when formatting a range * Preserve external indentation when formatting a range * Dedupe range formatting traversal callbacks * Simplify range formatting traversal using ast-types See https://github.com/prettier/prettier/pull/1659#issuecomment-302974798 * Make range formatting traversal more efficient There's less unnecessary parsing now. * Fix style errors * Add test where range expanding fails * Fix test where range expanding fails This makes sure that the range contains the entirety of the nodes containing each of the range's endpoints. * Add test for expanding range to beginning of line * Pass test for expanding range to beginning of line This makes it so that indentation before the range is added to the formatted range. * Don't parse/stringify AST to detect pre-range indentation See https://github.com/prettier/prettier/pull/1659#discussion_r117790671 * When formatting a range, find closest statement rather than parsing The `isStatement` implementation came from `docs/prettier.min.js`. See https://github.com/prettier/prettier/pull/1659#issuecomment-303154770 * Add test for range-formatting a FunctionDeclaration's argument object * Include FunctionDeclaration when searching for nearest node to range-format From the spec, a Program is a series of SourceElements, each of which is either a Statement or a FunctionDeclaration. See https://www.ecma-international.org/ecma-262/5.1/#sec-A.5 * Remove unnecessary try-catch See https://github.com/prettier/prettier/pull/1659#discussion_r117810096 * Add tests with multiple statements See https://github.com/prettier/prettier/pull/1659#discussion_r117810753 * Remove unnecessary arguments from findNodeByOffset() * Contract format range to ensure it starts/ends on nodes * Specify test ranges in the fixtures See https://github.com/prettier/prettier/pull/1659#discussion_r117811186 * Remove unnecessary comments from range fixtures * Remove run_file test function It's no longer used. This essentially reverts 8241216e68f2e0da997a4f558b03658d642c89a2 * Update range formatting docs Clarify that the range expands to the nearest statement, and not to the end of the line. * Don't overwrite test options when detecting range Now that multiple files share the same object again, we shouldn't be re-assigning to it. * Reuse already-read fixtures for AST_COMPARE=1 tests * Remove `run_file` global from test eslintrc * Undo package.json churn `yarn` reformatted it before, but the whitespace visually sets off the comment, so let's put it back how it was before. See https://github.com/prettier/prettier/pull/1659#discussion_r117864655 * Remove misleading comments from isSourceElement See https://github.com/prettier/prettier/pull/1659#discussion_r117865196 * Loop backwards through string instead of reversing it See https://github.com/prettier/prettier/pull/1659#discussion_r117865759 * Don't recompute indent string when formatting range See https://github.com/prettier/prettier/pull/1659#discussion_r117867268 * Rename findNodeByOffset to findNodeAtOffset "Find x by y" is the common usage for finding an `x` by a key `y`. However, since "by" has positional meaning, let's use "at" instead. See https://github.com/prettier/prettier/pull/1659#discussion_r117865121 * Always trimRight() in formatRange and explain why See https://github.com/prettier/prettier/pull/1659#discussion_r117864635 * Test formatting a range that crosses AST levels See https://github.com/prettier/prettier/pull/1659#issuecomment-303243688 * Fix formatting a range that crosses AST levels See https://github.com/prettier/prettier/pull/1659#issuecomment-303243688 * Remove unnecessary try-catch See https://github.com/prettier/prettier/pull/1659/files/e52db5e9f9ec4af599f658da03739e206dd4578c#r117878763 * Add test demonstrating range formatting indent detection * Detect alignment from text on line before range, but don't reformat it This avoids reformatting non-indentation that happens to precede the range on the same line, while still correctly indenting the range based on it. See https://github.com/prettier/prettier/pull/1659#discussion_r117881430
2017-05-23 17:43:58 +03:00
// Remove extra leading indentation as well as the added indentation after last newline
Add `--range-start` and `--range-end` options to format only parts of the input (#1609) * Add `--range-start` and `--range-end` options to format only parts of the input These options default to `0` and `Infinity`, respectively, so that the entire input is formatted by default. However, if either option is specified such that a node lies completely outside the resulting range, the node will be treated as if it has a `// prettier-ignore` comment. Related to https://github.com/prettier/prettier/pull/1577#issuecomment-300551179 Related to https://github.com/prettier/prettier/issues/1324 Related to https://github.com/prettier/prettier/issues/593 * printer: Extract hasPrettierIgnoreComment() helper * Move isOutsideRange() to util * Don't throw errors about comments outside range "not printing" * Remove unnecessary check from isOutsideRange() * Make --range-end exclusive This lets it use the conventional way of specifying ranges in strings. Note that if the rangeEnd in the tests is changed to 158, it will fail, but it wouldn't have failed before this change. * Change range formatting approach NOTE: This doesn't pass its test yet. Note that since we're reading the indentation from the first line, it is expected not to change. However, a semicolon is added, and the lines outside the range are not changed. The new approach is roughly: * Require that the range exactly covers an integer number of lines of the input * Detect the indentation of the line the range starts on * Format the range's substring using `printAstToDoc` * Add enough `indent`s to the doc to restore the detected indentation * Format the doc to a string with `printDocToString` * Prepend/append the original input before/after the range See https://github.com/prettier/prettier/pull/1609#issuecomment-301582273 --- Given `tests/range/range.js`, run the following: prettier tests/range/range.js --range-start 165 --range-end 246 See the range's text with: dd if=tests/range/range.js ibs=1 skip=165 count=81 2>/dev/null * Don't use default function parameters Node v4 doesn't support them. See http://node.green/#ES2015-syntax-default-function-parameters * Hackily fix indentation of range formatting See https://github.com/prettier/prettier/pull/1609#issuecomment-301625368 Also update the snapshot to reflect that the indentation actually should decrease by one space, since there were 13 spaces in the input and we round down after dividing by tabWidth. * Revert "printer: Extract hasPrettierIgnoreComment() helper" See https://github.com/prettier/prettier/pull/1609#discussion_r116804853 This reverts commit 62bf068ca98f69d4a7fd0ae188b3554d409eee8d. * Test automatically using the beginning of the rangeStart line and same for the end See https://github.com/prettier/prettier/pull/1609#issuecomment-301862076 * Fix automatically using the beginning of the rangeStart line and same for the end See https://github.com/prettier/prettier/pull/1609#issuecomment-301862076 * Propagate breaks after adding an indentation-triggering hardline See https://github.com/prettier/prettier/pull/1609/files/c1a61ebde8be73414c0a54bde3f323ac24295715#r116805581 * Extract getAlignmentSize(), use instead of countIndents() See https://github.com/prettier/prettier/pull/1609/files/c1a61ebde8be73414c0a54bde3f323ac24295715#r116804694 * Extract addAlignmentToDoc(), use instead of addIndentsToDoc() See https://github.com/prettier/prettier/pull/1609/files/c1a61ebde8be73414c0a54bde3f323ac24295715#r116804694 * Document that --range-start and --range-end include the entire line * Fix rangeStart calculation Before, it was incorrectly resulting in 1 when the originally provided value was 0 * Extract formatRange() helper function * Move getAlignmentSize() from printer to util This addresses https://github.com/prettier/prettier/pull/1609#discussion_r117636241 * Move addAlignmentToDoc() from printer to doc-builders This addresses https://github.com/prettier/prettier/pull/1609#discussion_r117636251
2017-05-21 20:14:13 +03:00
if (addAlignmentSize > 0) {
Find nearest node when formatting range (#1659) * Move range extension code into helper functions * Add findNodeByOffset() helper This was adapted from https://github.com/prettier/prettier/pull/1637/commits/cbc1929c64db558b4e444500bca3d2ce1d550359 * Test extending formatted range to entire node * Fix extending formatted range to entire node * Fix style errors * Add run_file test function This makes it possible to use different options on a per-file basis, which is useful for things like range formatting tests. * Test extending the format range to nearest parseable node This means you can select the range of a `catch` clause, attempt to format it, and have the `try` formatted as well, rather than throwing an error. * Fix extending the format range to nearest parseable node This means you can select the range of a `catch` clause, attempt to format it, and have the `try` formatted as well, rather than throwing an error. * Test that external indentation is left alone when formatting a range * Preserve external indentation when formatting a range * Dedupe range formatting traversal callbacks * Simplify range formatting traversal using ast-types See https://github.com/prettier/prettier/pull/1659#issuecomment-302974798 * Make range formatting traversal more efficient There's less unnecessary parsing now. * Fix style errors * Add test where range expanding fails * Fix test where range expanding fails This makes sure that the range contains the entirety of the nodes containing each of the range's endpoints. * Add test for expanding range to beginning of line * Pass test for expanding range to beginning of line This makes it so that indentation before the range is added to the formatted range. * Don't parse/stringify AST to detect pre-range indentation See https://github.com/prettier/prettier/pull/1659#discussion_r117790671 * When formatting a range, find closest statement rather than parsing The `isStatement` implementation came from `docs/prettier.min.js`. See https://github.com/prettier/prettier/pull/1659#issuecomment-303154770 * Add test for range-formatting a FunctionDeclaration's argument object * Include FunctionDeclaration when searching for nearest node to range-format From the spec, a Program is a series of SourceElements, each of which is either a Statement or a FunctionDeclaration. See https://www.ecma-international.org/ecma-262/5.1/#sec-A.5 * Remove unnecessary try-catch See https://github.com/prettier/prettier/pull/1659#discussion_r117810096 * Add tests with multiple statements See https://github.com/prettier/prettier/pull/1659#discussion_r117810753 * Remove unnecessary arguments from findNodeByOffset() * Contract format range to ensure it starts/ends on nodes * Specify test ranges in the fixtures See https://github.com/prettier/prettier/pull/1659#discussion_r117811186 * Remove unnecessary comments from range fixtures * Remove run_file test function It's no longer used. This essentially reverts 8241216e68f2e0da997a4f558b03658d642c89a2 * Update range formatting docs Clarify that the range expands to the nearest statement, and not to the end of the line. * Don't overwrite test options when detecting range Now that multiple files share the same object again, we shouldn't be re-assigning to it. * Reuse already-read fixtures for AST_COMPARE=1 tests * Remove `run_file` global from test eslintrc * Undo package.json churn `yarn` reformatted it before, but the whitespace visually sets off the comment, so let's put it back how it was before. See https://github.com/prettier/prettier/pull/1659#discussion_r117864655 * Remove misleading comments from isSourceElement See https://github.com/prettier/prettier/pull/1659#discussion_r117865196 * Loop backwards through string instead of reversing it See https://github.com/prettier/prettier/pull/1659#discussion_r117865759 * Don't recompute indent string when formatting range See https://github.com/prettier/prettier/pull/1659#discussion_r117867268 * Rename findNodeByOffset to findNodeAtOffset "Find x by y" is the common usage for finding an `x` by a key `y`. However, since "by" has positional meaning, let's use "at" instead. See https://github.com/prettier/prettier/pull/1659#discussion_r117865121 * Always trimRight() in formatRange and explain why See https://github.com/prettier/prettier/pull/1659#discussion_r117864635 * Test formatting a range that crosses AST levels See https://github.com/prettier/prettier/pull/1659#issuecomment-303243688 * Fix formatting a range that crosses AST levels See https://github.com/prettier/prettier/pull/1659#issuecomment-303243688 * Remove unnecessary try-catch See https://github.com/prettier/prettier/pull/1659/files/e52db5e9f9ec4af599f658da03739e206dd4578c#r117878763 * Add test demonstrating range formatting indent detection * Detect alignment from text on line before range, but don't reformat it This avoids reformatting non-indentation that happens to precede the range on the same line, while still correctly indenting the range based on it. See https://github.com/prettier/prettier/pull/1659#discussion_r117881430
2017-05-23 17:43:58 +03:00
return str.trim() + opts.newLine;
Add `--range-start` and `--range-end` options to format only parts of the input (#1609) * Add `--range-start` and `--range-end` options to format only parts of the input These options default to `0` and `Infinity`, respectively, so that the entire input is formatted by default. However, if either option is specified such that a node lies completely outside the resulting range, the node will be treated as if it has a `// prettier-ignore` comment. Related to https://github.com/prettier/prettier/pull/1577#issuecomment-300551179 Related to https://github.com/prettier/prettier/issues/1324 Related to https://github.com/prettier/prettier/issues/593 * printer: Extract hasPrettierIgnoreComment() helper * Move isOutsideRange() to util * Don't throw errors about comments outside range "not printing" * Remove unnecessary check from isOutsideRange() * Make --range-end exclusive This lets it use the conventional way of specifying ranges in strings. Note that if the rangeEnd in the tests is changed to 158, it will fail, but it wouldn't have failed before this change. * Change range formatting approach NOTE: This doesn't pass its test yet. Note that since we're reading the indentation from the first line, it is expected not to change. However, a semicolon is added, and the lines outside the range are not changed. The new approach is roughly: * Require that the range exactly covers an integer number of lines of the input * Detect the indentation of the line the range starts on * Format the range's substring using `printAstToDoc` * Add enough `indent`s to the doc to restore the detected indentation * Format the doc to a string with `printDocToString` * Prepend/append the original input before/after the range See https://github.com/prettier/prettier/pull/1609#issuecomment-301582273 --- Given `tests/range/range.js`, run the following: prettier tests/range/range.js --range-start 165 --range-end 246 See the range's text with: dd if=tests/range/range.js ibs=1 skip=165 count=81 2>/dev/null * Don't use default function parameters Node v4 doesn't support them. See http://node.green/#ES2015-syntax-default-function-parameters * Hackily fix indentation of range formatting See https://github.com/prettier/prettier/pull/1609#issuecomment-301625368 Also update the snapshot to reflect that the indentation actually should decrease by one space, since there were 13 spaces in the input and we round down after dividing by tabWidth. * Revert "printer: Extract hasPrettierIgnoreComment() helper" See https://github.com/prettier/prettier/pull/1609#discussion_r116804853 This reverts commit 62bf068ca98f69d4a7fd0ae188b3554d409eee8d. * Test automatically using the beginning of the rangeStart line and same for the end See https://github.com/prettier/prettier/pull/1609#issuecomment-301862076 * Fix automatically using the beginning of the rangeStart line and same for the end See https://github.com/prettier/prettier/pull/1609#issuecomment-301862076 * Propagate breaks after adding an indentation-triggering hardline See https://github.com/prettier/prettier/pull/1609/files/c1a61ebde8be73414c0a54bde3f323ac24295715#r116805581 * Extract getAlignmentSize(), use instead of countIndents() See https://github.com/prettier/prettier/pull/1609/files/c1a61ebde8be73414c0a54bde3f323ac24295715#r116804694 * Extract addAlignmentToDoc(), use instead of addIndentsToDoc() See https://github.com/prettier/prettier/pull/1609/files/c1a61ebde8be73414c0a54bde3f323ac24295715#r116804694 * Document that --range-start and --range-end include the entire line * Fix rangeStart calculation Before, it was incorrectly resulting in 1 when the originally provided value was 0 * Extract formatRange() helper function * Move getAlignmentSize() from printer to util This addresses https://github.com/prettier/prettier/pull/1609#discussion_r117636241 * Move addAlignmentToDoc() from printer to doc-builders This addresses https://github.com/prettier/prettier/pull/1609#discussion_r117636251
2017-05-21 20:14:13 +03:00
}
return str;
}
Find nearest node when formatting range (#1659) * Move range extension code into helper functions * Add findNodeByOffset() helper This was adapted from https://github.com/prettier/prettier/pull/1637/commits/cbc1929c64db558b4e444500bca3d2ce1d550359 * Test extending formatted range to entire node * Fix extending formatted range to entire node * Fix style errors * Add run_file test function This makes it possible to use different options on a per-file basis, which is useful for things like range formatting tests. * Test extending the format range to nearest parseable node This means you can select the range of a `catch` clause, attempt to format it, and have the `try` formatted as well, rather than throwing an error. * Fix extending the format range to nearest parseable node This means you can select the range of a `catch` clause, attempt to format it, and have the `try` formatted as well, rather than throwing an error. * Test that external indentation is left alone when formatting a range * Preserve external indentation when formatting a range * Dedupe range formatting traversal callbacks * Simplify range formatting traversal using ast-types See https://github.com/prettier/prettier/pull/1659#issuecomment-302974798 * Make range formatting traversal more efficient There's less unnecessary parsing now. * Fix style errors * Add test where range expanding fails * Fix test where range expanding fails This makes sure that the range contains the entirety of the nodes containing each of the range's endpoints. * Add test for expanding range to beginning of line * Pass test for expanding range to beginning of line This makes it so that indentation before the range is added to the formatted range. * Don't parse/stringify AST to detect pre-range indentation See https://github.com/prettier/prettier/pull/1659#discussion_r117790671 * When formatting a range, find closest statement rather than parsing The `isStatement` implementation came from `docs/prettier.min.js`. See https://github.com/prettier/prettier/pull/1659#issuecomment-303154770 * Add test for range-formatting a FunctionDeclaration's argument object * Include FunctionDeclaration when searching for nearest node to range-format From the spec, a Program is a series of SourceElements, each of which is either a Statement or a FunctionDeclaration. See https://www.ecma-international.org/ecma-262/5.1/#sec-A.5 * Remove unnecessary try-catch See https://github.com/prettier/prettier/pull/1659#discussion_r117810096 * Add tests with multiple statements See https://github.com/prettier/prettier/pull/1659#discussion_r117810753 * Remove unnecessary arguments from findNodeByOffset() * Contract format range to ensure it starts/ends on nodes * Specify test ranges in the fixtures See https://github.com/prettier/prettier/pull/1659#discussion_r117811186 * Remove unnecessary comments from range fixtures * Remove run_file test function It's no longer used. This essentially reverts 8241216e68f2e0da997a4f558b03658d642c89a2 * Update range formatting docs Clarify that the range expands to the nearest statement, and not to the end of the line. * Don't overwrite test options when detecting range Now that multiple files share the same object again, we shouldn't be re-assigning to it. * Reuse already-read fixtures for AST_COMPARE=1 tests * Remove `run_file` global from test eslintrc * Undo package.json churn `yarn` reformatted it before, but the whitespace visually sets off the comment, so let's put it back how it was before. See https://github.com/prettier/prettier/pull/1659#discussion_r117864655 * Remove misleading comments from isSourceElement See https://github.com/prettier/prettier/pull/1659#discussion_r117865196 * Loop backwards through string instead of reversing it See https://github.com/prettier/prettier/pull/1659#discussion_r117865759 * Don't recompute indent string when formatting range See https://github.com/prettier/prettier/pull/1659#discussion_r117867268 * Rename findNodeByOffset to findNodeAtOffset "Find x by y" is the common usage for finding an `x` by a key `y`. However, since "by" has positional meaning, let's use "at" instead. See https://github.com/prettier/prettier/pull/1659#discussion_r117865121 * Always trimRight() in formatRange and explain why See https://github.com/prettier/prettier/pull/1659#discussion_r117864635 * Test formatting a range that crosses AST levels See https://github.com/prettier/prettier/pull/1659#issuecomment-303243688 * Fix formatting a range that crosses AST levels See https://github.com/prettier/prettier/pull/1659#issuecomment-303243688 * Remove unnecessary try-catch See https://github.com/prettier/prettier/pull/1659/files/e52db5e9f9ec4af599f658da03739e206dd4578c#r117878763 * Add test demonstrating range formatting indent detection * Detect alignment from text on line before range, but don't reformat it This avoids reformatting non-indentation that happens to precede the range on the same line, while still correctly indenting the range based on it. See https://github.com/prettier/prettier/pull/1659#discussion_r117881430
2017-05-23 17:43:58 +03:00
function findSiblingAncestors(startNodeAndParents, endNodeAndParents) {
let resultStartNode = startNodeAndParents.node;
let resultEndNode = endNodeAndParents.node;
for (const endParent of endNodeAndParents.parentNodes) {
if (util.locStart(endParent) >= util.locStart(startNodeAndParents.node)) {
resultEndNode = endParent;
} else {
break;
}
}
for (const startParent of startNodeAndParents.parentNodes) {
if (util.locEnd(startParent) <= util.locEnd(endNodeAndParents.node)) {
resultStartNode = startParent;
} else {
break;
}
}
return {
startNode: resultStartNode,
endNode: resultEndNode
};
}
function findNodeAtOffset(node, offset, parentNodes) {
parentNodes = parentNodes || [];
const start = util.locStart(node);
const end = util.locEnd(node);
if (start <= offset && offset <= end) {
for (const childNode of comments.getSortedChildNodes(node)) {
const childResult = findNodeAtOffset(
childNode,
offset,
[node].concat(parentNodes)
);
if (childResult) {
return childResult;
}
}
if (isSourceElement(node)) {
return {
node: node,
parentNodes: parentNodes
};
}
}
}
// See https://www.ecma-international.org/ecma-262/5.1/#sec-A.5
function isSourceElement(node) {
if (node == null) {
return false;
}
switch (node.type) {
case "FunctionDeclaration":
case "BlockStatement":
case "BreakStatement":
case "ContinueStatement":
case "DebuggerStatement":
case "DoWhileStatement":
case "EmptyStatement":
case "ExpressionStatement":
case "ForInStatement":
case "ForStatement":
case "IfStatement":
case "LabeledStatement":
case "ReturnStatement":
case "SwitchStatement":
case "ThrowStatement":
case "TryStatement":
case "VariableDeclaration":
case "WhileStatement":
case "WithStatement":
return true;
}
return false;
}
function calculateRange(text, opts, ast) {
// Contract the range so that it has non-whitespace characters at its endpoints.
// This ensures we can format a range that doesn't end on a node.
const rangeStringOrig = text.slice(opts.rangeStart, opts.rangeEnd);
const startNonWhitespace = Math.max(
opts.rangeStart + rangeStringOrig.search(/\S/),
opts.rangeStart
Add `--range-start` and `--range-end` options to format only parts of the input (#1609) * Add `--range-start` and `--range-end` options to format only parts of the input These options default to `0` and `Infinity`, respectively, so that the entire input is formatted by default. However, if either option is specified such that a node lies completely outside the resulting range, the node will be treated as if it has a `// prettier-ignore` comment. Related to https://github.com/prettier/prettier/pull/1577#issuecomment-300551179 Related to https://github.com/prettier/prettier/issues/1324 Related to https://github.com/prettier/prettier/issues/593 * printer: Extract hasPrettierIgnoreComment() helper * Move isOutsideRange() to util * Don't throw errors about comments outside range "not printing" * Remove unnecessary check from isOutsideRange() * Make --range-end exclusive This lets it use the conventional way of specifying ranges in strings. Note that if the rangeEnd in the tests is changed to 158, it will fail, but it wouldn't have failed before this change. * Change range formatting approach NOTE: This doesn't pass its test yet. Note that since we're reading the indentation from the first line, it is expected not to change. However, a semicolon is added, and the lines outside the range are not changed. The new approach is roughly: * Require that the range exactly covers an integer number of lines of the input * Detect the indentation of the line the range starts on * Format the range's substring using `printAstToDoc` * Add enough `indent`s to the doc to restore the detected indentation * Format the doc to a string with `printDocToString` * Prepend/append the original input before/after the range See https://github.com/prettier/prettier/pull/1609#issuecomment-301582273 --- Given `tests/range/range.js`, run the following: prettier tests/range/range.js --range-start 165 --range-end 246 See the range's text with: dd if=tests/range/range.js ibs=1 skip=165 count=81 2>/dev/null * Don't use default function parameters Node v4 doesn't support them. See http://node.green/#ES2015-syntax-default-function-parameters * Hackily fix indentation of range formatting See https://github.com/prettier/prettier/pull/1609#issuecomment-301625368 Also update the snapshot to reflect that the indentation actually should decrease by one space, since there were 13 spaces in the input and we round down after dividing by tabWidth. * Revert "printer: Extract hasPrettierIgnoreComment() helper" See https://github.com/prettier/prettier/pull/1609#discussion_r116804853 This reverts commit 62bf068ca98f69d4a7fd0ae188b3554d409eee8d. * Test automatically using the beginning of the rangeStart line and same for the end See https://github.com/prettier/prettier/pull/1609#issuecomment-301862076 * Fix automatically using the beginning of the rangeStart line and same for the end See https://github.com/prettier/prettier/pull/1609#issuecomment-301862076 * Propagate breaks after adding an indentation-triggering hardline See https://github.com/prettier/prettier/pull/1609/files/c1a61ebde8be73414c0a54bde3f323ac24295715#r116805581 * Extract getAlignmentSize(), use instead of countIndents() See https://github.com/prettier/prettier/pull/1609/files/c1a61ebde8be73414c0a54bde3f323ac24295715#r116804694 * Extract addAlignmentToDoc(), use instead of addIndentsToDoc() See https://github.com/prettier/prettier/pull/1609/files/c1a61ebde8be73414c0a54bde3f323ac24295715#r116804694 * Document that --range-start and --range-end include the entire line * Fix rangeStart calculation Before, it was incorrectly resulting in 1 when the originally provided value was 0 * Extract formatRange() helper function * Move getAlignmentSize() from printer to util This addresses https://github.com/prettier/prettier/pull/1609#discussion_r117636241 * Move addAlignmentToDoc() from printer to doc-builders This addresses https://github.com/prettier/prettier/pull/1609#discussion_r117636251
2017-05-21 20:14:13 +03:00
);
Find nearest node when formatting range (#1659) * Move range extension code into helper functions * Add findNodeByOffset() helper This was adapted from https://github.com/prettier/prettier/pull/1637/commits/cbc1929c64db558b4e444500bca3d2ce1d550359 * Test extending formatted range to entire node * Fix extending formatted range to entire node * Fix style errors * Add run_file test function This makes it possible to use different options on a per-file basis, which is useful for things like range formatting tests. * Test extending the format range to nearest parseable node This means you can select the range of a `catch` clause, attempt to format it, and have the `try` formatted as well, rather than throwing an error. * Fix extending the format range to nearest parseable node This means you can select the range of a `catch` clause, attempt to format it, and have the `try` formatted as well, rather than throwing an error. * Test that external indentation is left alone when formatting a range * Preserve external indentation when formatting a range * Dedupe range formatting traversal callbacks * Simplify range formatting traversal using ast-types See https://github.com/prettier/prettier/pull/1659#issuecomment-302974798 * Make range formatting traversal more efficient There's less unnecessary parsing now. * Fix style errors * Add test where range expanding fails * Fix test where range expanding fails This makes sure that the range contains the entirety of the nodes containing each of the range's endpoints. * Add test for expanding range to beginning of line * Pass test for expanding range to beginning of line This makes it so that indentation before the range is added to the formatted range. * Don't parse/stringify AST to detect pre-range indentation See https://github.com/prettier/prettier/pull/1659#discussion_r117790671 * When formatting a range, find closest statement rather than parsing The `isStatement` implementation came from `docs/prettier.min.js`. See https://github.com/prettier/prettier/pull/1659#issuecomment-303154770 * Add test for range-formatting a FunctionDeclaration's argument object * Include FunctionDeclaration when searching for nearest node to range-format From the spec, a Program is a series of SourceElements, each of which is either a Statement or a FunctionDeclaration. See https://www.ecma-international.org/ecma-262/5.1/#sec-A.5 * Remove unnecessary try-catch See https://github.com/prettier/prettier/pull/1659#discussion_r117810096 * Add tests with multiple statements See https://github.com/prettier/prettier/pull/1659#discussion_r117810753 * Remove unnecessary arguments from findNodeByOffset() * Contract format range to ensure it starts/ends on nodes * Specify test ranges in the fixtures See https://github.com/prettier/prettier/pull/1659#discussion_r117811186 * Remove unnecessary comments from range fixtures * Remove run_file test function It's no longer used. This essentially reverts 8241216e68f2e0da997a4f558b03658d642c89a2 * Update range formatting docs Clarify that the range expands to the nearest statement, and not to the end of the line. * Don't overwrite test options when detecting range Now that multiple files share the same object again, we shouldn't be re-assigning to it. * Reuse already-read fixtures for AST_COMPARE=1 tests * Remove `run_file` global from test eslintrc * Undo package.json churn `yarn` reformatted it before, but the whitespace visually sets off the comment, so let's put it back how it was before. See https://github.com/prettier/prettier/pull/1659#discussion_r117864655 * Remove misleading comments from isSourceElement See https://github.com/prettier/prettier/pull/1659#discussion_r117865196 * Loop backwards through string instead of reversing it See https://github.com/prettier/prettier/pull/1659#discussion_r117865759 * Don't recompute indent string when formatting range See https://github.com/prettier/prettier/pull/1659#discussion_r117867268 * Rename findNodeByOffset to findNodeAtOffset "Find x by y" is the common usage for finding an `x` by a key `y`. However, since "by" has positional meaning, let's use "at" instead. See https://github.com/prettier/prettier/pull/1659#discussion_r117865121 * Always trimRight() in formatRange and explain why See https://github.com/prettier/prettier/pull/1659#discussion_r117864635 * Test formatting a range that crosses AST levels See https://github.com/prettier/prettier/pull/1659#issuecomment-303243688 * Fix formatting a range that crosses AST levels See https://github.com/prettier/prettier/pull/1659#issuecomment-303243688 * Remove unnecessary try-catch See https://github.com/prettier/prettier/pull/1659/files/e52db5e9f9ec4af599f658da03739e206dd4578c#r117878763 * Add test demonstrating range formatting indent detection * Detect alignment from text on line before range, but don't reformat it This avoids reformatting non-indentation that happens to precede the range on the same line, while still correctly indenting the range based on it. See https://github.com/prettier/prettier/pull/1659#discussion_r117881430
2017-05-23 17:43:58 +03:00
let endNonWhitespace;
for (
endNonWhitespace = opts.rangeEnd;
endNonWhitespace > opts.rangeStart;
--endNonWhitespace
) {
if (text[endNonWhitespace - 1].match(/\S/)) {
break;
}
}
const startNodeAndParents = findNodeAtOffset(ast, startNonWhitespace);
const endNodeAndParents = findNodeAtOffset(ast, endNonWhitespace);
const siblingAncestors = findSiblingAncestors(
startNodeAndParents,
endNodeAndParents
);
const startNode = siblingAncestors.startNode;
const endNode = siblingAncestors.endNode;
const rangeStart = Math.min(util.locStart(startNode), util.locStart(endNode));
const rangeEnd = Math.max(util.locEnd(startNode), util.locEnd(endNode));
return {
rangeStart: rangeStart,
rangeEnd: rangeEnd
};
}
function formatRange(text, opts, ast) {
if (0 < opts.rangeStart || opts.rangeEnd < text.length) {
const range = calculateRange(text, opts, ast);
const rangeStart = range.rangeStart;
const rangeEnd = range.rangeEnd;
const rangeString = text.slice(rangeStart, rangeEnd);
// Try to extend the range backwards to the beginning of the line.
// This is so we can detect indentation correctly and restore it.
// Use `Math.min` since `lastIndexOf` returns 0 when `rangeStart` is 0
const rangeStart2 = Math.min(
rangeStart,
text.lastIndexOf("\n", rangeStart) + 1
Add `--range-start` and `--range-end` options to format only parts of the input (#1609) * Add `--range-start` and `--range-end` options to format only parts of the input These options default to `0` and `Infinity`, respectively, so that the entire input is formatted by default. However, if either option is specified such that a node lies completely outside the resulting range, the node will be treated as if it has a `// prettier-ignore` comment. Related to https://github.com/prettier/prettier/pull/1577#issuecomment-300551179 Related to https://github.com/prettier/prettier/issues/1324 Related to https://github.com/prettier/prettier/issues/593 * printer: Extract hasPrettierIgnoreComment() helper * Move isOutsideRange() to util * Don't throw errors about comments outside range "not printing" * Remove unnecessary check from isOutsideRange() * Make --range-end exclusive This lets it use the conventional way of specifying ranges in strings. Note that if the rangeEnd in the tests is changed to 158, it will fail, but it wouldn't have failed before this change. * Change range formatting approach NOTE: This doesn't pass its test yet. Note that since we're reading the indentation from the first line, it is expected not to change. However, a semicolon is added, and the lines outside the range are not changed. The new approach is roughly: * Require that the range exactly covers an integer number of lines of the input * Detect the indentation of the line the range starts on * Format the range's substring using `printAstToDoc` * Add enough `indent`s to the doc to restore the detected indentation * Format the doc to a string with `printDocToString` * Prepend/append the original input before/after the range See https://github.com/prettier/prettier/pull/1609#issuecomment-301582273 --- Given `tests/range/range.js`, run the following: prettier tests/range/range.js --range-start 165 --range-end 246 See the range's text with: dd if=tests/range/range.js ibs=1 skip=165 count=81 2>/dev/null * Don't use default function parameters Node v4 doesn't support them. See http://node.green/#ES2015-syntax-default-function-parameters * Hackily fix indentation of range formatting See https://github.com/prettier/prettier/pull/1609#issuecomment-301625368 Also update the snapshot to reflect that the indentation actually should decrease by one space, since there were 13 spaces in the input and we round down after dividing by tabWidth. * Revert "printer: Extract hasPrettierIgnoreComment() helper" See https://github.com/prettier/prettier/pull/1609#discussion_r116804853 This reverts commit 62bf068ca98f69d4a7fd0ae188b3554d409eee8d. * Test automatically using the beginning of the rangeStart line and same for the end See https://github.com/prettier/prettier/pull/1609#issuecomment-301862076 * Fix automatically using the beginning of the rangeStart line and same for the end See https://github.com/prettier/prettier/pull/1609#issuecomment-301862076 * Propagate breaks after adding an indentation-triggering hardline See https://github.com/prettier/prettier/pull/1609/files/c1a61ebde8be73414c0a54bde3f323ac24295715#r116805581 * Extract getAlignmentSize(), use instead of countIndents() See https://github.com/prettier/prettier/pull/1609/files/c1a61ebde8be73414c0a54bde3f323ac24295715#r116804694 * Extract addAlignmentToDoc(), use instead of addIndentsToDoc() See https://github.com/prettier/prettier/pull/1609/files/c1a61ebde8be73414c0a54bde3f323ac24295715#r116804694 * Document that --range-start and --range-end include the entire line * Fix rangeStart calculation Before, it was incorrectly resulting in 1 when the originally provided value was 0 * Extract formatRange() helper function * Move getAlignmentSize() from printer to util This addresses https://github.com/prettier/prettier/pull/1609#discussion_r117636241 * Move addAlignmentToDoc() from printer to doc-builders This addresses https://github.com/prettier/prettier/pull/1609#discussion_r117636251
2017-05-21 20:14:13 +03:00
);
Find nearest node when formatting range (#1659) * Move range extension code into helper functions * Add findNodeByOffset() helper This was adapted from https://github.com/prettier/prettier/pull/1637/commits/cbc1929c64db558b4e444500bca3d2ce1d550359 * Test extending formatted range to entire node * Fix extending formatted range to entire node * Fix style errors * Add run_file test function This makes it possible to use different options on a per-file basis, which is useful for things like range formatting tests. * Test extending the format range to nearest parseable node This means you can select the range of a `catch` clause, attempt to format it, and have the `try` formatted as well, rather than throwing an error. * Fix extending the format range to nearest parseable node This means you can select the range of a `catch` clause, attempt to format it, and have the `try` formatted as well, rather than throwing an error. * Test that external indentation is left alone when formatting a range * Preserve external indentation when formatting a range * Dedupe range formatting traversal callbacks * Simplify range formatting traversal using ast-types See https://github.com/prettier/prettier/pull/1659#issuecomment-302974798 * Make range formatting traversal more efficient There's less unnecessary parsing now. * Fix style errors * Add test where range expanding fails * Fix test where range expanding fails This makes sure that the range contains the entirety of the nodes containing each of the range's endpoints. * Add test for expanding range to beginning of line * Pass test for expanding range to beginning of line This makes it so that indentation before the range is added to the formatted range. * Don't parse/stringify AST to detect pre-range indentation See https://github.com/prettier/prettier/pull/1659#discussion_r117790671 * When formatting a range, find closest statement rather than parsing The `isStatement` implementation came from `docs/prettier.min.js`. See https://github.com/prettier/prettier/pull/1659#issuecomment-303154770 * Add test for range-formatting a FunctionDeclaration's argument object * Include FunctionDeclaration when searching for nearest node to range-format From the spec, a Program is a series of SourceElements, each of which is either a Statement or a FunctionDeclaration. See https://www.ecma-international.org/ecma-262/5.1/#sec-A.5 * Remove unnecessary try-catch See https://github.com/prettier/prettier/pull/1659#discussion_r117810096 * Add tests with multiple statements See https://github.com/prettier/prettier/pull/1659#discussion_r117810753 * Remove unnecessary arguments from findNodeByOffset() * Contract format range to ensure it starts/ends on nodes * Specify test ranges in the fixtures See https://github.com/prettier/prettier/pull/1659#discussion_r117811186 * Remove unnecessary comments from range fixtures * Remove run_file test function It's no longer used. This essentially reverts 8241216e68f2e0da997a4f558b03658d642c89a2 * Update range formatting docs Clarify that the range expands to the nearest statement, and not to the end of the line. * Don't overwrite test options when detecting range Now that multiple files share the same object again, we shouldn't be re-assigning to it. * Reuse already-read fixtures for AST_COMPARE=1 tests * Remove `run_file` global from test eslintrc * Undo package.json churn `yarn` reformatted it before, but the whitespace visually sets off the comment, so let's put it back how it was before. See https://github.com/prettier/prettier/pull/1659#discussion_r117864655 * Remove misleading comments from isSourceElement See https://github.com/prettier/prettier/pull/1659#discussion_r117865196 * Loop backwards through string instead of reversing it See https://github.com/prettier/prettier/pull/1659#discussion_r117865759 * Don't recompute indent string when formatting range See https://github.com/prettier/prettier/pull/1659#discussion_r117867268 * Rename findNodeByOffset to findNodeAtOffset "Find x by y" is the common usage for finding an `x` by a key `y`. However, since "by" has positional meaning, let's use "at" instead. See https://github.com/prettier/prettier/pull/1659#discussion_r117865121 * Always trimRight() in formatRange and explain why See https://github.com/prettier/prettier/pull/1659#discussion_r117864635 * Test formatting a range that crosses AST levels See https://github.com/prettier/prettier/pull/1659#issuecomment-303243688 * Fix formatting a range that crosses AST levels See https://github.com/prettier/prettier/pull/1659#issuecomment-303243688 * Remove unnecessary try-catch See https://github.com/prettier/prettier/pull/1659/files/e52db5e9f9ec4af599f658da03739e206dd4578c#r117878763 * Add test demonstrating range formatting indent detection * Detect alignment from text on line before range, but don't reformat it This avoids reformatting non-indentation that happens to precede the range on the same line, while still correctly indenting the range based on it. See https://github.com/prettier/prettier/pull/1659#discussion_r117881430
2017-05-23 17:43:58 +03:00
const indentString = text.slice(rangeStart2, rangeStart);
const alignmentSize = util.getAlignmentSize(indentString, opts.tabWidth);
Add `--range-start` and `--range-end` options to format only parts of the input (#1609) * Add `--range-start` and `--range-end` options to format only parts of the input These options default to `0` and `Infinity`, respectively, so that the entire input is formatted by default. However, if either option is specified such that a node lies completely outside the resulting range, the node will be treated as if it has a `// prettier-ignore` comment. Related to https://github.com/prettier/prettier/pull/1577#issuecomment-300551179 Related to https://github.com/prettier/prettier/issues/1324 Related to https://github.com/prettier/prettier/issues/593 * printer: Extract hasPrettierIgnoreComment() helper * Move isOutsideRange() to util * Don't throw errors about comments outside range "not printing" * Remove unnecessary check from isOutsideRange() * Make --range-end exclusive This lets it use the conventional way of specifying ranges in strings. Note that if the rangeEnd in the tests is changed to 158, it will fail, but it wouldn't have failed before this change. * Change range formatting approach NOTE: This doesn't pass its test yet. Note that since we're reading the indentation from the first line, it is expected not to change. However, a semicolon is added, and the lines outside the range are not changed. The new approach is roughly: * Require that the range exactly covers an integer number of lines of the input * Detect the indentation of the line the range starts on * Format the range's substring using `printAstToDoc` * Add enough `indent`s to the doc to restore the detected indentation * Format the doc to a string with `printDocToString` * Prepend/append the original input before/after the range See https://github.com/prettier/prettier/pull/1609#issuecomment-301582273 --- Given `tests/range/range.js`, run the following: prettier tests/range/range.js --range-start 165 --range-end 246 See the range's text with: dd if=tests/range/range.js ibs=1 skip=165 count=81 2>/dev/null * Don't use default function parameters Node v4 doesn't support them. See http://node.green/#ES2015-syntax-default-function-parameters * Hackily fix indentation of range formatting See https://github.com/prettier/prettier/pull/1609#issuecomment-301625368 Also update the snapshot to reflect that the indentation actually should decrease by one space, since there were 13 spaces in the input and we round down after dividing by tabWidth. * Revert "printer: Extract hasPrettierIgnoreComment() helper" See https://github.com/prettier/prettier/pull/1609#discussion_r116804853 This reverts commit 62bf068ca98f69d4a7fd0ae188b3554d409eee8d. * Test automatically using the beginning of the rangeStart line and same for the end See https://github.com/prettier/prettier/pull/1609#issuecomment-301862076 * Fix automatically using the beginning of the rangeStart line and same for the end See https://github.com/prettier/prettier/pull/1609#issuecomment-301862076 * Propagate breaks after adding an indentation-triggering hardline See https://github.com/prettier/prettier/pull/1609/files/c1a61ebde8be73414c0a54bde3f323ac24295715#r116805581 * Extract getAlignmentSize(), use instead of countIndents() See https://github.com/prettier/prettier/pull/1609/files/c1a61ebde8be73414c0a54bde3f323ac24295715#r116804694 * Extract addAlignmentToDoc(), use instead of addIndentsToDoc() See https://github.com/prettier/prettier/pull/1609/files/c1a61ebde8be73414c0a54bde3f323ac24295715#r116804694 * Document that --range-start and --range-end include the entire line * Fix rangeStart calculation Before, it was incorrectly resulting in 1 when the originally provided value was 0 * Extract formatRange() helper function * Move getAlignmentSize() from printer to util This addresses https://github.com/prettier/prettier/pull/1609#discussion_r117636241 * Move addAlignmentToDoc() from printer to doc-builders This addresses https://github.com/prettier/prettier/pull/1609#discussion_r117636251
2017-05-21 20:14:13 +03:00
const rangeFormatted = format(
rangeString,
Object.assign({}, opts, {
rangeStart: 0,
rangeEnd: Infinity,
printWidth: opts.printWidth - alignmentSize
}),
alignmentSize
);
Find nearest node when formatting range (#1659) * Move range extension code into helper functions * Add findNodeByOffset() helper This was adapted from https://github.com/prettier/prettier/pull/1637/commits/cbc1929c64db558b4e444500bca3d2ce1d550359 * Test extending formatted range to entire node * Fix extending formatted range to entire node * Fix style errors * Add run_file test function This makes it possible to use different options on a per-file basis, which is useful for things like range formatting tests. * Test extending the format range to nearest parseable node This means you can select the range of a `catch` clause, attempt to format it, and have the `try` formatted as well, rather than throwing an error. * Fix extending the format range to nearest parseable node This means you can select the range of a `catch` clause, attempt to format it, and have the `try` formatted as well, rather than throwing an error. * Test that external indentation is left alone when formatting a range * Preserve external indentation when formatting a range * Dedupe range formatting traversal callbacks * Simplify range formatting traversal using ast-types See https://github.com/prettier/prettier/pull/1659#issuecomment-302974798 * Make range formatting traversal more efficient There's less unnecessary parsing now. * Fix style errors * Add test where range expanding fails * Fix test where range expanding fails This makes sure that the range contains the entirety of the nodes containing each of the range's endpoints. * Add test for expanding range to beginning of line * Pass test for expanding range to beginning of line This makes it so that indentation before the range is added to the formatted range. * Don't parse/stringify AST to detect pre-range indentation See https://github.com/prettier/prettier/pull/1659#discussion_r117790671 * When formatting a range, find closest statement rather than parsing The `isStatement` implementation came from `docs/prettier.min.js`. See https://github.com/prettier/prettier/pull/1659#issuecomment-303154770 * Add test for range-formatting a FunctionDeclaration's argument object * Include FunctionDeclaration when searching for nearest node to range-format From the spec, a Program is a series of SourceElements, each of which is either a Statement or a FunctionDeclaration. See https://www.ecma-international.org/ecma-262/5.1/#sec-A.5 * Remove unnecessary try-catch See https://github.com/prettier/prettier/pull/1659#discussion_r117810096 * Add tests with multiple statements See https://github.com/prettier/prettier/pull/1659#discussion_r117810753 * Remove unnecessary arguments from findNodeByOffset() * Contract format range to ensure it starts/ends on nodes * Specify test ranges in the fixtures See https://github.com/prettier/prettier/pull/1659#discussion_r117811186 * Remove unnecessary comments from range fixtures * Remove run_file test function It's no longer used. This essentially reverts 8241216e68f2e0da997a4f558b03658d642c89a2 * Update range formatting docs Clarify that the range expands to the nearest statement, and not to the end of the line. * Don't overwrite test options when detecting range Now that multiple files share the same object again, we shouldn't be re-assigning to it. * Reuse already-read fixtures for AST_COMPARE=1 tests * Remove `run_file` global from test eslintrc * Undo package.json churn `yarn` reformatted it before, but the whitespace visually sets off the comment, so let's put it back how it was before. See https://github.com/prettier/prettier/pull/1659#discussion_r117864655 * Remove misleading comments from isSourceElement See https://github.com/prettier/prettier/pull/1659#discussion_r117865196 * Loop backwards through string instead of reversing it See https://github.com/prettier/prettier/pull/1659#discussion_r117865759 * Don't recompute indent string when formatting range See https://github.com/prettier/prettier/pull/1659#discussion_r117867268 * Rename findNodeByOffset to findNodeAtOffset "Find x by y" is the common usage for finding an `x` by a key `y`. However, since "by" has positional meaning, let's use "at" instead. See https://github.com/prettier/prettier/pull/1659#discussion_r117865121 * Always trimRight() in formatRange and explain why See https://github.com/prettier/prettier/pull/1659#discussion_r117864635 * Test formatting a range that crosses AST levels See https://github.com/prettier/prettier/pull/1659#issuecomment-303243688 * Fix formatting a range that crosses AST levels See https://github.com/prettier/prettier/pull/1659#issuecomment-303243688 * Remove unnecessary try-catch See https://github.com/prettier/prettier/pull/1659/files/e52db5e9f9ec4af599f658da03739e206dd4578c#r117878763 * Add test demonstrating range formatting indent detection * Detect alignment from text on line before range, but don't reformat it This avoids reformatting non-indentation that happens to precede the range on the same line, while still correctly indenting the range based on it. See https://github.com/prettier/prettier/pull/1659#discussion_r117881430
2017-05-23 17:43:58 +03:00
// Since the range contracts to avoid trailing whitespace,
// we need to remove the newline that was inserted by the `format` call.
const rangeTrimmed = rangeFormatted.trimRight();
return text.slice(0, rangeStart) + rangeTrimmed + text.slice(rangeEnd);
Add `--range-start` and `--range-end` options to format only parts of the input (#1609) * Add `--range-start` and `--range-end` options to format only parts of the input These options default to `0` and `Infinity`, respectively, so that the entire input is formatted by default. However, if either option is specified such that a node lies completely outside the resulting range, the node will be treated as if it has a `// prettier-ignore` comment. Related to https://github.com/prettier/prettier/pull/1577#issuecomment-300551179 Related to https://github.com/prettier/prettier/issues/1324 Related to https://github.com/prettier/prettier/issues/593 * printer: Extract hasPrettierIgnoreComment() helper * Move isOutsideRange() to util * Don't throw errors about comments outside range "not printing" * Remove unnecessary check from isOutsideRange() * Make --range-end exclusive This lets it use the conventional way of specifying ranges in strings. Note that if the rangeEnd in the tests is changed to 158, it will fail, but it wouldn't have failed before this change. * Change range formatting approach NOTE: This doesn't pass its test yet. Note that since we're reading the indentation from the first line, it is expected not to change. However, a semicolon is added, and the lines outside the range are not changed. The new approach is roughly: * Require that the range exactly covers an integer number of lines of the input * Detect the indentation of the line the range starts on * Format the range's substring using `printAstToDoc` * Add enough `indent`s to the doc to restore the detected indentation * Format the doc to a string with `printDocToString` * Prepend/append the original input before/after the range See https://github.com/prettier/prettier/pull/1609#issuecomment-301582273 --- Given `tests/range/range.js`, run the following: prettier tests/range/range.js --range-start 165 --range-end 246 See the range's text with: dd if=tests/range/range.js ibs=1 skip=165 count=81 2>/dev/null * Don't use default function parameters Node v4 doesn't support them. See http://node.green/#ES2015-syntax-default-function-parameters * Hackily fix indentation of range formatting See https://github.com/prettier/prettier/pull/1609#issuecomment-301625368 Also update the snapshot to reflect that the indentation actually should decrease by one space, since there were 13 spaces in the input and we round down after dividing by tabWidth. * Revert "printer: Extract hasPrettierIgnoreComment() helper" See https://github.com/prettier/prettier/pull/1609#discussion_r116804853 This reverts commit 62bf068ca98f69d4a7fd0ae188b3554d409eee8d. * Test automatically using the beginning of the rangeStart line and same for the end See https://github.com/prettier/prettier/pull/1609#issuecomment-301862076 * Fix automatically using the beginning of the rangeStart line and same for the end See https://github.com/prettier/prettier/pull/1609#issuecomment-301862076 * Propagate breaks after adding an indentation-triggering hardline See https://github.com/prettier/prettier/pull/1609/files/c1a61ebde8be73414c0a54bde3f323ac24295715#r116805581 * Extract getAlignmentSize(), use instead of countIndents() See https://github.com/prettier/prettier/pull/1609/files/c1a61ebde8be73414c0a54bde3f323ac24295715#r116804694 * Extract addAlignmentToDoc(), use instead of addIndentsToDoc() See https://github.com/prettier/prettier/pull/1609/files/c1a61ebde8be73414c0a54bde3f323ac24295715#r116804694 * Document that --range-start and --range-end include the entire line * Fix rangeStart calculation Before, it was incorrectly resulting in 1 when the originally provided value was 0 * Extract formatRange() helper function * Move getAlignmentSize() from printer to util This addresses https://github.com/prettier/prettier/pull/1609#discussion_r117636241 * Move addAlignmentToDoc() from printer to doc-builders This addresses https://github.com/prettier/prettier/pull/1609#discussion_r117636251
2017-05-21 20:14:13 +03:00
}
}
function formatWithShebang(text, opts) {
if (!text.startsWith("#!")) {
return format(text, opts);
}
const index = text.indexOf("\n");
const shebang = text.slice(0, index + 1);
const nextChar = text.charAt(index + 1);
2017-01-28 18:50:22 +03:00
const newLine = nextChar === "\n" ? "\n" : nextChar === "\r" ? "\r\n" : "";
return shebang + newLine + format(text, opts);
}
module.exports = {
format: function(text, opts) {
return formatWithShebang(text, normalizeOptions(opts));
},
check: function(text, opts) {
try {
const formatted = formatWithShebang(text, normalizeOptions(opts));
return formatted === text;
} catch (e) {
return false;
}
},
version: version,
__debug: {
parse: function(text, opts) {
Run AST comparison tests on Travis (#1553) * Run AST comparison tests on Travis It looks like some of these currently fail, so we should probably also sort that out. Inspired by https://github.com/prettier/prettier/issues/1552 * tests: Use specified parser when AST_COMPARE=1 This fixes some of the tests with AST_COMPARE=1 * Move cleanAST() into prettier.__debug This makes it available for tests to use. * AST_COMPARE=1 uses cleanAst() instead of removeEmptyStatements() Ths fixes some of the tests with AST_COMPARE=1 * Export parse() from src/parser.js This makes it available for tests to use. * tests: Use specified parser more when AST_COMPARE=1 This is a continuation of commit 86437a66d326919897fe89891a25824870f5bb79 This fixes some of the tests with AST_COMPARE=1 * massageAST: remove leadingComments/trailingComments This fixes some of the tests with AST_COMPARE=1 * massageAST: remove `extra` This fixes some of the tests with AST_COMPARE=1 * tests_config/run_spec.js: Rename variables for clarity * AST_COMPARE=1 tests compare unstringified objects This makes the test error output shorter. * fixup! Export parse() from src/parser.js * Revert "Run AST comparison tests on Travis" See https://github.com/prettier/prettier/pull/1553#issuecomment-300027747 This reverts commit 49873a956c532f23fd216551a35ae35c1a18407e. * fixup! fixup! Export parse() from src/parser.js * parser: Require babel-code-frame only when needed This addresses: * https://github.com/prettier/prettier/pull/1553#discussion_r115386253 * https://github.com/prettier/prettier/pull/1553#discussion_r115386250 * parser: Don't export now-unused parseWith* functions Addresses https://github.com/prettier/prettier/pull/1553#discussion_r115386964 * Move cleanAST/massageAST into own file, don't export This addresses: * https://github.com/prettier/prettier/pull/1553#discussion_r115386993 * https://github.com/prettier/prettier/pull/1553#discussion_r115386611 * Don't destructure require() result (Node v4 compat.) * Fix copy/paste error
2017-05-09 04:16:35 +03:00
return parser.parse(text, opts);
},
formatAST: function(ast, opts) {
opts = normalizeOptions(opts);
const doc = printAstToDoc(ast, opts);
const str = printDocToString(doc, opts);
return str;
},
// Doesn't handle shebang for now
formatDoc: function(doc, opts) {
opts = normalizeOptions(opts);
const debug = printDocToDebug(doc);
const str = format(debug, opts);
return str;
},
printToDoc: function(text, opts) {
opts = normalizeOptions(opts);
Run AST comparison tests on Travis (#1553) * Run AST comparison tests on Travis It looks like some of these currently fail, so we should probably also sort that out. Inspired by https://github.com/prettier/prettier/issues/1552 * tests: Use specified parser when AST_COMPARE=1 This fixes some of the tests with AST_COMPARE=1 * Move cleanAST() into prettier.__debug This makes it available for tests to use. * AST_COMPARE=1 uses cleanAst() instead of removeEmptyStatements() Ths fixes some of the tests with AST_COMPARE=1 * Export parse() from src/parser.js This makes it available for tests to use. * tests: Use specified parser more when AST_COMPARE=1 This is a continuation of commit 86437a66d326919897fe89891a25824870f5bb79 This fixes some of the tests with AST_COMPARE=1 * massageAST: remove leadingComments/trailingComments This fixes some of the tests with AST_COMPARE=1 * massageAST: remove `extra` This fixes some of the tests with AST_COMPARE=1 * tests_config/run_spec.js: Rename variables for clarity * AST_COMPARE=1 tests compare unstringified objects This makes the test error output shorter. * fixup! Export parse() from src/parser.js * Revert "Run AST comparison tests on Travis" See https://github.com/prettier/prettier/pull/1553#issuecomment-300027747 This reverts commit 49873a956c532f23fd216551a35ae35c1a18407e. * fixup! fixup! Export parse() from src/parser.js * parser: Require babel-code-frame only when needed This addresses: * https://github.com/prettier/prettier/pull/1553#discussion_r115386253 * https://github.com/prettier/prettier/pull/1553#discussion_r115386250 * parser: Don't export now-unused parseWith* functions Addresses https://github.com/prettier/prettier/pull/1553#discussion_r115386964 * Move cleanAST/massageAST into own file, don't export This addresses: * https://github.com/prettier/prettier/pull/1553#discussion_r115386993 * https://github.com/prettier/prettier/pull/1553#discussion_r115386611 * Don't destructure require() result (Node v4 compat.) * Fix copy/paste error
2017-05-09 04:16:35 +03:00
const ast = parser.parse(text, opts);
attachComments(text, ast, opts);
const doc = printAstToDoc(ast, opts);
return doc;
},
printDocToString: function(doc, opts) {
opts = normalizeOptions(opts);
const str = printDocToString(doc, opts);
return str;
}
}
2016-11-29 23:23:00 +03:00
};