Skip to content

Commit

Permalink
Refactoring: better boundaries for different parts of the project (pr…
Browse files Browse the repository at this point in the history
  • Loading branch information
duailibe authored Apr 25, 2018
1 parent 289b98c commit 67f1c48
Show file tree
Hide file tree
Showing 23 changed files with 334 additions and 306 deletions.
11 changes: 11 additions & 0 deletions docs/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,17 @@ If `options.editorconfig` is `true` and an [`.editorconfig` file](http://editorc

Use `prettier.resolveConfig.sync(filePath [, options])` if you'd like to use sync version.

## `prettier.resolveConfigFile(filePath [, options])`

`resolveConfigFile` can be used to find the path of the Prettier's configuration file will be used when resolving the config (i.e. when calling `resolveConfig`). A promise is returned which will resolve to:

* The path of the configuration file.
* `null`, if no file was found.

The promise will be rejected if there was an error parsing the configuration file.

If `options.useCache` is `false`, all caching will be bypassed.

## `prettier.clearConfigCache()`

As you repeatedly call `resolveConfig`, the file system structure will be cached for performance. This function will clear the cache. Generally this is only needed for editor integrations that know that the file system has changed since the last format took place.
Expand Down
29 changes: 24 additions & 5 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,13 @@ const version = require("./package.json").version;

const privateUtil = require("./src/common/util");
const sharedUtil = require("./src/common/util-shared");
const getSupportInfo = require("./src/common/support").getSupportInfo;
const getSupportInfo = require("./src/main/support").getSupportInfo;
const loadPlugins = require("./src/common/load-plugins");
const massageAST = require("./src/main/massage-ast");

const comments = require("./src/main/comments");
const printAstToDoc = require("./src/main/ast-to-doc");
const normalizeOptions = require("./src/main/options").normalize;
const rawNormalizeOptions = require("./src/main/options").normalize;
const parser = require("./src/main/parser");

const config = require("./src/config/resolve-config");
Expand All @@ -17,6 +19,16 @@ const doc = require("./src/doc");
const printDocToString = doc.printer.printDocToString;
const printDocToDebug = doc.debug.printDocToDebug;

function withPlugins(opts) {
return Object.assign({}, opts, {
plugins: loadPlugins(opts && opts.plugins)
});
}

function normalizeOptions(opts) {
return rawNormalizeOptions(withPlugins(opts));
}

function guessLineEnding(text) {
const index = text.indexOf("\n");
if (index >= 0 && text.charAt(index - 1) === "\r") {
Expand Down Expand Up @@ -406,19 +418,26 @@ module.exports = {
doc,

resolveConfig: config.resolveConfig,
resolveConfigFile: config.resolveConfigFile,
clearConfigCache: config.clearCache,

getSupportInfo,
getSupportInfo(version, opts) {
return getSupportInfo(version, withPlugins(opts));
},

version,

util: sharedUtil,

/* istanbul ignore next */
__debug: {
parse: function(text, opts) {
parse: function(text, opts, massage) {
opts = normalizeOptions(opts);
return parser.parse(text, opts);
const parsed = parser.parse(text, opts);
if (massage) {
parsed.ast = massageAST(parsed.ast, opts);
}
return parsed;
},
formatAST: function(ast, opts) {
opts = normalizeOptions(opts);
Expand Down
5 changes: 2 additions & 3 deletions jest.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,8 @@ module.exports = {
collectCoverage: ENABLE_COVERAGE,
collectCoverageFrom: ["src/**/*.js", "index.js", "!<rootDir>/node_modules/"],
coveragePathIgnorePatterns: [
"<rootDir>/src/doc-debug.js",
"<rootDir>/src/clean-ast.js",
"<rootDir>/src/deprecated.js"
"<rootDir>/src/doc/doc-debug.js",
"<rootDir>/src/main/massage-ast.js"
],
moduleNameMapper: {
// Jest wires `fs` to `graceful-fs`, which causes a memory leak when
Expand Down
38 changes: 14 additions & 24 deletions src/cli/constant.js
Original file line number Diff line number Diff line change
@@ -1,19 +1,14 @@
"use strict";

const dedent = require("dedent");

const CATEGORY_CONFIG = "Config";
const CATEGORY_EDITOR = "Editor";
const CATEGORY_FORMAT = "Format";
const CATEGORY_OTHER = "Other";
const CATEGORY_OUTPUT = "Output";
const coreOptions = require("../main/core-options");

const categoryOrder = [
CATEGORY_OUTPUT,
CATEGORY_FORMAT,
CATEGORY_CONFIG,
CATEGORY_EDITOR,
CATEGORY_OTHER
coreOptions.CATEGORY_OUTPUT,
coreOptions.CATEGORY_FORMAT,
coreOptions.CATEGORY_CONFIG,
coreOptions.CATEGORY_EDITOR,
coreOptions.CATEGORY_OTHER
];

/**
Expand Down Expand Up @@ -87,14 +82,14 @@ const options = {
},
config: {
type: "path",
category: CATEGORY_CONFIG,
category: coreOptions.CATEGORY_CONFIG,
description:
"Path to a Prettier configuration file (.prettierrc, package.json, prettier.config.js).",
oppositeDescription: "Do not look for a configuration file."
},
"config-precedence": {
type: "choice",
category: CATEGORY_CONFIG,
category: coreOptions.CATEGORY_CONFIG,
default: "cli-override",
choices: [
{
Expand Down Expand Up @@ -124,15 +119,15 @@ const options = {
},
editorconfig: {
type: "boolean",
category: CATEGORY_CONFIG,
category: coreOptions.CATEGORY_CONFIG,
description: "Take .editorconfig into account when parsing configuration.",
oppositeDescription:
"Don't take .editorconfig into account when parsing configuration.",
default: true
},
"find-config-path": {
type: "path",
category: CATEGORY_CONFIG,
category: coreOptions.CATEGORY_CONFIG,
description:
"Find and print the path to a configuration file for the given input file."
},
Expand All @@ -146,13 +141,13 @@ const options = {
},
"ignore-path": {
type: "path",
category: CATEGORY_CONFIG,
category: coreOptions.CATEGORY_CONFIG,
default: ".prettierignore",
description: "Path to a file with patterns describing files to ignore."
},
"list-different": {
type: "boolean",
category: CATEGORY_OUTPUT,
category: coreOptions.CATEGORY_OUTPUT,
alias: "l",
description:
"Print the names of files that are different from Prettier's formatting."
Expand All @@ -178,12 +173,12 @@ const options = {
},
"with-node-modules": {
type: "boolean",
category: CATEGORY_CONFIG,
category: coreOptions.CATEGORY_CONFIG,
description: "Process files inside 'node_modules' directory."
},
write: {
type: "boolean",
category: CATEGORY_OUTPUT,
category: coreOptions.CATEGORY_OUTPUT,
description: "Edit files in-place. (Beware!)"
}
};
Expand All @@ -196,11 +191,6 @@ const usageSummary = dedent`
`;

module.exports = {
CATEGORY_CONFIG,
CATEGORY_EDITOR,
CATEGORY_FORMAT,
CATEGORY_OTHER,
CATEGORY_OUTPUT,
categoryOrder,
options,
usageSummary
Expand Down
30 changes: 13 additions & 17 deletions src/cli/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,13 @@ const leven = require("leven");

const minimist = require("./minimist");
const prettier = require("../../index");
const cleanAST = require("../common/clean-ast").cleanAST;
const errors = require("../common/errors");
const resolver = require("../config/resolve-config");
const constant = require("./constant");
const coreOptions = require("../main/core-options");
const optionsModule = require("../main/options");
const optionsNormalizer = require("../main/options-normalizer");
const thirdParty = require("../common/third-party");
const getSupportInfo = require("../common/support").getSupportInfo;
const util = require("../common/util");
const arrayify = require("../utils/arrayify");

const OPTION_USAGE_THRESHOLD = 25;
const CHOICE_USAGE_MARGIN = 3;
Expand Down Expand Up @@ -79,7 +77,7 @@ function handleError(context, filename, error) {
}

function logResolvedConfigPathOrDie(context, filePath) {
const configFile = resolver.resolveConfigFile.sync(filePath);
const configFile = prettier.resolveConfigFile.sync(filePath);
if (configFile) {
context.logger.log(path.relative(process.cwd(), configFile));
} else {
Expand Down Expand Up @@ -127,14 +125,12 @@ function format(context, input, opt) {
"prettier(input) !== prettier(prettier(input))\n" + diff(pp, pppp)
);
} else {
const normalizedOpts = optionsModule.normalize(opt);
const ast = cleanAST(
prettier.__debug.parse(input, opt).ast,
normalizedOpts
const stringify = obj => JSON.stringify(obj, null, 2);
const ast = stringify(
prettier.__debug.parse(input, opt, /* massage */ true).ast
);
const past = cleanAST(
prettier.__debug.parse(pp, opt).ast,
normalizedOpts
const past = stringify(
prettier.__debug.parse(pp, opt, /* massage */ true).ast
);

if (ast !== past) {
Expand Down Expand Up @@ -172,7 +168,7 @@ function getOptionsOrDie(context, filePath) {
: `resolve config from '${filePath}'`
);

const options = resolver.resolveConfig.sync(filePath, {
const options = prettier.resolveConfig.sync(filePath, {
editorconfig: context.argv["editorconfig"],
config: context.argv["config"]
});
Expand Down Expand Up @@ -713,7 +709,7 @@ function createLogger(logLevel) {
}

function normalizeDetailedOption(name, option) {
return Object.assign({ category: constant.CATEGORY_OTHER }, option, {
return Object.assign({ category: coreOptions.CATEGORY_OTHER }, option, {
choices:
option.choices &&
option.choices.map(choice => {
Expand Down Expand Up @@ -782,7 +778,7 @@ function createDetailedOptionMap(supportOptions) {
const newOption = Object.assign({}, option, {
name: option.cliName || dashify(option.name),
description: option.cliDescription || option.description,
category: option.cliCategory || constant.CATEGORY_FORMAT,
category: option.cliCategory || coreOptions.CATEGORY_FORMAT,
forwardToApi: option.name
});

Expand Down Expand Up @@ -828,7 +824,7 @@ function initContext(context) {
}

function updateContextOptions(context, plugins) {
const supportOptions = getSupportInfo(null, {
const supportOptions = prettier.getSupportInfo(null, {
showDeprecated: true,
showUnreleased: true,
showInternal: true,
Expand All @@ -839,7 +835,7 @@ function updateContextOptions(context, plugins) {
Object.assign({}, createDetailedOptionMap(supportOptions), constant.options)
);

const detailedOptions = util.arrayify(detailedOptionMap, "name");
const detailedOptions = arrayify(detailedOptionMap, "name");

const apiDefaultOptions = supportOptions
.filter(optionInfo => !optionInfo.deprecated)
Expand Down
9 changes: 0 additions & 9 deletions src/common/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -713,14 +713,6 @@ function hasNodeIgnoreComment(node) {
);
}

function arrayify(object, keyName) {
return Object.keys(object).reduce(
(array, key) =>
array.concat(Object.assign({ [keyName]: key }, object[key])),
[]
);
}

function addCommentHelper(node, comment) {
const comments = node.comments || (node.comments = []);
comments.push(comment);
Expand Down Expand Up @@ -753,7 +745,6 @@ function addTrailingComment(node, comment) {
}

module.exports = {
arrayify,
punctuationRegex,
punctuationCharRange,
getStringWidth,
Expand Down
2 changes: 1 addition & 1 deletion src/language-css/options.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

const jsOptions = require("../language-js/options");

// format based on https://github.com/prettier/prettier/blob/master/src/common/support.js
// format based on https://github.com/prettier/prettier/blob/master/src/main/core-options.js
module.exports = {
singleQuote: jsOptions.singleQuote
};
2 changes: 1 addition & 1 deletion src/language-graphql/options.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

const jsOptions = require("../language-js/options");

// format based on https://github.com/prettier/prettier/blob/master/src/common/support.js
// format based on https://github.com/prettier/prettier/blob/master/src/main/core-options.js
module.exports = {
bracketSpacing: jsOptions.bracketSpacing
};
7 changes: 7 additions & 0 deletions src/language-html/clean.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
"use strict";

module.exports = function(ast) {
if (ast.type === "text") {
return null;
}
};
22 changes: 21 additions & 1 deletion src/language-html/parser-parse5.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,32 @@ function parse(text /*, parsers, opts*/) {
treeAdapter: parse5.treeAdapters.htmlparser2,
locationInfo: true
});
return extendAst(ast);
return normalize(extendAst(ast));
} catch (error) {
throw error;
}
}

function normalize(ast) {
if (Array.isArray(ast)) {
return ast.map(normalize);
}

if (!ast || typeof ast !== "object") {
return ast;
}

delete ast.parent;
delete ast.next;
delete ast.prev;

for (const key of Object.keys(ast)) {
ast[key] = normalize(ast[key]);
}

return ast;
}

function extendAst(ast) {
if (!ast || !ast.children) {
return ast;
Expand Down
2 changes: 2 additions & 0 deletions src/language-html/printer-htmlparser2.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"use strict";

const embed = require("./embed");
const clean = require("./clean");
const privateUtil = require("../common/util");
const docBuilders = require("../doc").builders;
const concat = docBuilders.concat;
Expand Down Expand Up @@ -116,6 +117,7 @@ function printChildren(path, print) {

module.exports = {
print: genericPrint,
massageAstNode: clean,
embed,
hasPrettierIgnore: privateUtil.hasIgnoreComment
};
2 changes: 1 addition & 1 deletion src/language-js/options.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

const CATEGORY_JAVASCRIPT = "JavaScript";

// format based on https://github.com/prettier/prettier/blob/master/src/common/support.js
// format based on https://github.com/prettier/prettier/blob/master/src/main/core-options.js
module.exports = {
arrowParens: {
since: "1.9.0",
Expand Down
Loading

0 comments on commit 67f1c48

Please sign in to comment.