Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

refactor: extract options-normalizer/validator #5020

Merged
merged 3 commits into from
Aug 31, 2018
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@
"typescript-eslint-parser": "18.0.0",
"unicode-regex": "1.0.1",
"unified": "6.1.6",
"vnopts": "1.0.0",
"yaml": "ikatyang/yaml#a765c1ee16d6b8a5e715564645f2b85f7e04828b",
"yaml-unist-parser": "ikatyang/yaml-unist-parser#cd4f73325b3fc02a6d17842d0d9cee0dfc729c9b"
},
Expand Down
3 changes: 2 additions & 1 deletion src/cli/constant.js
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,8 @@ const options = {
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."
oppositeDescription: "Do not look for a configuration file.",
exception: value => value === false
},
"config-precedence": {
type: "choice",
Expand Down
15 changes: 6 additions & 9 deletions src/cli/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -848,12 +848,16 @@ function normalizeDetailedOptionMap(detailedOptionMap) {

function createMinimistOptions(detailedOptions) {
return {
// we use vnopts' AliasSchema to handle aliases for better error messages
alias: {},
boolean: detailedOptions
.filter(option => option.type === "boolean")
.map(option => option.name),
.map(option => [option.name].concat(option.alias || []))
.reduce((a, b) => a.concat(b)),
string: detailedOptions
.filter(option => option.type !== "boolean")
.map(option => option.name),
.map(option => [option.name].concat(option.alias || []))
.reduce((a, b) => a.concat(b)),
default: detailedOptions
.filter(option => !option.deprecated)
.filter(
Expand All @@ -867,13 +871,6 @@ function createMinimistOptions(detailedOptions) {
(current, option) =>
Object.assign({ [option.name]: option.default }, current),
{}
),
alias: detailedOptions
.filter(option => option.alias !== undefined)
.reduce(
(current, option) =>
Object.assign({ [option.name]: option.alias }, current),
{}
)
};
}
Expand Down
6 changes: 4 additions & 2 deletions src/main/core-options.js
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,6 @@ const options = {
since: "1.4.0",
category: CATEGORY_SPECIAL,
type: "path",
default: undefined,
description:
"Specify the input filepath. This will be used to do parser inference.",
cliName: "stdin-filepath",
Expand Down Expand Up @@ -208,7 +207,10 @@ const options = {
since: "0.0.0",
category: CATEGORY_GLOBAL,
type: "boolean",
default: false,
default: [
{ since: "0.0.0", value: false },
{ since: "1.15.0", value: undefined }
],
deprecated: "0.0.10",
description: "Use flow parser.",
redirect: { option: "parser", value: "flow" },
Expand Down
22 changes: 0 additions & 22 deletions src/main/options-descriptor.js

This file was deleted.

241 changes: 116 additions & 125 deletions src/main/options-normalizer.js
Original file line number Diff line number Diff line change
@@ -1,152 +1,143 @@
"use strict";

const leven = require("leven");
const validator = require("./options-validator");
const descriptors = require("./options-descriptor");

function normalizeOptions(options, optionInfos, opts) {
opts = opts || {};
const logger =
opts.logger === false
? { warn() {} }
: opts.logger !== undefined
? opts.logger
: console;
const descriptor = opts.descriptor || descriptors.apiDescriptor;
const passThrough = opts.passThrough || [];

const optionInfoMap = optionInfos.reduce(
(reduced, optionInfo) =>
Object.assign(reduced, { [optionInfo.name]: optionInfo }),
{}
);
const normalizedOptions = Object.keys(options).reduce((newOptions, key) => {
const optionInfo = optionInfoMap[key];

let optionName = key;
let optionValue = options[key];

if (!optionInfo) {
if (passThrough === true || passThrough.indexOf(optionName) !== -1) {
newOptions[optionName] = optionValue;
} else {
logger.warn(
createUnknownOptionMessage(
optionName,
optionValue,
optionInfos,
descriptor
)
);
}
return newOptions;
}
const vnopts = require("vnopts");

const cliDescriptor = {
key: key => (key.length === 1 ? `-${key}` : `--${key}`),
value: value => vnopts.apiDescriptor.value(value),
pair: ({ key, value }) =>
value === false
? `--no-${key}`
: value === true
? cliDescriptor.key(key)
: value === ""
? `${cliDescriptor.key(key)} without an argument`
: `${cliDescriptor.key(key)}=${value}`
};

if (!optionInfo.deprecated) {
optionValue = normalizeOption(optionValue, optionInfo);
} else if (typeof optionInfo.redirect === "string") {
logger.warn(createRedirectOptionMessage(optionInfo, descriptor));
optionName = optionInfo.redirect;
} else if (optionValue) {
logger.warn(createRedirectOptionMessage(optionInfo, descriptor));
optionValue = optionInfo.redirect.value;
optionName = optionInfo.redirect.option;
}
function normalizeOptions(
options,
optionInfos,
{ logger, isCLI = false, passThrough = false } = {}
) {
const unknown = !passThrough
? vnopts.levenUnknownHandler
: Array.isArray(passThrough)
? (key, value) =>
passThrough.indexOf(key) === -1 ? undefined : { [key]: value }
: (key, value) => ({ [key]: value });

const descriptor = isCLI ? cliDescriptor : vnopts.apiDescriptor;
const schemas = optionInfosToSchemas(optionInfos, { isCLI });
return vnopts.normalize(options, schemas, { logger, unknown, descriptor });
}

if (optionInfo.choices) {
const choiceInfo = optionInfo.choices.find(
choice => choice.value === optionValue
);
if (choiceInfo && choiceInfo.deprecated) {
logger.warn(
createRedirectChoiceMessage(optionInfo, choiceInfo, descriptor)
);
optionValue = choiceInfo.redirect;
}
}
function optionInfosToSchemas(optionInfos, { isCLI }) {
const schemas = [];

if (optionInfo.array && !Array.isArray(optionValue)) {
optionValue = [optionValue];
}
if (isCLI) {
schemas.push(vnopts.AnySchema.create({ name: "_" }));
}

if (optionValue !== optionInfo.default) {
validator.validateOption(optionValue, optionInfoMap[optionName], {
descriptor
});
}
for (const optionInfo of optionInfos) {
schemas.push(optionInfoToSchema(optionInfo, { isCLI }));

newOptions[optionName] = optionValue;
return newOptions;
}, {});
if (optionInfo.alias && isCLI) {
schemas.push(
vnopts.AliasSchema.create({
name: optionInfo.alias,
sourceName: optionInfo.name
})
);
}
}

return normalizedOptions;
return schemas;
}

function normalizeOption(option, optionInfo) {
return optionInfo.type === "int" ? Number(option) : option;
}
function optionInfoToSchema(optionInfo, { isCLI }) {
let SchemaConstructor;
const parameters = { name: optionInfo.name };
const handlers = {};

function createUnknownOptionMessage(key, value, optionInfos, descriptor) {
const messages = [`Ignored unknown option ${descriptor(key, value)}.`];
switch (optionInfo.type) {
case "int":
SchemaConstructor = vnopts.IntegerSchema;
if (isCLI) {
parameters.preprocess = value => Number(value);
}
break;
case "choice":
SchemaConstructor = vnopts.ChoiceSchema;
parameters.choices = optionInfo.choices.map(
choiceInfo =>
typeof choiceInfo === "object" && choiceInfo.redirect
? Object.assign({}, choiceInfo, {
redirect: {
to: { key: optionInfo.name, value: choiceInfo.redirect }
}
})
: choiceInfo
);
break;
case "boolean":
SchemaConstructor = vnopts.BooleanSchema;
break;
case "flag":
case "path":
SchemaConstructor = vnopts.StringSchema;
break;
default:
throw new Error(`Unexpected type ${optionInfo.type}`);
}

const suggestedOptionInfo = optionInfos.find(
optionInfo => leven(optionInfo.name, key) < 3
);
if (suggestedOptionInfo) {
messages.push(`Did you mean ${JSON.stringify(suggestedOptionInfo.name)}?`);
if (optionInfo.exception) {
parameters.validate = (value, schema, utils) => {
return optionInfo.exception(value) || schema.validate(value, utils);
};
} else {
parameters.validate = (value, schema, utils) => {
return value === undefined || schema.validate(value, utils);
};
}

return messages.join(" ");
}
if (optionInfo.redirect) {
handlers.redirect = value =>
!value
? undefined
: {
to: {
key: optionInfo.redirect.option,
value: optionInfo.redirect.value
}
};
}

function createRedirectOptionMessage(optionInfo, descriptor) {
return `${descriptor(
optionInfo.name
)} is deprecated. Prettier now treats it as ${
typeof optionInfo.redirect === "string"
? descriptor(optionInfo.redirect)
: descriptor(optionInfo.redirect.option, optionInfo.redirect.value)
}.`;
}
if (optionInfo.deprecated) {
handlers.deprecated = true;
}

function createRedirectChoiceMessage(optionInfo, choiceInfo, descriptor) {
return `${descriptor(
optionInfo.name,
choiceInfo.value
)} is deprecated. Prettier now treats it as ${descriptor(
optionInfo.name,
choiceInfo.redirect
)}.`;
return optionInfo.array
? vnopts.ArraySchema.create(
Object.assign(
isCLI ? { preprocess: v => [].concat(v) } : {},
handlers,
{ valueSchema: SchemaConstructor.create(parameters) }
)
)
: SchemaConstructor.create(Object.assign({}, parameters, handlers));
}

function normalizeApiOptions(options, optionInfos, opts) {
return normalizeOptions(
options,
optionInfos,
Object.assign({ descriptor: descriptors.apiDescriptor }, opts)
);
return normalizeOptions(options, optionInfos, opts);
}

function normalizeCliOptions(options, optionInfos, opts) {
const args = options["_"] || [];

const newOptions = normalizeOptions(
Object.keys(options).reduce(
(reduced, key) =>
Object.assign(
reduced,
key.length === 1 // omit alias
? null
: { [key]: options[key] }
),
{}
),
return normalizeOptions(
options,
optionInfos,
Object.assign({ descriptor: descriptors.cliDescriptor }, opts)
Object.assign({ isCLI: true }, opts)
);
newOptions["_"] = args;

return newOptions;
}

module.exports = {
Expand Down
Loading