Merge pull request #5467 from loganfsmyth/clean-options

Misc reorganizing and prep for ignore/only refactoring
This commit is contained in:
Logan Smyth
2017-03-16 20:25:20 -07:00
committed by GitHub
11 changed files with 259 additions and 300 deletions

View File

@@ -1,64 +1,29 @@
import fs from "fs";
export { default as File } from "./transformation/file";
export { default as buildExternalHelpers } from "./tools/build-external-helpers";
export { default as template } from "babel-template";
export { default as resolvePlugin } from "./helpers/resolve-plugin";
export { default as resolvePreset } from "./helpers/resolve-preset";
export File from "./transformation/file";
export buildExternalHelpers from "./tools/build-external-helpers";
export resolvePlugin from "./helpers/resolve-plugin";
export resolvePreset from "./helpers/resolve-preset";
export { version } from "../package";
export { getEnv } from "./helpers/environment";
import * as util from "./util";
export { util };
export * as util from "./util";
import * as messages from "babel-messages";
export { messages };
export * as messages from "babel-messages";
export * as types from "babel-types";
export traverse from "babel-traverse";
export template from "babel-template";
import * as t from "babel-types";
export { t as types };
import traverse from "babel-traverse";
export { traverse };
import OptionManager from "./transformation/file/options/option-manager";
export { OptionManager };
export OptionManager from "./transformation/file/options/option-manager";
export function Plugin(alias) {
throw new Error(`The (${alias}) Babel 5 plugin is being run with Babel 6.`);
}
import { transform, analyse, transformFromAst } from "./transformation/pipeline";
export { transform, analyse, transformFromAst };
export {
transform,
analyse,
transformFromAst,
transformFile,
transformFileSync,
} from "./transformation/pipeline";
export function transformFile(filename: string, opts?: Object, callback: Function) {
if (typeof opts === "function") {
callback = opts;
opts = {};
}
opts.filename = filename;
fs.readFile(filename, function (err, code) {
let result;
if (!err) {
try {
result = transform(code, opts);
} catch (_err) {
err = _err;
}
}
if (err) {
callback(err);
} else {
callback(null, result);
}
});
}
export function transformFileSync(filename: string, opts?: Object = {}): string {
opts.filename = filename;
return transform(fs.readFileSync(filename, "utf8"), opts);
}

View File

@@ -3,15 +3,12 @@
import getHelper from "babel-helpers";
import * as metadataVisitor from "./metadata";
import convertSourceMap from "convert-source-map";
import OptionManager from "./options/option-manager";
import PluginPass from "../plugin-pass";
import { NodePath, Hub, Scope } from "babel-traverse";
import sourceMap from "source-map";
import generate from "babel-generator";
import codeFrame from "babel-code-frame";
import defaults from "lodash/defaults";
import traverse from "babel-traverse";
import Logger from "./logger";
import Store from "../../store";
import { parse } from "babylon";
import * as util from "../../util";
@@ -44,10 +41,6 @@ export default class File extends Store {
constructor(opts: Object = {}) {
super();
this.log = new Logger(this, opts.filename || "unknown");
opts = this.initOptions(opts);
let passes = [];
if (opts.plugins) passes.push(opts.plugins);
@@ -102,7 +95,6 @@ export default class File extends Store {
pluginPasses: Array<Array<[Plugin, Object]>>;
parserOpts: BabelParserOptions;
log: Logger;
opts: Object;
dynamicImportTypes: Object;
dynamicImportIds: Object;
@@ -130,41 +122,6 @@ export default class File extends Store {
}
}
initOptions(opts) {
opts = this.log.wrap(() => new OptionManager().init(opts));
if (opts.inputSourceMap) {
opts.sourceMaps = true;
}
if (opts.moduleId) {
opts.moduleIds = true;
}
opts.basename = path.basename(opts.filename, path.extname(opts.filename));
defaults(opts, {
moduleRoot: opts.sourceRoot,
});
defaults(opts, {
sourceRoot: opts.moduleRoot,
});
defaults(opts, {
filenameRelative: opts.filename,
});
const basenameRelative = path.basename(opts.filenameRelative);
defaults(opts, {
sourceFileName: basenameRelative,
sourceMapTarget: basenameRelative,
});
return opts;
}
getModuleName(): ?string {
const opts = this.opts;
if (!opts.moduleIds) {
@@ -404,9 +361,9 @@ export default class File extends Store {
}
}
this.log.debug("Parse start");
util.debug(this.opts, "Parse start");
const ast = parseCode(code, parserOpts || this.parserOpts);
this.log.debug("Parse stop");
util.debug(this.opts, "Parse stop");
return ast;
}
@@ -424,9 +381,9 @@ export default class File extends Store {
}
addAst(ast) {
this.log.debug("Start set AST");
util.debug(this.opts, "Start set AST");
this._addAst(ast);
this.log.debug("End set AST");
util.debug(this.opts, "End set AST");
}
transform(): BabelFileResult {
@@ -441,13 +398,13 @@ export default class File extends Store {
}
this.call("pre", passes);
this.log.debug("Start transform traverse");
util.debug(this.opts, "Start transform traverse");
// merge all plugin visitors into a single visitor
const visitor = traverse.visitors.merge(visitors, passes, this.opts.wrapPluginVisitorMethod);
traverse(this.ast, visitor, this.scope);
this.log.debug("End transform traverse");
util.debug(this.opts, "End transform traverse");
this.call("post", passes);
}
@@ -588,14 +545,14 @@ export default class File extends Store {
}
}
this.log.debug("Generation start");
util.debug(this.opts, "Generation start");
const _result = gen(ast, opts.generatorOpts ? Object.assign(opts, opts.generatorOpts) : opts,
this.code);
result.code = _result.code;
result.map = _result.map;
this.log.debug("Generation end");
util.debug(this.opts, "Generation end");
if (this.shebang) {
// add back shebang

View File

@@ -1,66 +0,0 @@
import type File from "./index";
import buildDebug from "debug";
const verboseDebug = buildDebug("babel:verbose");
const generalDebug = buildDebug("babel");
const seenDeprecatedMessages = [];
export default class Logger {
constructor(file: File, filename: string) {
this.filename = filename;
this.file = file;
}
filename: string;
file: File;
_buildMessage(msg: string): string {
let parts = `[BABEL] ${this.filename}`;
if (msg) parts += `: ${msg}`;
return parts;
}
wrap<T>(callback: () => T): T {
try {
return callback();
} catch (e) {
e.message = this._buildMessage(e.message);
throw e;
}
}
warn(msg: string) {
console.warn(this._buildMessage(msg));
}
error(msg: string, Constructor: typeof Error = Error): Error {
throw new Constructor(this._buildMessage(msg));
}
deprecate(msg: string) {
if (this.file.opts && this.file.opts.suppressDeprecationMessages) return;
msg = this._buildMessage(msg);
// already seen this message
if (seenDeprecatedMessages.indexOf(msg) >= 0) return;
// make sure we don't see it again
seenDeprecatedMessages.push(msg);
console.error(msg);
}
verbose(msg: string) {
if (verboseDebug.enabled) verboseDebug(this._buildMessage(msg));
}
debug(msg: string) {
if (generalDebug.enabled) generalDebug(this._buildMessage(msg));
}
deopt(node: Object, msg: string) {
this.debug(msg);
}
}

View File

@@ -25,18 +25,18 @@ export default function buildConfigChain(opts: Object = {}) {
const filename = opts.filename;
const builder = new ConfigChainBuilder();
// resolve all .babelrc files
if (opts.babelrc !== false) {
builder.findConfigs(filename);
}
builder.mergeConfig({
options: opts,
alias: "base",
dirname: process.cwd(),
});
return builder.configs;
// resolve all .babelrc files
if (opts.babelrc !== false) {
builder.findConfigs(filename);
}
return builder.configs.reverse();
}
class ConfigChainBuilder {
@@ -61,6 +61,14 @@ class ConfigChainBuilder {
let foundIgnore = false;
while (loc !== (loc = path.dirname(loc))) {
if (!foundIgnore) {
const ignoreLoc = path.join(loc, BABELIGNORE_FILENAME);
if (exists(ignoreLoc)) {
this.addIgnoreConfig(ignoreLoc);
foundIgnore = true;
}
}
if (!foundConfig) {
const configLoc = path.join(loc, BABELRC_FILENAME);
const configJSLoc = path.join(loc, BABELRC_JS_FILENAME);
@@ -85,14 +93,6 @@ class ConfigChainBuilder {
foundConfig = !!foundConfigs.length;
}
if (!foundIgnore) {
const ignoreLoc = path.join(loc, BABELIGNORE_FILENAME);
if (exists(ignoreLoc)) {
this.addIgnoreConfig(ignoreLoc);
foundIgnore = true;
}
}
if (foundIgnore && foundConfig) return;
}
}
@@ -175,6 +175,26 @@ class ConfigChainBuilder {
loc = loc || alias;
// env
const envKey = babel.getEnv();
if (options.env) {
const envOpts = options.env[envKey];
delete options.env;
this.mergeConfig({
options: envOpts,
alias: `${alias}.env.${envKey}`,
dirname: dirname,
});
}
this.configs.push({
options,
alias,
loc,
dirname,
});
// add extends clause
if (options.extends) {
const extendsLoc = resolve(options.extends, dirname);
@@ -185,28 +205,6 @@ class ConfigChainBuilder {
}
delete options.extends;
}
this.configs.push({
options,
alias,
loc,
dirname,
});
// env
let envOpts;
const envKey = babel.getEnv();
if (options.env) {
envOpts = options.env[envKey];
delete options.env;
}
this.mergeConfig({
options: envOpts,
alias: `${alias}.env.${envKey}`,
dirname: dirname,
});
}
}

View File

@@ -3,6 +3,7 @@ import Plugin from "../../plugin";
import * as messages from "babel-messages";
import resolvePlugin from "../../../helpers/resolve-plugin";
import resolvePreset from "../../../helpers/resolve-preset";
import defaults from "lodash/defaults";
import cloneDeepWith from "lodash/cloneDeepWith";
import merge from "../../../helpers/merge";
import removed from "./removed";
@@ -372,11 +373,45 @@ export default class OptionManager {
}
init(opts: Object = {}): Object {
for (const config of buildConfigChain(opts)) {
this.mergeOptions(config);
try {
for (const config of buildConfigChain(opts)) {
this.mergeOptions(config);
}
} catch (e) {
e.message = util.message(opts, e.message);
throw e;
}
return this.options;
opts = this.options;
if (opts.inputSourceMap) {
opts.sourceMaps = true;
}
if (opts.moduleId) {
opts.moduleIds = true;
}
defaults(opts, {
moduleRoot: opts.sourceRoot,
});
defaults(opts, {
sourceRoot: opts.moduleRoot,
});
defaults(opts, {
filenameRelative: opts.filename,
});
const basenameRelative = path.basename(opts.filenameRelative);
defaults(opts, {
sourceFileName: basenameRelative,
sourceMapTarget: basenameRelative,
});
return opts;
}
}

View File

@@ -1,7 +1,10 @@
/* global BabelFileResult, BabelFileMetadata */
import fs from "fs";
import normalizeAst from "../helpers/normalize-ast";
import Plugin from "./plugin";
import File from "./file";
import OptionManager from "./file/options/option-manager";
export function analyse(code: string, opts: Object = {}, visitor?: Object): ?BabelFileMetadata {
opts.code = false;
@@ -13,6 +16,8 @@ export function analyse(code: string, opts: Object = {}, visitor?: Object): ?Bab
}
export function transform(code: string, opts?: Object): BabelFileResult {
opts = new OptionManager().init(opts);
const file = new File(opts);
return file.wrap(code, function () {
file.addCode(code);
@@ -22,6 +27,8 @@ export function transform(code: string, opts?: Object): BabelFileResult {
}
export function transformFromAst(ast: Object, code: string, opts: Object): BabelFileResult {
opts = new OptionManager().init(opts);
ast = normalizeAst(ast);
const file = new File(opts);
@@ -31,3 +38,50 @@ export function transformFromAst(ast: Object, code: string, opts: Object): Babel
return file.transform();
});
}
export function transformFile(filename: string, opts?: Object, callback: Function) {
if (typeof opts === "function") {
callback = opts;
opts = {};
}
opts.filename = filename;
opts = new OptionManager().init(opts);
fs.readFile(filename, function (err, code) {
let result;
if (!err) {
try {
const file = new File(opts);
result = file.wrap(code, function () {
file.addCode(code);
file.parseCode(code);
return file.transform();
});
} catch (_err) {
err = _err;
}
}
if (err) {
callback(err);
} else {
callback(null, result);
}
});
}
export function transformFileSync(filename: string, opts?: Object = {}): string {
opts.filename = filename;
opts = new OptionManager().init(opts);
const code = fs.readFileSync(filename, "utf8");
const file = new File(opts);
return file.wrap(code, function () {
file.addCode(code);
file.parseCode(code);
return file.transform();
});
}

View File

@@ -5,9 +5,24 @@ import includes from "lodash/includes";
import isRegExp from "lodash/isRegExp";
import path from "path";
import slash from "slash";
import buildDebug from "debug";
export { inherits, inspect } from "util";
const debugBabel = buildDebug("babel");
export function debug(opts: Object, msg: string) {
debugBabel(message(opts, msg));
}
export function message(opts: Object, msg: string) {
// There are a few case where throws errors will try to annotate themselves multiple times, so
// to keep things simple we just bail out if re-wrapping the message.
if (/^\[BABEL\]/.test(msg)) return msg;
return `[BABEL] ${opts.filename || "unknown"}: ${msg}`;
}
/**
* Test if a filename ends with a compilable extension.
*/
@@ -111,20 +126,22 @@ export function booleanify(val: any): boolean | any {
export function shouldIgnore(
filename: string,
ignore: Array<RegExp | Function> = [],
ignore: Array<RegExp | Function>,
only?: Array<RegExp | Function>,
): boolean {
filename = filename.replace(/\\/g, "/");
if (ignore && ignore.length) {
for (const pattern of ignore) {
if (matchesPattern(pattern, filename)) return true;
}
}
if (only) {
for (const pattern of only) {
if (_shouldIgnore(pattern, filename)) return false;
if (matchesPattern(pattern, filename)) return false;
}
return true;
} else if (ignore.length) {
for (const pattern of ignore) {
if (_shouldIgnore(pattern, filename)) return true;
}
}
return false;
@@ -135,7 +152,7 @@ export function shouldIgnore(
* Otherwise returns result of matching pattern Regex with filename.
*/
function _shouldIgnore(pattern: Function | RegExp, filename: string) {
function matchesPattern(pattern: Function | RegExp, filename: string) {
if (typeof pattern === "function") {
return pattern(filename);
} else {

View File

@@ -86,16 +86,6 @@ describe("buildConfigChain", function () {
});
const expected = [
{
options: {
plugins: [
"dir2",
],
},
alias: fixture("dir2", ".babelrc"),
loc: fixture("dir2", ".babelrc"),
dirname: fixture("dir2"),
},
{
options: {
ignore: [
@@ -106,6 +96,16 @@ describe("buildConfigChain", function () {
loc: fixture(".babelignore"),
dirname: fixture(),
},
{
options: {
plugins: [
"dir2",
],
},
alias: fixture("dir2", ".babelrc"),
loc: fixture("dir2", ".babelrc"),
dirname: fixture("dir2"),
},
{
options: {
filename: fixture("dir2", "src.js"),
@@ -125,16 +125,6 @@ describe("buildConfigChain", function () {
});
const expected = [
{
options: {
plugins: [
"env-base",
],
},
alias: fixture("env", ".babelrc"),
loc: fixture("env", ".babelrc"),
dirname: fixture("env"),
},
{
options: {
ignore: [
@@ -145,6 +135,16 @@ describe("buildConfigChain", function () {
loc: fixture(".babelignore"),
dirname: fixture(),
},
{
options: {
plugins: [
"env-base",
],
},
alias: fixture("env", ".babelrc"),
loc: fixture("env", ".babelrc"),
dirname: fixture("env"),
},
{
options: {
filename: fixture("env", "src.js"),
@@ -166,6 +166,16 @@ describe("buildConfigChain", function () {
});
const expected = [
{
options: {
ignore: [
"root-ignore",
],
},
alias: fixture(".babelignore"),
loc: fixture(".babelignore"),
dirname: fixture(),
},
{
options: {
plugins: [
@@ -186,16 +196,6 @@ describe("buildConfigChain", function () {
loc: fixture("env", ".babelrc.env.foo"),
dirname: fixture("env"),
},
{
options: {
ignore: [
"root-ignore",
],
},
alias: fixture(".babelignore"),
loc: fixture(".babelignore"),
dirname: fixture(),
},
{
options: {
filename: fixture("env", "src.js"),
@@ -218,6 +218,16 @@ describe("buildConfigChain", function () {
});
const expected = [
{
options: {
ignore: [
"root-ignore",
],
},
alias: fixture(".babelignore"),
loc: fixture(".babelignore"),
dirname: fixture(),
},
{
options: {
plugins: [
@@ -238,16 +248,6 @@ describe("buildConfigChain", function () {
loc: fixture("env", ".babelrc.env.bar"),
dirname: fixture("env"),
},
{
options: {
ignore: [
"root-ignore",
],
},
alias: fixture(".babelignore"),
loc: fixture(".babelignore"),
dirname: fixture(),
},
{
options: {
filename: fixture("env", "src.js"),
@@ -305,6 +305,16 @@ describe("buildConfigChain", function () {
});
const expected = [
{
options: {
ignore: [
"root-ignore",
],
},
alias: fixture(".babelignore"),
loc: fixture(".babelignore"),
dirname: fixture(),
},
{
options: {
plugins: [
@@ -316,16 +326,6 @@ describe("buildConfigChain", function () {
loc: fixture("js-config", ".babelrc.js"),
dirname: fixture("js-config"),
},
{
options: {
ignore: [
"root-ignore",
],
},
alias: fixture(".babelignore"),
loc: fixture(".babelignore"),
dirname: fixture(),
},
{
options: {
filename: fixture("js-config", "src.js"),
@@ -345,6 +345,16 @@ describe("buildConfigChain", function () {
});
const expected = [
{
options: {
ignore: [
"root-ignore",
],
},
alias: fixture(".babelignore"),
loc: fixture(".babelignore"),
dirname: fixture(),
},
{
options: {
plugins: [
@@ -356,16 +366,6 @@ describe("buildConfigChain", function () {
loc: fixture("js-config-default", ".babelrc.js"),
dirname: fixture("js-config-default"),
},
{
options: {
ignore: [
"root-ignore",
],
},
alias: fixture(".babelignore"),
loc: fixture(".babelignore"),
dirname: fixture(),
},
{
options: {
filename: fixture("js-config-default", "src.js"),
@@ -384,6 +384,16 @@ describe("buildConfigChain", function () {
});
const expected = [
{
options: {
ignore: [
"root-ignore",
],
},
alias: fixture(".babelignore"),
loc: fixture(".babelignore"),
dirname: fixture(),
},
{
options: {
plugins: [
@@ -405,16 +415,6 @@ describe("buildConfigChain", function () {
loc: fixture("js-config-extended", ".babelrc.js"),
dirname: fixture("js-config-extended"),
},
{
options: {
ignore: [
"root-ignore",
],
},
alias: fixture(".babelignore"),
loc: fixture(".babelignore"),
dirname: fixture(),
},
{
options: {
filename: fixture("js-config-extended", "src.js"),
@@ -435,16 +435,6 @@ describe("buildConfigChain", function () {
});
const expected = [
{
options: {
plugins: [
"json",
],
},
alias: fixture("json-pkg-config-no-babel", ".babelrc"),
loc: fixture("json-pkg-config-no-babel", ".babelrc"),
dirname: fixture("json-pkg-config-no-babel"),
},
{
options: {
ignore: [
@@ -455,6 +445,16 @@ describe("buildConfigChain", function () {
loc: fixture(".babelignore"),
dirname: fixture(),
},
{
options: {
plugins: [
"json",
],
},
alias: fixture("json-pkg-config-no-babel", ".babelrc"),
loc: fixture("json-pkg-config-no-babel", ".babelrc"),
dirname: fixture("json-pkg-config-no-babel"),
},
{
options: {
filename: fixture("json-pkg-config-no-babel", "src.js"),

View File

@@ -98,7 +98,8 @@ export default function ({ types: t }) {
}
});
const moduleNameOrBasename = moduleName ? moduleName.value : this.file.opts.basename;
const moduleNameOrBasename = moduleName ? moduleName.value :
basename(this.file.opts.filename, extname(this.file.opts.filename));
let globalToAssign = t.memberExpression(
t.identifier("global"), t.identifier(t.toIdentifier(moduleNameOrBasename))
);

View File

@@ -42,7 +42,7 @@ export default function ({ types: t }) {
visitor: {
ExportDefaultDeclaration({ node }, state) {
if (isCreateClass(node.declaration)) {
let displayName = state.file.opts.basename;
let displayName = path.basename(state.file.opts.filename, path.extname(state.file.opts.filename));
// ./{module name}/index.js
if (displayName === "index") {

View File

@@ -45,9 +45,7 @@ export default function ({ types: t }) {
}
if (!state.fileNameIdentifier) {
const fileName = state.file.log.filename !== "unknown"
? state.file.log.filename
: null;
const fileName = state.file.opts.filename;
const fileNameIdentifier = path.scope.generateUidIdentifier(FILE_NAME_VAR);
path.hub.file.scope.push({ id: fileNameIdentifier, init: t.stringLiteral(fileName) });