Add braces to every if/for(-in)/while statement in tools directory.

This commit is contained in:
Ben Newman
2015-11-13 12:09:06 -05:00
parent 739d0d9676
commit ed17924940
60 changed files with 1466 additions and 727 deletions

View File

@@ -48,7 +48,9 @@ main.registerCommand({
}
}
if (buildmessage.jobHasMessages()) return;
if (buildmessage.jobHasMessages()) {
return;
}
const cordovaProject = new CordovaProject(projectContext);
@@ -56,7 +58,9 @@ main.registerCommand({
const cordovaPlatforms = cordova.filterPlatforms(installedPlatforms);
cordovaProject.ensurePlatformsAreSynchronized(cordovaPlatforms);
if (buildmessage.jobHasMessages()) return;
if (buildmessage.jobHasMessages()) {
return;
}
// Only write the new platform list when we have succesfully synchronized
projectContext.platformList.write(installedPlatforms);
@@ -92,7 +96,9 @@ version of Meteor`);
}
}
if (buildmessage.jobHasMessages()) return;
if (buildmessage.jobHasMessages()) {
return;
}
installedPlatforms = _.without(installedPlatforms, ...platformsToRemove);
projectContext.platformList.write(installedPlatforms);

View File

@@ -39,7 +39,9 @@ var getReleaseVersionPublishedOn = function (versionRecord) {
var toolName = toolPackage[0];
var toolVersion = toolPackage[1];
var toolRecord = catalog.official.getVersion(toolName, toolVersion);
if (! toolRecord || ! toolRecord.published) return null;
if (! toolRecord || ! toolRecord.published) {
return null;
}
return new Date(toolRecord.published);
};
@@ -243,8 +245,9 @@ _.extend(PkgExports.prototype, {
var strExports = _.map(self.data, function (exp) {
// If this export is valid for all architectures, don't specify
// architectures here.
if (exp.architectures.length === compiler.ALL_ARCHES.length)
if (exp.architectures.length === compiler.ALL_ARCHES.length) {
return exp.name;
}
// Don't split descriptions of individual pkgExports between lines.
return Console.noWrap(
@@ -269,7 +272,9 @@ var PkgImplies = function (pkgDeps) {
// and save their architectures. Also, we want to replace 'os' with
// 'server', as with exports.
_.each(ref.references, function (r) {
if (! r.implied) return;
if (! r.implied) {
return;
}
var archName = (r.arch === "os") ? "server" : r.arch;
architectures.push(archName);
});
@@ -294,8 +299,9 @@ _.extend(PkgImplies.prototype, {
var self = this;
var strImplies = _.map(self.data, function (ref) {
// If an imply is valid for all architectures, don't specify it here.
if (ref["architectures"].length === compiler.ALL_ARCHES.length)
if (ref["architectures"].length === compiler.ALL_ARCHES.length) {
return ref.name;
}
// Don't split descriptions of individual implies between lines.
return Console.noWrap(
@@ -638,7 +644,9 @@ _.extend(PackageQuery.prototype, {
if (self.showArchitecturesOS) {
var allBuilds = catalog.official.getAllBuilds(self.name, version);
var architectures = _.map(allBuilds, function (build) {
if (! build['buildArchitectures']) return "unknown";
if (! build['buildArchitectures']) {
return "unknown";
}
var archOS =
_.filter(build.buildArchitectures.split('+'), function (arch) {
return ( arch !== "web.browser" ) && ( arch !== "web.cordova" );
@@ -1493,8 +1501,9 @@ main.registerCommand({
var filterBroken = function (match, isRelease, name) {
// If the package does not match, or it is not a package at all or if we
// don't want to filter anyway, we do not care.
if (!match || isRelease)
if (!match || isRelease) {
return match;
}
var vr;
if (!options["show-all"]) {
// If we can't find a version in the local catalog, we want to get the

View File

@@ -38,8 +38,9 @@ var getReleaseOrPackageRecord = function(name) {
if (!rec) {
// Not a package! But is it a release track?
rec = catalog.official.getReleaseTrack(name);
if (rec)
if (rec) {
rel = true;
}
}
return { record: rec, isRelease: rel };
};
@@ -330,8 +331,9 @@ main.registerCommand({
}
var packageName = localVersionRecord.packageName;
var packageSource = projectContext.localCatalog.getPackageSource(packageName);
if (! packageSource)
if (! packageSource) {
throw Error("no PackageSource for " + packageName);
}
// Anything published to the server must explicitly set a version.
if (! packageSource.versionExplicitlyProvided) {
@@ -385,8 +387,9 @@ main.registerCommand({
}
// If we're already using this package, that's OK; no need to override.
if (projectContext.projectConstraintsFile.getConstraint(name))
if (projectContext.projectConstraintsFile.getConstraint(name)) {
return;
}
projectContext.projectConstraintsFile.addConstraints(
[utils.parsePackageConstraint(name)]);
});
@@ -655,8 +658,9 @@ main.registerCommand({
});
var isopk = projectContext.isopackCache.getIsopack(name);
if (! isopk)
if (! isopk) {
throw Error("didn't build isopack for " + name);
}
var conn;
try {
@@ -873,8 +877,9 @@ main.registerCommand({
buildmessage.enterJob("checking consistency of " + packageName, function () {
var packageSource = projectContext.localCatalog.getPackageSource(
packageName);
if (! packageSource)
if (! packageSource) {
throw Error("no PackageSource for built package " + packageName);
}
if (! packageSource.versionExplicitlyProvided) {
buildmessage.error(
@@ -914,8 +919,9 @@ main.registerCommand({
return;
} else {
var isopk = projectContext.isopackCache.getIsopack(packageName);
if (! isopk)
if (! isopk) {
throw Error("no isopack for " + packageName);
}
var existingBuild =
catalog.official.getBuildWithPreciseBuildArchitectures(
@@ -957,12 +963,14 @@ main.registerCommand({
"publishing package " + packageName,
function () {
var isopk = projectContext.isopackCache.getIsopack(packageName);
if (! isopk)
if (! isopk) {
throw Error("no isopack for " + packageName);
}
var packageSource = projectContext.localCatalog.getPackageSource(
packageName);
if (! packageSource)
if (! packageSource) {
throw Error("no PackageSource for built package " + packageName);
}
var binary = isopk.platformSpecific();
packageClient.publishPackage({
@@ -972,8 +980,9 @@ main.registerCommand({
new: ! catalog.official.getPackage(packageName),
doNotPublishBuild: binary
});
if (buildmessage.jobHasMessages())
if (buildmessage.jobHasMessages()) {
return;
}
Console.info(
'Published ' + packageName + '@' + packageSource.version + '.');
@@ -1003,8 +1012,9 @@ main.registerCommand({
packageClient.callPackageServerBM(
conn, 'createReleaseTrack', { name: relConf.track } );
});
if (buildmessage.jobHasMessages())
if (buildmessage.jobHasMessages()) {
return;
}
}
buildmessage.enterJob("creating a new release version", function () {
@@ -1122,12 +1132,14 @@ main.registerCommand({
var packageName = constraint.package;
// Skip isobuild:* pseudo-packages.
if (compiler.isIsobuildFeaturePackage(packageName))
if (compiler.isIsobuildFeaturePackage(packageName)) {
return;
}
var mapInfo = projectContext.packageMap.getInfo(packageName);
if (! mapInfo)
if (! mapInfo) {
throw Error("no version for used package " + packageName);
}
var versionRecord = projectContext.projectCatalog.getVersion(
packageName, mapInfo.version);
if (! versionRecord) {
@@ -1309,8 +1321,9 @@ var maybeUpdateRelease = function (options) {
// At this point we should have a release. (If we didn't to start
// with, #UpdateSpringboard fixed that.) And it can't be a checkout,
// because we checked for that at the very beginning.
if (! release.current || ! release.current.isProperRelease())
if (! release.current || ! release.current.isProperRelease()) {
throw new Error("don't have a proper release?");
}
// If we're not in an app, then we're basically done. The only thing left to
// do is print out some messages explaining what happened (and advising the
@@ -1452,8 +1465,9 @@ var maybeUpdateRelease = function (options) {
var solutionReleaseVersion = _.find(releaseVersionsToTry, function (versionToTry) {
var releaseRecord = catalog.official.getReleaseVersion(
releaseTrack, versionToTry);
if (!releaseRecord)
if (!releaseRecord) {
throw Error("missing release record?");
}
// Reset the project context and pretend we're using the potential release.
projectContext.reset({ releaseForConstraints: releaseRecord });
@@ -1611,8 +1625,9 @@ main.registerCommand({
var upgradeIndirectDepPatchVersions = false;
if (options.args.length === 0) {
projectContext.projectConstraintsFile.eachConstraint(function (constraint) {
if (! compiler.isIsobuildFeaturePackage(constraint.package))
if (! compiler.isIsobuildFeaturePackage(constraint.package)) {
upgradePackageNames.push(constraint.package);
}
});
upgradeIndirectDepPatchVersions = true;
} else {
@@ -1645,8 +1660,9 @@ main.registerCommand({
main.captureAndExit(
"=> Errors while upgrading packages:", "upgrading packages", function () {
projectContext.resolveConstraints();
if (buildmessage.jobHasMessages())
if (buildmessage.jobHasMessages()) {
return;
}
// If the user explicitly mentioned some packages to upgrade, they must
// actually end up in our solution!
@@ -1655,8 +1671,9 @@ main.registerCommand({
buildmessage.error(packageName + ': package is not in the project');
}
});
if (buildmessage.jobHasMessages())
if (buildmessage.jobHasMessages()) {
return;
}
// Finish preparing the project.
projectContext.prepareProjectForBuild();
@@ -1894,7 +1911,9 @@ main.registerCommand({
changed && projectContext.cordovaPluginsFile.write(plugins);
}
if (_.isEmpty(packagesToAdd)) return exitCode;
if (_.isEmpty(packagesToAdd)) {
return exitCode;
}
// Messages that we should print if we make any changes, but that don't count
// as errors.
@@ -1910,8 +1929,9 @@ main.registerCommand({
var constraint = utils.parsePackageConstraint(packageReq, {
useBuildmessage: true
});
if (buildmessage.jobHasMessages())
if (buildmessage.jobHasMessages()) {
return;
}
// It's OK to make errors based on looking at the catalog, because this
// is a OnceAtStart command.
@@ -1923,8 +1943,9 @@ main.registerCommand({
}
_.each(constraint.versionConstraint.alternatives, function (subConstr) {
if (subConstr.versionString === null)
if (subConstr.versionString === null) {
return;
}
// Figure out if this version exists either in the official catalog or
// the local catalog. (This isn't the same as using the combined
// catalog, since it's OK to type "meteor add foo@1.0.0" if the local
@@ -1942,8 +1963,9 @@ main.registerCommand({
subConstr.versionString);
}
});
if (buildmessage.jobHasMessages())
if (buildmessage.jobHasMessages()) {
return;
}
var current = projectContext.projectConstraintsFile.getConstraint(
constraint.package);
@@ -2082,7 +2104,9 @@ main.registerCommand({
changed && projectContext.cordovaPluginsFile.write(plugins);
}
if (_.isEmpty(packages)) return exitCode;
if (_.isEmpty(packages)) {
return exitCode;
}
// For each package name specified, check if we already have it and warn the
// user. Because removing each package is a completely atomic operation that
@@ -2102,8 +2126,9 @@ main.registerCommand({
packagesToRemove.push(packageName);
}
});
if (! packagesToRemove.length)
if (! packagesToRemove.length) {
return exitCode;
}
// Remove the packages from the in-memory representation of .meteor/packages.
projectContext.projectConstraintsFile.removePackages(packagesToRemove);
@@ -2230,10 +2255,11 @@ main.registerCommand({
Console.info();
Console.info("The maintainers for " + name + " are:");
_.each(record.maintainers, function (user) {
if (! user || !user.username)
if (! user || !user.username) {
Console.rawInfo("<unknown>" + "\n");
else
} else {
Console.rawInfo(user.username + "\n");
}
});
return 0;
});
@@ -2280,8 +2306,9 @@ main.registerCommand({
var toolPackageVersion = releaseRecord.tool &&
utils.parsePackageAndVersion(releaseRecord.tool);
if (!toolPackageVersion)
if (!toolPackageVersion) {
throw new Error("bad tool in release: " + releaseRecord.tool);
}
var toolPackage = toolPackageVersion.package;
var toolVersion = toolPackageVersion.version;
@@ -2416,8 +2443,9 @@ main.registerCommand({
var toolIsopack = new isopack.Isopack;
toolIsopack.initFromPath(toolPackage, toolIsopackPath);
var toolRecord = _.findWhere(toolIsopack.toolsOnDisk, {arch: osArch});
if (!toolRecord)
if (!toolRecord) {
throw Error("missing tool for " + osArch);
}
tmpTropo.linkToLatestMeteor(files.pathJoin(
tmpTropo.packagePath(toolPackage, toolVersion, true),

View File

@@ -52,10 +52,12 @@ var __dirnameConverted = files.convertToStandardPath(__dirname);
// In the future, you should be able to make this default to some
// other domain you control, rather than 'meteor.com'.
var qualifySitename = function (site) {
if (site.indexOf(".") === -1)
if (site.indexOf(".") === -1) {
site = site + ".meteor.com";
while (site.length && site[site.length - 1] === ".")
}
while (site.length && site[site.length - 1] === ".") {
site = site.substring(0, site.length - 1);
}
return site;
};
@@ -187,8 +189,9 @@ main.registerCommand({
catalogRefresh: new catalog.Refresh.Never()
}, function (options) {
if (release.current === null) {
if (! options.appDir)
if (! options.appDir) {
throw new Error("missing release, but not in an app?");
}
Console.error(
"This project was created with a checkout of Meteor, rather than an " +
"official release, and doesn't have a release number associated with " +
@@ -323,8 +326,9 @@ function doRunCommand(options) {
appPort = appPortMatch[2] ? parseInt(appPortMatch[2]) : null;
}
if (options['raw-logs'])
if (options['raw-logs']) {
runLog.setRawLogs(true);
}
// Velocity testing. Sets up a DDP connection to the app process and
// runs phantomjs.
@@ -516,10 +520,11 @@ main.registerCommand({
return transform(f);
},
transformContents: function (contents, f) {
if ((/(\.html|\.js|\.css)/).test(f))
if ((/(\.html|\.js|\.css)/).test(f)) {
return new Buffer(transform(contents.toString()));
else
} else {
return contents;
}
},
ignore: [/^local$/]
});
@@ -578,12 +583,13 @@ main.registerCommand({
};
var appPathAsEntered;
if (options.args.length === 1)
if (options.args.length === 1) {
appPathAsEntered = options.args[0];
else if (options.example)
} else if (options.example) {
appPathAsEntered = options.example;
else
} else {
throw new main.ShowUsage;
}
var appPath = files.pathResolve(appPathAsEntered);
if (files.findAppDir(appPath)) {
@@ -682,10 +688,11 @@ ${nonCodeFileExts.join(', ')}
return transform(f);
},
transformContents: function (contents, f) {
if ((/(\.html|\.js|\.css)/).test(f))
if ((/(\.html|\.js|\.css)/).test(f)) {
return new Buffer(transform(contents.toString()));
else
} else {
return contents;
}
},
ignore: toIgnore
});
@@ -704,13 +711,15 @@ ${nonCodeFileExts.join(', ')}
main.captureAndExit("=> Errors while creating your project", function () {
projectContext.readProjectMetadata();
if (buildmessage.jobHasMessages())
if (buildmessage.jobHasMessages()) {
return;
}
projectContext.releaseFile.write(
release.current.isCheckout() ? "none" : release.current.name);
if (buildmessage.jobHasMessages())
if (buildmessage.jobHasMessages()) {
return;
}
// Any upgrader that is in this version of Meteor doesn't need to be run on
// this project.
@@ -934,8 +943,9 @@ on an OS X system.");
return 1;
}
if (! options._serverOnly)
if (! options._serverOnly) {
files.mkdir_p(outputPath);
}
if (! options.directory) {
main.captureAndExit('', 'creating server tarball', () => {
@@ -971,7 +981,9 @@ on an OS X system.");
{ title: `building Cordova app for \
${cordova.displayNameForPlatform(platform)}` }, () => {
let buildOptions = [];
if (!options.debug) buildOptions.push('--release');
if (!options.debug) {
buildOptions.push('--release');
}
cordovaProject.buildForPlatform(platform, buildOptions);
const buildPath = files.pathJoin(
@@ -1154,15 +1166,17 @@ to this command.`);
mongoUrl = deploy.temporaryMongoUrl(site);
usedMeteorAccount = true;
if (! mongoUrl)
if (! mongoUrl) {
// temporaryMongoUrl() will have printed an error message
return 1;
}
}
if (options.url) {
console.log(mongoUrl);
} else {
if (usedMeteorAccount)
if (usedMeteorAccount) {
auth.maybePrintRegistrationLink();
}
process.stdin.pause();
var runMongo = require('../runners/run-mongo.js');
runMongo.runMongoShell(mongoUrl);
@@ -1263,8 +1277,9 @@ main.registerCommand({
"To instantly deploy your app on a free testing server,",
"just enter your email address!");
Console.error();
if (! auth.registerOrLogIn())
if (! auth.registerOrLogIn()) {
return 1;
}
}
// Override architecture iff applicable.
@@ -1375,12 +1390,13 @@ main.registerCommand({
return 1;
}
if (options.add)
if (options.add) {
return deploy.changeAuthorized(site, "add", options.add);
else if (options.remove)
} else if (options.remove) {
return deploy.changeAuthorized(site, "remove", options.remove);
else
} else {
return deploy.listAuthorized(site);
}
});
///////////////////////////////////////////////////////////////////////////////
@@ -1499,8 +1515,9 @@ main.registerCommand({
// Download packages for our architecture, and for the deploy server's
// architecture if we're deploying.
var serverArchitectures = [archinfo.host()];
if (options.deploy && DEPLOY_ARCH !== archinfo.host())
if (options.deploy && DEPLOY_ARCH !== archinfo.host()) {
serverArchitectures.push(DEPLOY_ARCH);
}
// XXX Because every run uses a new app with its own IsopackCache directory,
// this always does a clean build of all packages. Maybe we can speed up
@@ -1940,8 +1957,9 @@ main.registerCommand({
try {
require('../utils/http-helpers.js').getUrl("http://www.google.com/");
} catch (e) {
if (e instanceof files.OfflineError)
if (e instanceof files.OfflineError) {
offline = true;
}
}
}
@@ -1949,8 +1967,9 @@ main.registerCommand({
try {
return new RegExp(str);
} catch (e) {
if (!(e instanceof SyntaxError))
if (!(e instanceof SyntaxError)) {
throw e;
}
Console.error("Bad regular expression: " + str);
return null;
}
@@ -2250,17 +2269,20 @@ main.registerCommand({
catalogRefresh: new catalog.Refresh.Never()
}, function (options) {
var p = function (key) {
if (_.has(options, key))
if (_.has(options, key)) {
return JSON.stringify(options[key]);
}
return 'none';
};
Console.info(p('ething') + " " + p('port') + " " + p('changed') +
" " + p('args'));
if (options.url)
if (options.url) {
Console.info('url');
if (options['delete'])
}
if (options['delete']) {
Console.info('delete');
}
});
///////////////////////////////////////////////////////////////////////////////

View File

@@ -1,6 +1,7 @@
var showRequireProfile = ('METEOR_PROFILE_REQUIRE' in process.env);
if (showRequireProfile)
if (showRequireProfile) {
require('../tool-env/profile-require.js').start();
}
var assert = require("assert");
var _ = require('underscore');
@@ -54,26 +55,32 @@ function Command(options) {
notOnWindows: false
}, options);
if (! _.has(options, 'maxArgs'))
if (! _.has(options, 'maxArgs')) {
options.maxArgs = options.minArgs;
}
_.each(["name", "func"], function (key) {
if (! _.has(options, key))
if (! _.has(options, key)) {
throw new Error("command missing '" + key + "'?");
}
});
_.extend(this, options);
_.each(this.options, function (value, key) {
if (key === "args" || key === "appDir")
if (key === "args" || key === "appDir") {
throw new Error(options.name + ": bad option name " + key);
if (! _.has(value, 'type'))
}
if (! _.has(value, 'type')) {
value.type = String;
if (_.has(value, 'default') && _.has(value, 'required'))
}
if (_.has(value, 'default') && _.has(value, 'required')) {
throw new Error(options.name + ": " + key + " can't be both optional " +
"and required");
if (_.has(value, 'short') && value.short.length !== 1)
}
if (_.has(value, 'short') && value.short.length !== 1) {
throw new Error(options.name + ": " + key + " has a bad short option");
}
});
};
@@ -82,8 +89,9 @@ function Command(options) {
// command-line options object.
Command.prototype.evaluateOption = function (optionName, options) {
var self = this;
if (typeof self[optionName] === 'function')
if (typeof self[optionName] === 'function') {
return self[optionName](options);
}
return self[optionName];
};
@@ -245,8 +253,9 @@ main.registerCommand = function (options, func) {
var target = commands;
while (nameParts.length > 1) {
var part = nameParts.shift();
if (! _.has(target, part))
if (! _.has(target, part)) {
target[part] = {};
}
target = target[part];
}
@@ -313,8 +322,9 @@ var longHelp = exports.longHelp = function (commandName) {
var parts = commandName.length ? commandName.split(' ') : [];
var node = commands;
_.each(parts, function (part) {
if (! _.has(node, part))
if (! _.has(node, part)) {
throw new Error("walked off edge of command tree?");
}
node = node[part];
});
@@ -339,8 +349,9 @@ var longHelp = exports.longHelp = function (commandName) {
// there is nothing to display.
// For now, there's no way to mark commands with subcommands (eg 'admin')
// as hidden.
if (! n.hidden && helpDict[fullName])
if (! n.hidden && helpDict[fullName]) {
commandsWanted[fullName] = { name: shortName };
}
});
var maxNameLength = _.max(_.map(commandsWanted, function (c) {
@@ -366,11 +377,13 @@ var longHelp = exports.longHelp = function (commandName) {
var entry = _.find(help, function (c) {
return c.name === commandName;
});
if (! entry)
if (! entry) {
throw new Error("help missing for " + commandName + "?");
}
var ret = entry.body.split('\n').slice(1).join('\n');
if (commandList !== null)
if (commandList !== null) {
ret = ret.replace('{{commands}}', commandList);
}
return ret;
};
@@ -392,8 +405,9 @@ var longHelp = exports.longHelp = function (commandName) {
// release. affects error messages.
var springboard = function (rel, options) {
options = options || {};
if (process.env.METEOR_DEBUG_SPRINGBOARD)
if (process.env.METEOR_DEBUG_SPRINGBOARD) {
console.log("WILL SPRINGBOARD TO", rel.getToolsPackageAtVersion());
}
var archinfo = require('../utils/archinfo.js');
var isopack = require('../isobuild/isopack.js');
@@ -457,9 +471,10 @@ var springboard = function (rel, options) {
toolIsopack.initFromPath(toolsPkg, packagePath);
var toolRecord = _.findWhere(toolIsopack.toolsOnDisk,
{arch: archinfo.host()});
if (!toolRecord)
if (!toolRecord) {
throw Error("missing tool for " + archinfo.host() + " in " +
toolsPkg + "@" + toolsVersion);
}
var executable = files.pathJoin(packagePath, toolRecord.path, 'meteor');
// Strip off the "node" and "meteor.js" from argv and replace it with the
@@ -592,8 +607,9 @@ Fiber(function () {
if (value instanceof Command) {
_.each(value.options || {}, function (optionInfo, optionName) {
var names = ["--" + optionName];
if (_.has(optionInfo, 'short'))
if (_.has(optionInfo, 'short')) {
names.push("-" + optionInfo.short);
}
_.each(names, function (name) {
var optionIsBoolean = (optionInfo.type === Boolean);
if (_.has(isBoolean, name)) {
@@ -619,8 +635,9 @@ Fiber(function () {
// a little weird but it feels good and it follows a grand Unix
// tradition.
_.each(commands['--'] || {}, function (value, key) {
if (_.has(isBoolean, "--" + key))
if (_.has(isBoolean, "--" + key)) {
throw new Error("--" + key + " is both an option and a command?");
}
isBoolean["--" + key] = true;
});
@@ -660,8 +677,9 @@ Fiber(function () {
term = term.substr(0, equals);
}
if (! _.has(rawOptions, term))
if (! _.has(rawOptions, term)) {
rawOptions[term] = [];
}
// Save off the value of the option. true for (known) booleans,
// null if value is missing, else a string. Don't try to
@@ -686,8 +704,9 @@ Fiber(function () {
// in place into '-a -b -c', '-p 45', '-a -b -c -p 45'. Not that
// anyone really talks this way anymore.
if (term.match(/^-/)) {
if (term.match(/^-[-=]?$/))
if (term.match(/^-[-=]?$/)) {
throw Error("these cases should be handled above?");
}
var replacements = [];
for (var j = 1; j < term.length; j++) {
@@ -701,8 +720,9 @@ Fiber(function () {
if (remainder.length) {
// If there's an '=' here, don't include it in the option value. A
// trailing '=' *should* cause us to set the option value to ''.
if (remainder.charAt(0) === '=')
if (remainder.charAt(0) === '=') {
remainder = remainder.substr(1);
}
replacements.push(remainder);
break;
}
@@ -710,8 +730,9 @@ Fiber(function () {
j + 1 < term.length && term.charAt(j + 1) === '=') {
// We know it's a boolean, but we've been given an '='. This will
// cause a pretty error later.
if (! _.has(rawOptions, subterm))
if (! _.has(rawOptions, subterm)) {
rawOptions[subterm] = [];
}
rawOptions[subterm].push(false);
// Don't process the '=' on the next pass.
j ++;
@@ -898,13 +919,15 @@ Fiber(function () {
try {
rel = release.load(releaseName);
} catch (e) {
if (!(e instanceof release.NoSuchReleaseError))
if (!(e instanceof release.NoSuchReleaseError)) {
throw e;
}
}
if (!rel) {
if (releaseName === null)
if (releaseName === null) {
throw Error("huh? couldn't load from-checkout release?");
}
// ATTEMPT 2: legacy release, on disk. (And it's a "real" release, not a
// "red pill" release which has the same name as a modern release!)
@@ -1072,8 +1095,9 @@ Fiber(function () {
if (! showHelp) {
command = commands.run
commandName = "run";
if (! command)
if (! command) {
throw new Error("no 'run' command?");
}
}
} else {
// Find the command they specified.
@@ -1163,10 +1187,12 @@ Fiber(function () {
// long and short versions, and across possibly multiple
// occurrences of the option on the command line
var values = [];
if (presentLong)
if (presentLong) {
values = values.concat(rawOptions["--" + optionName]);
if (presentShort)
}
if (presentShort) {
values = values.concat(rawOptions["-" + optionInfo.short]);
}
if (values.length > 1) {
// in the future, we could support multiple values, but we don't
@@ -1218,10 +1244,12 @@ Fiber(function () {
// Remove from the list of input arguments so that later we can
// detect unrecognized arguments.
if (presentLong)
if (presentLong) {
delete rawOptions["--" + optionName];
if (presentShort)
}
if (presentShort) {
delete rawOptions["-" + optionInfo.short];
}
} else {
// Option not supplied. Throw an error if it was required,
// supply a default value if one is defined, or just leave it
@@ -1311,8 +1339,9 @@ Fiber(function () {
if (requiresPackage || usesPackage || requiresAppOrPackage) {
var packageDir = files.findPackageDir();
if (packageDir)
if (packageDir) {
packageDir = files.pathResolve(packageDir);
}
if (packageDir) {
options.packageDir = packageDir;
}
@@ -1354,8 +1383,9 @@ Fiber(function () {
// Now that we're ready to start executing the command, if we are in
// startup time profiling mode, print the profile.
if (showRequireProfile)
if (showRequireProfile) {
require('../tool-env/profile-require.js').printReport();
}
Console.setPretty(command.evaluateOption('pretty', options));
Console.enableProgressDisplay(true);
@@ -1416,9 +1446,11 @@ Fiber(function () {
// Exit. (We will not get here if the command threw an exception
// such as main.WaitForExit).
if (ret === undefined)
if (ret === undefined) {
ret = 0;
if (typeof ret !== "number")
}
if (typeof ret !== "number") {
throw new Error("command returned non-number?");
}
process.exit(ret);
}).run();

View File

@@ -584,11 +584,13 @@ _.extend(Console.prototype, {
setPretty: function (pretty) {
var self = this;
// If we're being forced, do nothing.
if (FORCE_PRETTY !== undefined)
if (FORCE_PRETTY !== undefined) {
return;
}
// If no change, do nothing.
if (self._pretty === pretty)
if (self._pretty === pretty) {
return;
}
self._pretty = pretty;
self._updateProgressDisplay();
},
@@ -604,8 +606,9 @@ _.extend(Console.prototype, {
self._pretty = self._progressDisplayEnabled = true;
// Update the screen if anything changed.
if (! originalPretty || ! originalProgressDisplayEnabled)
if (! originalPretty || ! originalProgressDisplayEnabled) {
self._updateProgressDisplay();
}
try {
return f();
@@ -614,8 +617,9 @@ _.extend(Console.prototype, {
self._pretty = originalPretty;
self._progressDisplayEnabled = originalProgressDisplayEnabled;
// Update the screen if anything changed.
if (! originalPretty || ! originalProgressDisplayEnabled)
if (! originalPretty || ! originalProgressDisplayEnabled) {
self._updateProgressDisplay();
}
}
},
@@ -640,8 +644,9 @@ _.extend(Console.prototype, {
// relies on the previous chars to be erasable with '\b' (end-line chars
// can't be erased this way). This is why we report a smaller number than it
// is in reality, for safety.
if (process.platform === 'win32')
if (process.platform === 'win32') {
width -= 5;
}
return width;
},
@@ -1080,8 +1085,9 @@ _.extend(Console.prototype, {
var longest = '';
_.each(rows, function (row) {
var col0 = row[0] || '';
if (col0.length > longest.length)
if (col0.length > longest.length) {
longest = col0;
}
});
var pad = longest.replace(/./g, ' ');
@@ -1149,8 +1155,9 @@ _.extend(Console.prototype, {
wrappedText = text;
}
wrappedText = _.map(wrappedText.split('\n'), function (s) {
if (s === "")
if (s === "") {
return "";
}
return indent + s;
}).join('\n');
@@ -1186,8 +1193,9 @@ _.extend(Console.prototype, {
enabled = true;
}
if (self._progressDisplayEnabled === enabled)
if (self._progressDisplayEnabled === enabled) {
return;
}
self._progressDisplayEnabled = enabled;
self._updateProgressDisplay();
@@ -1292,8 +1300,9 @@ Console.prototype.readLine = function (options) {
rl.on('line', function (line) {
rl.close();
if (! options.echo)
if (! options.echo) {
options.stream.write("\n");
}
self._setProgressDisplay(previousProgressDisplay);
fut['return'](line);
});

View File

@@ -234,8 +234,9 @@ export class CordovaBuilder {
// Copy all the access rules
_.each(this.accessRules, (rule, pattern) => {
var opts = { origin: pattern };
if (rule === 'external')
if (rule === 'external') {
opts['launch-external'] = true;
}
config.element('access', opts);
});
@@ -298,8 +299,9 @@ export class CordovaBuilder {
const [width, height] = size.split('x');
const suppliedPath = this.imagePaths[tag][name];
if (!suppliedPath)
if (!suppliedPath) {
return;
}
const suppliedFilename = _.last(suppliedPath.split(files.pathSep));
let extension = _.last(suppliedFilename.split('.'));
@@ -405,8 +407,9 @@ export class CordovaBuilder {
appId: this.projectContext.appIdentifier
};
if (publicSettings)
if (publicSettings) {
runtimeConfig.PUBLIC_SETTINGS = publicSettings;
}
const { Boilerplate } =
isopackets.load('cordova-support')['boilerplate-generator'];
@@ -453,8 +456,9 @@ function createAppConfiguration(builder) {
info: function (options) {
// check that every key is meaningful
_.each(options, function (value, key) {
if (!_.has(builder.metadata, key))
if (!_.has(builder.metadata, key)) {
throw new Error("Unknown key in App.info configuration: " + key);
}
});
_.extend(builder.metadata, options);
@@ -515,8 +519,9 @@ Valid platforms are: ios, android.`);
var validDevices =
_.keys(iconsIosSizes).concat(_.keys(iconsAndroidSizes));
_.each(icons, function (value, key) {
if (!_.include(validDevices, key))
if (!_.include(validDevices, key)) {
throw new Error(key + ": unknown key in App.icons configuration.");
}
});
_.extend(builder.imagePaths.icon, icons);
},
@@ -558,8 +563,9 @@ Valid platforms are: ios, android.`);
_.keys(launchIosSizes).concat(_.keys(launchAndroidSizes));
_.each(launchScreens, function (value, key) {
if (!_.include(validDevices, key))
if (!_.include(validDevices, key)) {
throw new Error(key + ": unknown key in App.launchScreens configuration.");
}
});
_.extend(builder.imagePaths.splash, launchScreens);
},

View File

@@ -76,11 +76,15 @@ yet supported.`);
const outdated = _.some(minPlatformVersions, (minVersion, platform) => {
// If the platform is not installed, it cannot be outdated
if (!_.contains(installedPlatforms, platform)) return false;
if (!_.contains(installedPlatforms, platform)) {
return false;
}
const installedVersion = this.installedVersionForPlatform(platform);
// If we cannot establish the installed version, we consider it outdated
if (!installedVersion) return true;
if (!installedVersion) {
return true;
}
return semver.lt(installedVersion, minVersion);
});
@@ -116,7 +120,9 @@ outdated platforms`);
builder.processControlFile();
if (buildmessage.jobHasMessages()) return;
if (buildmessage.jobHasMessages()) {
return;
}
// Don't copy resources (they will be copied as part of the prepare)
builder.writeConfigXmlAndCopyResources(false);
@@ -153,7 +159,9 @@ outdated platforms`);
builder.processControlFile();
if (buildmessage.jobHasMessages()) return;
if (buildmessage.jobHasMessages()) {
return;
}
builder.writeConfigXmlAndCopyResources();
builder.copyWWW(bundlePath);
@@ -345,7 +353,9 @@ from Cordova project`, async () => {
const installedPlatforms = this.listInstalledPlatforms();
for (platform of platforms) {
if (_.contains(installedPlatforms, platform)) continue;
if (_.contains(installedPlatforms, platform)) {
continue;
}
this.addPlatform(platform);
}
@@ -461,7 +471,9 @@ to Cordova project`, async () => {
// plugins is an array of plugin IDs.
removePlugins(plugins) {
if (_.isEmpty(plugins)) return;
if (_.isEmpty(plugins)) {
return;
}
this.runCommands(`removing plugins ${plugins} \
from Cordova project`, async () => {
@@ -487,7 +499,9 @@ from Cordova project`, async () => {
// SHA reference.
pluginVersions = convertPluginVersions(pluginVersions);
if (buildmessage.jobHasMessages()) return;
if (buildmessage.jobHasMessages()) {
return;
}
// Also, we warn if any App.configurePlugin calls in mobile-config.js
// need to be updated (and in the meantime we take care of the

View File

@@ -161,7 +161,9 @@ export class AndroidRunTarget extends CordovaRunTarget {
function logFromAndroidLogcatLine(Log, line) {
// Ignore lines indicating beginning of logging
if (line.match(/^--------- beginning of /)) return null;
if (line.match(/^--------- beginning of /)) {
return null;
}
// Matches logcat brief format
// "I/Tag( PID): message"
@@ -209,7 +211,9 @@ function logFromAndroidLogcatLine(Log, line) {
};
function logFromConsoleOutput(Log, message, filename, lineNumber) {
if (isDebugOutput(message) && !Console.verbose) return null;
if (isDebugOutput(message) && !Console.verbose) {
return null;
}
filename = filename.replace(/\?.*$/, '');

View File

@@ -78,7 +78,9 @@ export class CordovaRunner {
this.cordovaProject.prepareFromAppBundle(bundlePath,
pluginVersions, options);
if (buildmessage.jobHasMessages()) return;
if (buildmessage.jobHasMessages()) {
return;
}
for (platform of this.platformsForRunTargets) {
this.cordovaProject.prepareForPlatform(platform);
@@ -107,7 +109,9 @@ export class CordovaRunner {
havePlatformsChangedSinceLastRun() {
const platformsForRunTargets = this.platformsForRunTargets;
if (!platformsForRunTargets) return false;
if (!platformsForRunTargets) {
return false;
}
const cordovaPlatformsInApp = this.cordovaProject.cordovaPlatformsInApp;

View File

@@ -67,8 +67,9 @@ var findUpwards = function (predicate, startPath) {
testDir = newDir;
}
}
if (!testDir)
if (!testDir) {
return null;
}
return testDir;
};
@@ -124,7 +125,9 @@ files.addToGitignore = function (dirPath, entry) {
// already there do nothing
} else {
// rewrite file w/ new entry.
if (data.substr(-1) !== "\n") data = data + "\n";
if (data.substr(-1) !== "\n") {
data = data + "\n";
}
data = data + entry + "\n";
files.writeFile(filepath, data, 'utf8');
}
@@ -137,8 +140,9 @@ files.addToGitignore = function (dirPath, entry) {
// Are we running Meteor from a git checkout?
files.inCheckout = _.once(function () {
try {
if (files.exists(files.pathJoin(files.getCurrentToolsDir(), '.git')))
if (files.exists(files.pathJoin(files.getCurrentToolsDir(), '.git'))) {
return true;
}
} catch (e) { console.log(e); }
return false;
@@ -150,10 +154,11 @@ files.inCheckout = _.once(function () {
files.usesWarehouse = function () {
// Test hook: act like we're "installed" using a non-homedir warehouse
// directory.
if (process.env.METEOR_WAREHOUSE_DIR)
if (process.env.METEOR_WAREHOUSE_DIR) {
return true;
else
} else {
return ! files.inCheckout();
}
};
// Read the '.tools_version.txt' file. If in a checkout, throw an error.
@@ -243,11 +248,13 @@ files.getSettings = function (filename, watchSet) {
files.prettyPath = function (p) {
p = files.realpath(p);
var home = files.getHomeDir();
if (! home)
if (! home) {
return p;
}
var relativeToHome = files.pathRelative(home, p);
if (relativeToHome.substr(0, 3) === ('..' + files.pathSep))
if (relativeToHome.substr(0, 3) === ('..' + files.pathSep)) {
return p;
}
return files.pathJoin('~', relativeToHome);
};
@@ -256,8 +263,9 @@ files.statOrNull = function (path) {
try {
return files.stat(path);
} catch (e) {
if (e.code == "ENOENT")
if (e.code == "ENOENT") {
return null;
}
throw e;
}
};
@@ -279,8 +287,9 @@ var makeTreeReadOnly = function (p) {
// the l in lstat is critical -- we want to ignore symbolic links
var stat = files.lstat(p);
} catch (e) {
if (e.code == "ENOENT")
if (e.code == "ENOENT") {
return;
}
throw e;
}
@@ -292,8 +301,9 @@ var makeTreeReadOnly = function (p) {
if (stat.isFile()) {
var permissions = stat.mode & 0o777;
var readOnlyPermissions = permissions & 0o555;
if (permissions !== readOnlyPermissions)
if (permissions !== readOnlyPermissions) {
files.chmod(p, readOnlyPermissions);
}
}
};
@@ -446,11 +456,14 @@ files.cp_r = function (from, to, options) {
_.each(files.readdir(from), function (f) {
if (_.any(options.ignore || [], function (pattern) {
return f.match(pattern);
})) return;
})) {
return;
}
var fullFrom = files.pathJoin(from, f);
if (options.transformFilename)
if (options.transformFilename) {
f = options.transformFilename(f);
}
var fullTo = files.pathJoin(to, f);
var stats = options.preserveSymlinks
? files.lstat(fullFrom) : files.stat(fullFrom);
@@ -592,11 +605,13 @@ files.mkdtemp = function (prefix) {
return process.env[t];
}).filter(_.identity));
if (! tmpDir && process.platform !== 'win32')
if (! tmpDir && process.platform !== 'win32') {
tmpDir = '/tmp';
}
if (! tmpDir)
if (! tmpDir) {
throw new Error("Couldn't create a temporary directory.");
}
tmpDir = files.realpath(tmpDir);
@@ -623,10 +638,12 @@ files.mkdtemp = function (prefix) {
// Call this if you're done using a temporary directory. It will asynchronously
// be deleted.
files.freeTempDir = function (tempDir) {
if (! _.contains(tempDirs, tempDir))
if (! _.contains(tempDirs, tempDir)) {
throw Error("not a tracked temp dir: " + tempDir);
if (process.env.METEOR_SAVE_TMPDIRS)
}
if (process.env.METEOR_SAVE_TMPDIRS) {
return;
}
setImmediate(function () {
// note: rm_recursive can yield, so it's possible that during this
// rm_recursive call, the onExit rm_recursive fires too. (Or it could even
@@ -711,9 +728,10 @@ files.extractTarGz = function (buffer, destPath, options) {
// succeed!
var topLevelOfArchive = files.readdir(tempDir);
if (topLevelOfArchive.length !== 1)
if (topLevelOfArchive.length !== 1) {
throw new Error(
"Extracted archive '" + tempDir + "' should only contain one entry");
}
var extractDir = files.pathJoin(tempDir, topLevelOfArchive[0]);
makeTreeReadOnly(extractDir);
@@ -811,8 +829,9 @@ files.renameDirAlmostAtomically = function (fromDir, toDir) {
try {
files.rename(toDir, garbageDir);
} catch (e) {
if (e.code !== 'ENOENT')
if (e.code !== 'ENOENT') {
throw e;
}
movedOldDir = false;
}
@@ -820,8 +839,9 @@ files.renameDirAlmostAtomically = function (fromDir, toDir) {
files.rename(fromDir, toDir);
// ... and delete the old one.
if (movedOldDir)
if (movedOldDir) {
files.rm_recursive(garbageDir);
}
};
files.writeFileAtomically = function (filename, contents) {
@@ -865,8 +885,9 @@ files.symlinkOverSync = function (linkText, file) {
// underlying V8 issue is:
// https://code.google.com/p/v8/issues/detail?id=1281
files.runJavaScript = function (code, options) {
if (typeof code !== 'string')
if (typeof code !== 'string') {
throw new Error("code must be a string");
}
options = options || {};
var filename = options.filename || "<anonymous>";
@@ -932,8 +953,9 @@ files.runJavaScript = function (code, options) {
// stderr (which we don't).
var script = require('vm').createScript(wrapped, stackFilename);
} catch (nodeParseError) {
if (!(nodeParseError instanceof SyntaxError))
if (!(nodeParseError instanceof SyntaxError)) {
throw nodeParseError;
}
// Got a parse error. Unfortunately, we can't actually get the
// location of the parse error from the SyntaxError; Node has some
// hacky support for displaying it over stderr if you pass an
@@ -1010,8 +1032,9 @@ files.readdirNoDots = function (path) {
try {
var entries = files.readdir(path);
} catch (e) {
if (e.code === 'ENOENT')
if (e.code === 'ENOENT') {
return [];
}
throw e;
}
return _.filter(entries, function (entry) {
@@ -1029,8 +1052,9 @@ var getLines = function (file) {
// strip blank lines at the end
while (lines.length) {
var line = lines[lines.length - 1];
if (line.match(/\S/))
if (line.match(/\S/)) {
break;
}
lines.pop();
}
@@ -1048,8 +1072,9 @@ exports.getLinesOrEmpty = function (file) {
try {
return getLines(file);
} catch (e) {
if (e && e.code === 'ENOENT')
if (e && e.code === 'ENOENT') {
return [];
}
throw e;
}
};
@@ -1060,8 +1085,9 @@ exports.readJSONOrNull = function (file) {
try {
var raw = files.readFile(file, 'utf8');
} catch (e) {
if (e && e.code === 'ENOENT')
if (e && e.code === 'ENOENT') {
return null;
}
throw e;
}
return JSON.parse(raw);
@@ -1070,8 +1096,9 @@ exports.readJSONOrNull = function (file) {
// Trims whitespace & other filler characters of a line in a project file.
files.trimSpaceAndComments = function (line) {
var match = line.match(/^([^#]*)#/);
if (match)
if (match) {
line = match[1];
}
return files.trimSpace(line);
};
@@ -1142,7 +1169,9 @@ files.currentEnvWithPathsAdded = function (...paths) {
pathPropertyName = _.find(Object.keys(env), (key) => {
return key.toUpperCase() === 'PATH';
});
if (!pathPropertyName) pathPropertyName = 'Path';
if (!pathPropertyName) {
pathPropertyName = 'Path';
}
} else {
pathPropertyName = 'PATH';
}
@@ -1397,8 +1426,9 @@ if (process.platform === "win32") {
rename(from, to);
success = true;
} catch (err) {
if (err.code !== 'EPERM')
if (err.code !== 'EPERM') {
throw err;
}
}
}
if (! success) {
@@ -1478,8 +1508,9 @@ files.readBufferWithLengthAndOffset = function (filename, length, offset) {
} finally {
files.close(fd);
}
if (count !== length)
if (count !== length) {
throw new Error("couldn't read entire resource");
}
}
return data;
};

View File

@@ -37,8 +37,9 @@ exports.watch = function watch(absPath, callback) {
watcher = files.pathwatcherWatch(absPath, pathwatcherWrapper);
} catch (e) {
// If it isn't an actual pathwatcher failure, rethrow.
if (e.message !== 'Unable to watch path')
if (e.message !== 'Unable to watch path') {
throw e;
}
var constants = require('constants');
var archinfo = require('../utils/archinfo.js');
if (! suggestedRaisingWatchLimit &&

View File

@@ -133,8 +133,9 @@ export class SourceProcessorSet {
addLegacyHandler({ extension, handler, packageDisplayName, isTemplate,
archMatching }) {
if (this._allowConflicts)
if (this._allowConflicts) {
throw Error("linters have no legacy handlers");
}
if (this._byExtension.hasOwnProperty(extension)) {
this._conflictError(packageDisplayName,
@@ -175,8 +176,9 @@ export class SourceProcessorSet {
// Note: Only returns SourceProcessors, not legacy handlers.
getByExtension(extension) {
if (this._allowConflicts)
if (this._allowConflicts) {
throw Error("Can't call getByExtension for linters");
}
if (this._byExtension.hasOwnProperty(extension)) {
return this._byExtension[extension][0];
@@ -186,8 +188,9 @@ export class SourceProcessorSet {
// Note: Only returns SourceProcessors, not legacy handlers.
getByFilename(filename) {
if (this._allowConflicts)
if (this._allowConflicts) {
throw Error("Can't call getByFilename for linters");
}
if (this._byFilename.hasOwnProperty(filename)) {
return this._byFilename[filename][0];

View File

@@ -96,8 +96,10 @@ Previous builder: ${previousBuilder.outputPath}, this builder: ${outputPath}`
// root. Throws an exception on failure.
_ensureDirectory(relPath) {
const parts = files.pathNormalize(relPath).split(files.pathSep);
if (parts.length > 1 && parts[parts.length - 1] === '')
parts.pop(); // remove trailing slash
if (parts.length > 1 && parts[parts.length - 1] === '') {
// remove trailing slash
parts.pop();
}
const partsSoFar = [];
parts.forEach(part => {
@@ -139,8 +141,9 @@ Previous builder: ${previousBuilder.outputPath}, this builder: ${outputPath}`
const mustBeUnique = (i === parts.length - 1);
// Basic sanitization
if (part.match(/^\.+$/))
if (part.match(/^\.+$/)) {
throw new Error(`Path contains forbidden segment '${part}'`);
}
part = part.replace(/[^a-zA-Z0-9._\:-]/g, '');
@@ -148,8 +151,9 @@ Previous builder: ${previousBuilder.outputPath}, this builder: ${outputPath}`
let ext = '';
if (shouldBeFile) {
const split = part.split('.');
if (split.length > 1)
if (split.length > 1) {
ext = "." + split.pop();
}
part = split.join('.');
}
@@ -159,8 +163,9 @@ Previous builder: ${previousBuilder.outputPath}, this builder: ${outputPath}`
const candidate = files.pathJoin(partsOut.join(files.pathSep), part + suffix + ext);
if (candidate.length) {
// If we've never heard of this, then it's unique enough.
if (!(candidate in this.usedAsFile))
if (!(candidate in this.usedAsFile)) {
break;
}
// If we want this bit to be a directory, and we don't need it to be
// unique (ie, it isn't the very last bit), and it's currently a
// directory, then that's OK.
@@ -204,20 +209,24 @@ Previous builder: ${previousBuilder.outputPath}, this builder: ${outputPath}`
// If `file` is used then it will be added to the builder's WatchSet.
write(relPath, {data, file, hash, sanitize, executable, symlink}) {
// Ensure no trailing slash
if (relPath.slice(-1) === files.pathSep)
if (relPath.slice(-1) === files.pathSep) {
relPath = relPath.slice(0, -1);
}
// In sanitize mode, ensure path does not contain segments like
// '..', does not contain forbidden characters, and is unique.
if (sanitize)
if (sanitize) {
relPath = this._sanitize(relPath);
}
let getData = null;
if (data) {
if (! (data instanceof Buffer))
if (! (data instanceof Buffer)) {
throw new Error("data must be a Buffer");
if (file)
}
if (file) {
throw new Error("May only pass one of data and file, not both");
}
getData = () => data;
} else if (file) {
// postpone reading the file into memory
@@ -255,8 +264,9 @@ Previous builder: ${previousBuilder.outputPath}, this builder: ${outputPath}`
// necessary. Throw an exception if the file already exists.
writeJson(relPath, data) {
// Ensure no trailing slash
if (relPath.slice(-1) === files.pathSep)
if (relPath.slice(-1) === files.pathSep) {
relPath = relPath.slice(0, -1);
}
this._ensureDirectory(files.pathDirname(relPath));
const absPath = files.pathJoin(this.buildPath, relPath);
@@ -285,8 +295,9 @@ Previous builder: ${previousBuilder.outputPath}, this builder: ${outputPath}`
// directory rather than a file.
reserve(relPath, {directory} = {}) {
// Ensure no trailing slash
if (relPath.slice(-1) === files.pathSep)
if (relPath.slice(-1) === files.pathSep) {
relPath = relPath.slice(0, -1);
}
const parts = relPath.split(files.pathSep);
const partsSoFar = [];
@@ -294,8 +305,9 @@ Previous builder: ${previousBuilder.outputPath}, this builder: ${outputPath}`
const part = parts[i];
partsSoFar.push(part);
const soFar = partsSoFar.join(files.pathSep);
if (this.usedAsFile[soFar])
if (this.usedAsFile[soFar]) {
throw new Error("Path reservation conflict: " + relPath);
}
const shouldBeDirectory = (i < parts.length - 1) || directory;
if (shouldBeDirectory) {
@@ -374,8 +386,9 @@ Previous builder: ${previousBuilder.outputPath}, this builder: ${outputPath}`
// - specificFiles: just copy these paths (specified as relative to 'to').
// - symlink: true if the directory should be symlinked instead of copying
copyDirectory({from, to, ignore, specificFiles, symlink, npmDiscards}) {
if (to.slice(-1) === files.pathSep)
if (to.slice(-1) === files.pathSep) {
to = to.slice(0, -1);
}
const absPathTo = files.pathJoin(this.buildPath, to);
if (symlink) {
@@ -449,7 +462,9 @@ Previous builder: ${previousBuilder.outputPath}, this builder: ${outputPath}`
}
// skip excluded files
if (ignore.some(pattern => itemForMatch.match(pattern))) return;
if (ignore.some(pattern => itemForMatch.match(pattern))) {
return;
}
if (npmDiscards instanceof NpmDiscards &&
npmDiscards.shouldDiscard(thisAbsFrom, isDirectory)) {
@@ -507,11 +522,13 @@ Previous builder: ${previousBuilder.outputPath}, this builder: ${outputPath}`
if (method === "generateFilename") {
// fix up the returned path to be relative to the
// sub-bundle, not the parent bundle
if (ret.substr(0, 1) === '/')
if (ret.substr(0, 1) === '/') {
ret = ret.substr(1);
if (ret.substr(0, relPathWithSep.length) !== relPathWithSep)
}
if (ret.substr(0, relPathWithSep.length) !== relPathWithSep) {
throw new Error("generateFilename returned path outside of " +
"sub-bundle?");
}
ret = ret.substr(relPathWithSep.length);
}

View File

@@ -177,8 +177,9 @@ exports.ignoreFiles = [
];
var rejectBadPath = function (p) {
if (p.match(/\.\./))
if (p.match(/\.\./)) {
throw new Error("bad path: " + p);
}
};
var stripLeadingSlash = function (p) {
@@ -241,10 +242,12 @@ var NodeModulesDirectory = function (options) {
// - cacheable
class File {
constructor (options) {
if (options.data && ! (options.data instanceof Buffer))
if (options.data && ! (options.data instanceof Buffer)) {
throw new Error('File contents must be provided as a Buffer');
if (! options.sourcePath && ! options.data)
}
if (! options.sourcePath && ! options.data) {
throw new Error("Must provide either sourcePath or data");
}
// The absolute path in the filesystem from which we loaded (or will
// load) this file (null if the file does not correspond to one on
@@ -305,17 +308,18 @@ class File {
if (! this._contents) {
if (! this.sourcePath) {
throw new Error("Have neither contents nor sourcePath for file");
}
else
} else {
this._contents = files.readFile(this.sourcePath);
}
}
return encoding ? this._contents.toString(encoding) : this._contents;
}
setContents(b) {
if (!(b instanceof Buffer))
if (!(b instanceof Buffer)) {
throw new Error("Must set contents to a Buffer");
}
this._contents = b;
// Un-cache hash.
this._hash = null;
@@ -340,12 +344,16 @@ class File {
// Append "?<hash>" to the URL and mark the file as cacheable.
addCacheBuster() {
if (! this.url)
if (! this.url) {
throw new Error("File must have a URL");
if (this.cacheable)
return; // eg, already got setUrlToHash
if (/\?/.test(this.url))
}
if (this.cacheable) {
// eg, already got setUrlToHash
return;
}
if (/\?/.test(this.url)) {
throw new Error("URL already has a query string");
}
this.url += "?hash=" + this.hash();
this.cacheable = true;
}
@@ -357,8 +365,9 @@ class File {
setUrlFromRelPath(relPath) {
var url = relPath;
if (url.charAt(0) !== '/')
if (url.charAt(0) !== '/') {
url = '/' + url;
}
// XXX replacing colons with underscores as colon is hard to escape later
// on different targets and generally is not a good separator for web.
@@ -368,10 +377,11 @@ class File {
setTargetPathFromRelPath(relPath) {
// XXX hack
if (relPath.match(/^packages\//) || relPath.match(/^assets\//))
if (relPath.match(/^packages\//) || relPath.match(/^assets\//)) {
this.targetPath = relPath;
else
} else {
this.targetPath = files.pathJoin('app', relPath);
}
// XXX same as in setUrlFromRelPath, we replace colons with a different
// separator to avoid difficulties further. E.g.: on Windows it is not a
@@ -395,8 +405,9 @@ class File {
// note: this assets object may be shared among multiple files!
setAssets(assets) {
if (!_.isEmpty(assets))
if (!_.isEmpty(assets)) {
this.assets = assets;
}
}
}
@@ -575,8 +586,9 @@ class Target {
unibuild && rootUnibuilds.push(unibuild);
});
if (buildmessage.jobHasMessages())
if (buildmessage.jobHasMessages()) {
return;
}
// PHASE 1: Which unibuilds will be used?
//
@@ -590,8 +602,9 @@ class Target {
const usedUnibuilds = {}; // Map from unibuild.id to Unibuild.
this.usedPackages = {}; // Map from package name to true;
const addToGetsUsed = function (unibuild) {
if (_.has(usedUnibuilds, unibuild.id))
if (_.has(usedUnibuilds, unibuild.id)) {
return;
}
usedUnibuilds[unibuild.id] = unibuild;
if (unibuild.kind === 'main') {
// Only track real packages, not plugin pseudo-packages.
@@ -609,8 +622,9 @@ class Target {
rootUnibuilds.forEach(addToGetsUsed);
if (buildmessage.jobHasMessages())
if (buildmessage.jobHasMessages()) {
return;
}
// PHASE 2: In what order should we load the unibuilds?
//
@@ -635,8 +649,9 @@ class Target {
// this.unibuilds, then adds unibuild itself.
const add = function (unibuild) {
// If this has already been added, there's nothing to do.
if (!_.has(needed, unibuild.id))
if (!_.has(needed, unibuild.id)) {
return;
}
// Process each ordered dependency. (If we have an unordered dependency
// `u`, then there's no reason to add it *now*, and for all we know, `u`
@@ -678,9 +693,12 @@ class Target {
// Get an arbitrary unibuild from those that remain, or break if none
// remain.
let first = null;
for (first in needed) break;
if (! first)
for (first in needed) {
break;
}
if (! first) {
break;
}
// Now add it, after its ordered dependencies.
add(needed[first]);
}
@@ -733,8 +751,9 @@ class Target {
// resource (for os unibuilds).
const unibuildAssets = {};
resources.forEach((resource) => {
if (resource.type !== 'asset')
if (resource.type !== 'asset') {
return;
}
const f = new File({
info: 'unbuild ' + resource,
@@ -759,11 +778,13 @@ class Target {
// Now look for the other kinds of resources.
resources.forEach((resource) => {
if (resource.type === 'asset')
return; // already handled
if (resource.type === 'asset') {
// already handled
return;
}
if (_.contains(['js', 'css'], resource.type)) {
if (resource.type === 'css' && ! isWeb)
if (resource.type === 'css' && ! isWeb) {
// XXX might be nice to throw an error here, but then we'd
// have to make it so that package.js ignores css files
// that appear in the server directories in an app tree
@@ -771,6 +792,7 @@ class Target {
// XXX XXX can't we easily do that in the css handler in
// meteor.js?
return;
}
const f = new File({ info: 'resource ' + resource.servePath, data: resource.data, cacheable: false});
@@ -783,8 +805,9 @@ class Target {
if (resource.type === 'js' && isOs) {
// Hack, but otherwise we'll end up putting app assets on this file.
if (resource.servePath !== '/packages/global-imports.js')
if (resource.servePath !== '/packages/global-imports.js') {
f.setAssets(unibuildAssets);
}
if (! isApp && unibuild.nodeModulesPath) {
var nmd = this.nodeModulesDirectories[unibuild.nodeModulesPath];
@@ -849,8 +872,9 @@ class Target {
}
if (_.contains(['head', 'body'], resource.type)) {
if (! isWeb)
if (! isWeb) {
throw new Error('HTML segments can only go to the client');
}
this[resource.type].push(resource.data);
return;
}
@@ -920,7 +944,9 @@ class Target {
sm.sources = sm.sources.map(function (path) {
const prefix = 'meteor://\u{1f4bb}app';
if (path.slice(0, prefix.length) === prefix) return path;
if (path.slice(0, prefix.length) === prefix) {
return path;
}
// This emoji makes sure the category is always last. The character
// is PERSONAL COMPUTER (yay ES6 unicode escapes):
// http://www.fileformat.info/info/unicode/char/1f4bb/index.htm
@@ -931,15 +957,17 @@ class Target {
if (this.js) {
this.js.forEach(function (js) {
if (js.sourceMap)
if (js.sourceMap) {
js.sourceMap = rewriteSourceMap(js.sourceMap);
}
});
}
if (this.css) {
this.css.forEach(function (css) {
if (css.sourceMap)
if (css.sourceMap) {
css.sourceMap = rewriteSourceMap(css.sourceMap);
}
});
}
}
@@ -950,8 +978,9 @@ class Target {
// we always add the exact version specified, overriding any other
// version that has already been added.
_addCordovaDependency(name, version, override) {
if (! this.cordovaDependencies)
if (! this.cordovaDependencies) {
return;
}
if (override) {
this.cordovaDependencies[name] = version;
@@ -974,8 +1003,9 @@ class Target {
// XXX The versions of these direct dependencies override any versions
// of the same plugins that packages are using.
_addDirectCordovaDependencies() {
if (! this.cordovaDependencies)
if (! this.cordovaDependencies) {
return;
}
_.each(this.cordovaPluginsFile.getPluginVersions(), (version, name) => {
this._addCordovaDependency(
@@ -1038,8 +1068,9 @@ class ClientTarget extends Target {
this.head = [];
this.body = [];
if (! archinfo.matches(this.arch, 'web'))
if (! archinfo.matches(this.arch, 'web')) {
throw new Error('ClientTarget targeting something that isn\'t a client?');
}
}
// Minify the CSS in this target
@@ -1271,16 +1302,18 @@ class JsImage {
assetPath = files.convertToStandardPath(assetPath);
var fut;
if (! callback) {
if (! Fiber.current)
if (! Fiber.current) {
throw new Error("The synchronous Assets API can " +
"only be called from within a Fiber.");
}
fut = new Future();
callback = fut.resolver();
}
var _callback = function (err, result) {
if (result && ! encoding)
if (result && ! encoding) {
// Sadly, this copies in Node 0.10.
result = new Uint8Array(result);
}
callback(err, result);
};
@@ -1291,8 +1324,9 @@ class JsImage {
var result = encoding ? buffer.toString(encoding) : buffer;
_callback(null, result);
}
if (fut)
if (fut) {
return fut.wait();
}
};
// Eval each JavaScript file, providing a 'Npm' symbol in the same
@@ -1302,8 +1336,9 @@ class JsImage {
// static assets.
var failed = false;
_.each(self.jsToLoad, function (item) {
if (failed)
if (failed) {
return;
}
var env = _.extend({
Package: ret,
@@ -1447,8 +1482,9 @@ class JsImage {
// JavaScript sources
var load = [];
_.each(self.jsToLoad, function (item) {
if (! item.targetPath)
if (! item.targetPath) {
throw new Error("No targetPath?");
}
var loadItem = {};
@@ -1483,8 +1519,9 @@ class JsImage {
item.source = item.source.replace(
/\n\/\/# sourceMappingURL=.+\n?$/g, '');
item.source += "\n//# sourceMappingURL=" + sourceMapFileName + "\n";
if (item.sourceMapRoot)
if (item.sourceMapRoot) {
loadItem.sourceMapRoot = item.sourceMapRoot;
}
}
loadItem.path = builder.writeToGeneratedFilename(
@@ -1589,9 +1626,10 @@ class JsImage {
var json = JSON.parse(files.readFile(controlFilePath));
var dir = files.pathDirname(controlFilePath);
if (json.format !== "javascript-image-pre1")
if (json.format !== "javascript-image-pre1") {
throw new Error("Unsupported plugin format: " +
JSON.stringify(json.format));
}
ret.arch = json.arch;
@@ -1654,10 +1692,11 @@ class JsImageTarget extends Target {
constructor(options) {
super(options);
if (! archinfo.matches(this.arch, "os"))
if (! archinfo.matches(this.arch, "os")) {
// Conceivably we could support targeting the client as long as
// no native node modules were used. No use case for that though.
throw new Error("JsImageTarget targeting something unusual?");
}
}
toJsImage() {
@@ -1695,8 +1734,9 @@ class ServerTarget extends JsImageTarget {
this.clientTargets = options.clientTargets;
this.releaseName = options.releaseName;
if (! archinfo.matches(this.arch, "os"))
if (! archinfo.matches(this.arch, "os")) {
throw new Error("ServerTarget targeting something that isn't a server?");
}
}
// Output the finished target to disk
@@ -1818,11 +1858,13 @@ class ServerTarget extends JsImageTarget {
});
var writeFile = Profile("bundler..writeFile", function (file, builder) {
if (! file.targetPath)
if (! file.targetPath) {
throw new Error("No targetPath?");
}
var contents = file.contents();
if (! (contents instanceof Buffer))
if (! (contents instanceof Buffer)) {
throw new Error("contents not a Buffer?");
}
// XXX should probably use sanitize: true, but that will have
// to wait until the server is actually driven by the manifest
// (rather than just serving all of the files in a certain
@@ -2118,8 +2160,9 @@ exports.bundle = function ({
const bundlerCacheDir =
projectContext.getProjectLocalDirectory('bundler-cache');
if (! release.usingRightReleaseForApp(projectContext))
if (! release.usingRightReleaseForApp(projectContext)) {
throw new Error("running wrong release for app?");
}
if (! _.contains(['development', 'production'], buildMode)) {
throw new Error('Unrecognized build mode: ' + buildMode);
@@ -2161,8 +2204,9 @@ exports.bundle = function ({
buildMode: buildOptions.buildMode,
providePackageJSONForUnavailableBinaryDeps
};
if (clientTargets)
if (clientTargets) {
targetOptions.clientTargets = clientTargets;
}
var server = new ServerTarget(targetOptions);
@@ -2247,11 +2291,13 @@ exports.bundle = function ({
var pathForTarget = function (target) {
var name;
_.each(targets, function (t, n) {
if (t === target)
if (t === target) {
name = n;
}
});
if (! name)
if (! name) {
throw new Error("missing target?");
}
return files.pathJoin('programs', name);
};
@@ -2300,8 +2346,10 @@ exports.bundle = function ({
success = true;
});
if (success && messages.hasMessages())
success = false; // there were errors
if (success && messages.hasMessages()) {
// there were errors
success = false;
}
return {
errors: success ? false : messages,
@@ -2386,10 +2434,12 @@ function lintBundle (projectContext, isopack, packageSource) {
// namespace." It should be an easy refactor,
exports.buildJsImage = Profile("bundler.buildJsImage", function (options) {
buildmessage.assertInCapture();
if (options.npmDependencies && ! options.npmDir)
if (options.npmDependencies && ! options.npmDir) {
throw new Error("Must indicate .npm directory to use");
if (! options.name)
}
if (! options.name) {
throw new Error("Must provide a name");
}
var packageSource = new PackageSource;

View File

@@ -263,8 +263,9 @@ exports.makeCompileStep = function (sourceItem, file, inputSourceArch, options)
* @returns {Buffer}
*/
read: function (n) {
if (n === undefined || readOffset + n > contents.length)
if (n === undefined || readOffset + n > contents.length) {
n = contents.length - readOffset;
}
var ret = contents.slice(readOffset, readOffset + n);
readOffset += n;
return ret;
@@ -281,13 +282,16 @@ exports.makeCompileStep = function (sourceItem, file, inputSourceArch, options)
* @instance
*/
addHtml: function (options) {
if (! archinfo.matches(inputSourceArch.arch, "web"))
if (! archinfo.matches(inputSourceArch.arch, "web")) {
throw new Error("Document sections can only be emitted to " +
"web targets");
if (options.section !== "head" && options.section !== "body")
}
if (options.section !== "head" && options.section !== "body") {
throw new Error("'section' must be 'head' or 'body'");
if (typeof options.data !== "string")
}
if (typeof options.data !== "string") {
throw new Error("'data' option to appendDocument must be a string");
}
resources.push({
type: options.section,
data: new Buffer(files.convertToStandardLineEndings(options.data), 'utf8')
@@ -314,11 +318,13 @@ exports.makeCompileStep = function (sourceItem, file, inputSourceArch, options)
* @instance
*/
addStylesheet: function (options) {
if (! archinfo.matches(inputSourceArch.arch, "web"))
if (! archinfo.matches(inputSourceArch.arch, "web")) {
throw new Error("Stylesheets can only be emitted to " +
"web targets");
if (typeof options.data !== "string")
}
if (typeof options.data !== "string") {
throw new Error("'data' option to addStylesheet must be a string");
}
resources.push({
type: "css",
refreshable: true,
@@ -348,10 +354,12 @@ exports.makeCompileStep = function (sourceItem, file, inputSourceArch, options)
* @instance
*/
addJavaScript: function (options) {
if (typeof options.data !== "string")
if (typeof options.data !== "string") {
throw new Error("'data' option to addJavaScript must be a string");
if (typeof options.sourcePath !== "string")
}
if (typeof options.sourcePath !== "string") {
throw new Error("'sourcePath' option must be supplied to addJavaScript. Consider passing inputPath.");
}
// By default, use fileOptions for the `bare` option but also allow
// overriding it with the options

View File

@@ -106,8 +106,9 @@ export class CompilerPluginProcessor {
_.each(sourceBatch.resourceSlots, function (resourceSlot) {
var sourceProcessor = resourceSlot.sourceProcessor;
// Skip non-sources.
if (! sourceProcessor)
if (! sourceProcessor) {
return;
}
if (! _.has(sourceProcessorsWithSlots, sourceProcessor.id)) {
sourceProcessorsWithSlots[sourceProcessor.id] = {
@@ -352,8 +353,9 @@ class ResourceSlot {
addStylesheet(options) {
const self = this;
if (! self.sourceProcessor)
if (! self.sourceProcessor) {
throw Error("addStylesheet on non-source ResourceSlot?");
}
self.outputResources.push({
type: "css",
@@ -370,8 +372,9 @@ class ResourceSlot {
addJavaScript(options) {
const self = this;
// #HardcodeJs this gets called by constructor in the "js" case
if (! self.sourceProcessor && self.inputResource.extension !== "js")
if (! self.sourceProcessor && self.inputResource.extension !== "js") {
throw Error("addJavaScript on non-source ResourceSlot?");
}
// By default, use the 'bare' option given to addFiles, but allow the option
// passed to addJavaScript to override it.
@@ -399,8 +402,9 @@ class ResourceSlot {
addAsset(options) {
const self = this;
if (! self.sourceProcessor)
if (! self.sourceProcessor) {
throw Error("addAsset on non-source ResourceSlot?");
}
if (! (options.data instanceof Buffer)) {
if (_.isString(options.data)) {
@@ -424,13 +428,16 @@ class ResourceSlot {
const self = this;
const unibuild = self.packageSourceBatch.unibuild;
if (! archinfo.matches(unibuild.arch, "web"))
if (! archinfo.matches(unibuild.arch, "web")) {
throw new Error("Document sections can only be emitted to " +
"web targets");
if (options.section !== "head" && options.section !== "body")
}
if (options.section !== "head" && options.section !== "body") {
throw new Error("'section' must be 'head' or 'body'");
if (typeof options.data !== "string")
}
if (typeof options.data !== "string") {
throw new Error("'data' option to appendDocument must be a string");
}
self.outputResources.push({
type: options.section,
@@ -625,8 +632,9 @@ class PackageSourceBatch {
diskCached = files.readJSONOrNull(cacheFilename);
} catch (e) {
// Ignore JSON parse errors; pretend there was no cache.
if (!(e instanceof SyntaxError))
if (!(e instanceof SyntaxError)) {
throw e;
}
}
if (diskCached && diskCached instanceof Array) {
// Fix the non-JSON part of our return value.

View File

@@ -86,16 +86,18 @@ compiler.compile = Profile(function (packageSource, options) {
// and have the runner restart.
pluginWatchSet.merge(buildResult.watchSet);
if (buildmessage.jobHasMessages())
if (buildmessage.jobHasMessages()) {
return;
}
_.each(buildResult.usedPackageNames, function (packageName) {
pluginProviderPackageNames[packageName] = true;
});
// Register the built plugin's code.
if (!_.has(plugins, info.name))
if (!_.has(plugins, info.name)) {
plugins[info.name] = {};
}
plugins[info.name][buildResult.image.arch] = buildResult.image;
});
});
@@ -169,8 +171,9 @@ compiler.compile = Profile(function (packageSource, options) {
});
_.each(packageSource.architectures, function (architecture) {
if (architecture.arch === 'web.cordova' && ! includeCordovaUnibuild)
if (architecture.arch === 'web.cordova' && ! includeCordovaUnibuild) {
return;
}
var unibuildResult = compileUnibuild({
isopack: isopk,
@@ -664,8 +667,9 @@ function runLinters({inputSourceArch, isopackCache, sources,
// version when we're bundling for Linux.
allowWrongPlatform: true,
}, (unibuild) => {
if (unibuild.pkg.name === inputSourceArch.pkg.name)
if (unibuild.pkg.name === inputSourceArch.pkg.name) {
return;
}
_.each(unibuild.declaredExports, (symbol) => {
if (! symbol.testOnly || inputSourceArch.isTest) {
globalImports.push(symbol.name);
@@ -683,8 +687,9 @@ function runLinters({inputSourceArch, isopackCache, sources,
// If we don't have a linter for this file (or we do but it's only on
// another arch), skip without even reading the file into a WatchSet.
if (classification.type === 'wrong-arch' ||
classification.type === 'unmatched')
classification.type === 'unmatched') {
return;
}
// We shouldn't ever add a legacy handler and we're not hardcoding JS for
// linters, so we should always have SourceProcessor if anything matches.
if (! classification.sourceProcessors) {
@@ -723,12 +728,15 @@ function runLinters({inputSourceArch, isopackCache, sources,
const linter = sourceProcessor.userPlugin.processFilesForPackage;
function archToString(arch) {
if (arch.match(/web\.cordova/))
if (arch.match(/web\.cordova/)) {
return "Cordova";
if (arch.match(/web\..*/))
}
if (arch.match(/web\..*/)) {
return "Client";
if (arch.match(/os.*/))
}
if (arch.match(/os.*/)) {
return "Server";
}
throw new Error("Don't know how to display the arch: " + arch);
}
@@ -769,8 +777,9 @@ export function getActivePluginPackages(isopk, {
// the implies field is on the target unibuild, but we really only care
// about packages.)
var activePluginPackages = [isopk];
if (pluginProviderPackageNames)
if (pluginProviderPackageNames) {
pluginProviderPackageNames[isopk.name] = true;
}
// We don't use plugins from weak dependencies, because the ability
// to compile a certain type of file shouldn't depend on whether or
@@ -790,16 +799,18 @@ export function getActivePluginPackages(isopk, {
skipUnordered: true
// implicitly skip weak deps by not specifying acceptableWeakPackages option
}, function (unibuild) {
if (unibuild.pkg.name === isopk.name)
if (unibuild.pkg.name === isopk.name) {
return;
}
if (pluginProviderPackageNames) {
pluginProviderPackageNames[unibuild.pkg.name] = true;
}
if (pluginProviderWatchSet) {
pluginProviderWatchSet.merge(unibuild.pkg.pluginWatchSet);
}
if (_.isEmpty(unibuild.pkg.plugins))
if (_.isEmpty(unibuild.pkg.plugins)) {
return;
}
activePluginPackages.push(unibuild.pkg);
});
@@ -825,10 +836,12 @@ compiler.eachUsedUnibuild = function (
var processedUnibuildId = {};
var usesToProcess = [];
_.each(dependencies, function (use) {
if (options.skipUnordered && use.unordered)
if (options.skipUnordered && use.unordered) {
return;
if (use.weak && !_.has(acceptableWeakPackages, use.package))
}
if (use.weak && !_.has(acceptableWeakPackages, use.package)) {
return;
}
usesToProcess.push(use);
});
@@ -836,18 +849,21 @@ compiler.eachUsedUnibuild = function (
var use = usesToProcess.shift();
// We only care about real packages, not isobuild:* psuedo-packages.
if (isIsobuildFeaturePackage(use.package))
if (isIsobuildFeaturePackage(use.package)) {
continue;
}
var usedPackage = isopackCache.getIsopack(use.package);
// Ignore this package if we were told to skip debug-only packages and it is
// debug-only.
if (usedPackage.debugOnly && options.skipDebugOnly)
if (usedPackage.debugOnly && options.skipDebugOnly) {
continue;
}
// Ditto prodOnly.
if (usedPackage.prodOnly && options.skipProdOnly)
if (usedPackage.prodOnly && options.skipProdOnly) {
continue;
}
var unibuild = usedPackage.getUnibuildAtArch(arch, {allowWrongPlatform});
if (!unibuild) {
@@ -856,8 +872,9 @@ compiler.eachUsedUnibuild = function (
continue;
}
if (_.has(processedUnibuildId, unibuild.id))
if (_.has(processedUnibuildId, unibuild.id)) {
continue;
}
processedUnibuildId[unibuild.id] = true;
callback(unibuild, {

View File

@@ -60,8 +60,9 @@ _.extend(exports.IsopackCache.prototype, {
var self = this;
buildmessage.assertInCapture();
if (self.cacheDir)
if (self.cacheDir) {
files.mkdir_p(self.cacheDir);
}
var onStack = {};
if (rootPackageNames) {
@@ -104,8 +105,9 @@ _.extend(exports.IsopackCache.prototype, {
// package whose dependencies have all already been built.
getIsopack: function (name) {
var self = this;
if (! _.has(self._isopacks, name))
if (! _.has(self._isopacks, name)) {
throw Error("isopack " + name + " not yet loaded?");
}
return self._isopacks[name];
},
@@ -119,8 +121,9 @@ _.extend(exports.IsopackCache.prototype, {
_ensurePackageLoaded: function (name, onStack) {
var self = this;
buildmessage.assertInCapture();
if (_.has(self._isopacks, name))
if (_.has(self._isopacks, name)) {
return;
}
var ensureLoaded = function (depName) {
if (_.has(onStack, depName)) {
@@ -135,8 +138,9 @@ _.extend(exports.IsopackCache.prototype, {
};
var packageInfo = self._packageMap.getInfo(name);
if (! packageInfo)
if (! packageInfo) {
throw Error("Depend on unknown package " + name + "?");
}
var previousIsopack = null;
if (self._previousIsopackCache &&
_.has(self._previousIsopackCache._isopacks, name)) {
@@ -161,8 +165,9 @@ _.extend(exports.IsopackCache.prototype, {
});
// If we failed to load something that this package depends on, don't
// load it.
if (buildmessage.jobHasMessages())
if (buildmessage.jobHasMessages()) {
return;
}
self._loadLocalPackage(name, packageInfo, previousIsopack);
});
} else if (packageInfo.kind === 'versioned') {
@@ -203,8 +208,9 @@ _.extend(exports.IsopackCache.prototype, {
// If loading the isopack fails, then we don't need to look for more
// packages to load, but we should still recover by putting it in
// self._isopacks.
if (buildmessage.jobHasMessages())
if (buildmessage.jobHasMessages()) {
return;
}
packagesToLoad = isopack.getStrongOrderedUsedAndImpliedPackages();
});
}
@@ -322,8 +328,9 @@ _.extend(exports.IsopackCache.prototype, {
var self = this;
// If there isn't an isopack-buildinfo.json file, then we definitely aren't
// up to date!
if (! isopackBuildInfoJson)
if (! isopackBuildInfoJson) {
return false;
}
// If we include Cordova but this Isopack doesn't, or via versa, then we're
// not up to date.
@@ -414,10 +421,12 @@ _.extend(exports.IsopackCache.prototype, {
},
_shouldLintPackage(packageSource) {
if (this._lintLocalPackages)
if (this._lintLocalPackages) {
return true;
if (! this._lintPackageWithSourceRoot)
}
if (! this._lintPackageWithSourceRoot) {
return false;
}
return this._lintPackageWithSourceRoot === packageSource.sourceRoot;
},

View File

@@ -15,8 +15,9 @@ var Console = require('../console/console.js').Console;
var Profile = require('../tool-env/profile.js').Profile;
var rejectBadPath = function (p) {
if (p.match(/\.\./))
if (p.match(/\.\./)) {
throw new Error("bad path: " + p);
}
};
///////////////////////////////////////////////////////////////////////////////
@@ -239,10 +240,12 @@ Isopack.convertIsopackFormat = Profile(
var toPos = _.indexOf(Isopack.knownFormats, toFormat);
var step = fromPos < toPos ? 1 : -1;
if (fromPos === -1)
if (fromPos === -1) {
throw new Error("Can't convert from unknown Isopack format: " + fromFormat);
if (toPos === -1)
}
if (toPos === -1) {
throw new Error("Can't convert to unknown Isopack format: " + toFormat);
}
while (fromPos !== toPos) {
if (step > 0) {
@@ -361,8 +364,9 @@ _.extend(Isopack.prototype, {
anySourceFiles = true;
var relativePath = files.pathRelative(sourceRoot, filename);
// We only want files that are actually under sourceRoot.
if (relativePath.substr(0, 3) === '..' + files.pathSep)
if (relativePath.substr(0, 3) === '..' + files.pathSep) {
return;
}
sourceFiles[relativePath] = true;
});
};
@@ -374,8 +378,9 @@ _.extend(Isopack.prototype, {
// Were we actually built from source or loaded from an IsopackCache? If so
// then there should be at least one source file in some WatchSet. If not,
// return null.
if (! anySourceFiles)
if (! anySourceFiles) {
return null;
}
return _.keys(sourceFiles);
}),
@@ -467,8 +472,9 @@ _.extend(Isopack.prototype, {
_checkPluginsInitialized: function () {
var self = this;
if (self._pluginsInitialized)
if (self._pluginsInitialized) {
return;
}
throw Error("plugins not yet initialized?");
},
@@ -479,8 +485,9 @@ _.extend(Isopack.prototype, {
buildmessage.assertInJob();
if (self._pluginsInitialized)
if (self._pluginsInitialized) {
return;
}
self.sourceProcessors.compiler = new buildPluginModule.SourceProcessorSet(
self.displayName(), { hardcodeJs: true, singlePackage: true });
@@ -892,8 +899,9 @@ _.extend(Isopack.prototype, {
// PackageMap which can be subset to create a new PackageMap object.)
var unibuildWatchSets = {};
if (options.isopackBuildInfoJson) {
if (! options.firstIsopack)
if (! options.firstIsopack) {
throw Error("can't merge isopacks with buildinfo");
}
// XXX should comprehensively sanitize (eg, typecheck) everything
// read from json files
@@ -948,8 +956,9 @@ _.extend(Isopack.prototype, {
var alreadyHaveUnibuild = _.find(self.unibuilds, function (unibuild) {
return unibuild.arch === unibuildMeta.arch;
});
if (alreadyHaveUnibuild)
if (alreadyHaveUnibuild) {
return;
}
var unibuildJson = JSON.parse(
files.readFile(files.pathJoin(dir, unibuildMeta.path)));
@@ -1038,9 +1047,10 @@ _.extend(Isopack.prototype, {
servePath: resource.servePath || undefined,
path: resource.path || undefined
});
} else
} else {
throw new Error("bad resource type in isopack: " +
JSON.stringify(resource.type));
}
});
var declaredExports;
@@ -1296,8 +1306,9 @@ _.extend(Isopack.prototype, {
concat[resource.type].push(new Buffer("\n", "utf8"));
offset[resource.type]++;
}
if (! (resource.data instanceof Buffer))
if (! (resource.data instanceof Buffer)) {
throw new Error("Resource data must be a Buffer");
}
unibuildJson.resources.push({
type: resource.type,
file: files.pathJoin(unibuildDir, resource.type),
@@ -1318,8 +1329,10 @@ _.extend(Isopack.prototype, {
// Output other resources each to their own file
_.each(unibuild.resources, function (resource) {
if (_.contains(["head", "body"], resource.type))
return; // already did this one
if (_.contains(["head", "body"], resource.type)) {
// already did this one
return;
}
// If we're going to write a legacy prelink file later, track the
// original form of the resource object (with the source in a Buffer,
@@ -1481,8 +1494,9 @@ _.extend(Isopack.prototype, {
packageVariables = [];
var packageVariableNames = {};
_.each(unibuild.declaredExports, function (symbol) {
if (_.has(packageVariableNames, symbol.name))
if (_.has(packageVariableNames, symbol.name)) {
return;
}
packageVariables.push({
name: symbol.name,
export: symbol.testOnly? "tests" : true
@@ -1512,8 +1526,9 @@ _.extend(Isopack.prototype, {
prelinkData = new Buffer(prelinkFile.source, 'utf8');
_.each(results.assignedVariables, function (name) {
if (_.has(packageVariableNames, name))
if (_.has(packageVariableNames, name)) {
return;
}
packageVariables.push({
name: name
});
@@ -1724,8 +1739,9 @@ _.extend(Isopack.prototype, {
title: "compiling " + isopacketName + " packages for the tool"
}, function () {
isopacketBuildContext.isopackCache.buildLocalPackages(packages);
if (buildmessage.jobHasMessages())
if (buildmessage.jobHasMessages()) {
return;
}
var image = bundler.buildJsImage({
name: "isopacket-" + isopacketName,
@@ -1733,8 +1749,9 @@ _.extend(Isopack.prototype, {
isopackCache: isopacketBuildContext.isopackCache,
use: packages
}).image;
if (buildmessage.jobHasMessages())
if (buildmessage.jobHasMessages()) {
return;
}
image.write(
builder.enter(files.pathJoin('isopackets', isopacketName)));
@@ -1798,8 +1815,9 @@ _.extend(Isopack.prototype, {
var self = this;
var packages = {};
var processUse = function (use) {
if (use.weak || use.unordered)
if (use.weak || use.unordered) {
return;
}
// Only include real packages, not isobuild:* pseudo-packages.
if (compiler.isIsobuildFeaturePackage(use.package)) {
return;

View File

@@ -20,10 +20,11 @@ const APP_PRELINK_CACHE = new LRU({
});
var packageDot = function (name) {
if (/^[a-zA-Z][a-zA-Z0-9]*$/.exec(name))
if (/^[a-zA-Z][a-zA-Z0-9]*$/.exec(name)) {
return "Package." + name;
else
} else {
return "Package['" + name + "']";
}
};
///////////////////////////////////////////////////////////////////////////////
@@ -64,8 +65,9 @@ _.extend(Module.prototype, {
_.each(self.files, function (file) {
var m = 0;
_.each(file.source.split('\n'), function (line) {
if (line.length <= ignoreOver && line.length > m)
if (line.length <= ignoreOver && line.length > m) {
m = line.length;
}
});
maxInFile.push(m);
});
@@ -145,8 +147,9 @@ _.extend(Module.prototype, {
// Emit each file
_.each(self.files, function (file) {
if (!_.isEmpty(chunks))
if (!_.isEmpty(chunks)) {
chunks.push("\n\n\n\n\n\n");
}
chunks.push(file.getPrelinkedOutput({
sourceWidth: sourceWidth,
noLineNumbers: self.noLineNumbers
@@ -187,13 +190,15 @@ var buildSymbolTree = function (symbolMap) {
var walk = ret;
_.each(parts, function (part) {
if (! (part in walk))
if (! (part in walk)) {
walk[part] = {};
}
walk = walk[part];
});
if (value)
if (value) {
walk[lastPart] = value;
}
});
return ret;
@@ -275,8 +280,9 @@ _.extend(File.prototype, {
return (ASSIGNED_GLOBALS_CACHE[self.sourceHash] =
_.keys(findAssignedGlobals(self.source)));
} catch (e) {
if (!e.$ParseError)
if (!e.$ParseError) {
throw e;
}
var errorOptions = {
file: self.servePath,
@@ -502,8 +508,9 @@ _.extend(File.prototype, {
// (bannerWidth - 6); if bannerWidth is not provided, the smallest width that
// fits is used.
var banner = function (lines, bannerWidth) {
if (!bannerWidth)
if (!bannerWidth) {
bannerWidth = 6 + _.max(lines, function (x) { return x.length; }).length;
}
var divider = dividerLine(bannerWidth);
var spacer = "// " + new Array(bannerWidth - 6 + 1).join(' ') + " //\n";
@@ -611,8 +618,9 @@ var getHeader = function (options) {
var getImportCode = function (imports, header, omitvar) {
var self = this;
if (_.isEmpty(imports))
if (_.isEmpty(imports)) {
return "";
}
// Imports
var scratch = {};
@@ -744,8 +752,10 @@ var fullLink = Profile("linker.fullLink", function (inputFiles, {
assignedVariables = module.computeAssignedVariables();
return buildmessage.jobHasMessages();
});
if (failed)
return []; // recover by pretending there are no files
if (failed) {
// recover by pretending there are no files
return [];
}
// Otherwise we're making a package and we have to actually combine the files
// into a single scope.
@@ -761,8 +771,9 @@ var fullLink = Profile("linker.fullLink", function (inputFiles, {
return _.map(prelinkedFiles, function (file) {
if (file.sourceMap) {
if (includeSourceMapInstructions)
if (includeSourceMapInstructions) {
header = SOURCE_MAP_INSTRUCTIONS_COMMENT + "\n\n" + header;
}
// Bias the source map by the length of the header without
// (fully) parsing and re-serializing it. (We used to do this
@@ -771,8 +782,10 @@ var fullLink = Profile("linker.fullLink", function (inputFiles, {
// if we could use "index maps" for this (the 'sections' key),
// as that would let us avoid even JSON-parsing the source map,
// but that doesn't seem to be supported by Firefox yet.
if (header.charAt(header.length - 1) !== "\n")
header += "\n"; // make sure it's a whole number of lines
if (header.charAt(header.length - 1) !== "\n") {
// make sure it's a whole number of lines
header += "\n";
}
var headerLines = header.split('\n').length - 1;
var sourceMap = file.sourceMap;
sourceMap.mappings = (new Array(headerLines + 1).join(';')) +

View File

@@ -20,8 +20,9 @@ var meteorNpm = exports;
var tmpDirs = [];
cleanup.onExit(function () {
_.each(tmpDirs, function (dir) {
if (files.exists(dir))
if (files.exists(dir)) {
files.rm_recursive(dir);
}
});
});
@@ -56,8 +57,9 @@ meteorNpm.updateDependencies = function (packageName,
try {
files.rename(packageNpmDir, newPackageNpmDir);
} catch (e) {
if (e.code !== 'ENOENT')
if (e.code !== 'ENOENT') {
throw e;
}
// It didn't exist, which is exactly what we wanted.
return false;
}
@@ -102,8 +104,9 @@ meteorNpm.updateDependencies = function (packageName,
// Some other exception -- let it propagate.
throw e;
} finally {
if (files.exists(newPackageNpmDir))
if (files.exists(newPackageNpmDir)) {
files.rm_recursive(newPackageNpmDir);
}
tmpDirs = _.without(tmpDirs, newPackageNpmDir);
}
@@ -125,11 +128,13 @@ meteorNpm.dependenciesArePortable = function (packageNpmDir) {
var search = function (dir) {
return _.find(files.readdir(dir), function (itemName) {
if (itemName.match(/\.node$/))
if (itemName.match(/\.node$/)) {
return true;
}
var item = files.pathJoin(dir, itemName);
if (files.lstat(item).isDirectory())
if (files.lstat(item).isDirectory()) {
return search(item);
}
}) || false;
};
@@ -159,13 +164,15 @@ var updateExistingNpmDirectory = function (packageName, newPackageNpmDir,
packageNpmDir, npmDependencies,
quiet) {
// sanity check on contents of .npm directory
if (!files.stat(packageNpmDir).isDirectory())
if (!files.stat(packageNpmDir).isDirectory()) {
throw new Error("Corrupted .npm directory -- should be a directory: " +
packageNpmDir);
if (!files.exists(files.pathJoin(packageNpmDir, 'npm-shrinkwrap.json')))
}
if (!files.exists(files.pathJoin(packageNpmDir, 'npm-shrinkwrap.json'))) {
throw new Error(
"Corrupted .npm directory -- can't find npm-shrinkwrap.json in " +
packageNpmDir);
}
// We need to rebuild all node modules when the Node version
// changes, in case there are some binary ones. Technically this is
@@ -177,15 +184,17 @@ var updateExistingNpmDirectory = function (packageName, newPackageNpmDir,
oldNodeVersion = files.readFile(
files.pathJoin(packageNpmDir, 'node_modules', '.node_version'), 'utf8');
} catch (e) {
if (e.code !== 'ENOENT')
if (e.code !== 'ENOENT') {
throw e;
}
// Use the Node version from the last release where we didn't
// drop this file.
oldNodeVersion = 'v0.8.24';
}
if (oldNodeVersion !== currentNodeCompatibilityVersion())
if (oldNodeVersion !== currentNodeCompatibilityVersion()) {
files.rm_recursive(nodeModulesDir);
}
}
// If the node modules directory exists but doesn't have .package.json and
@@ -202,8 +211,9 @@ var updateExistingNpmDirectory = function (packageName, newPackageNpmDir,
// filesystem. node_modules may be absent due to a change in Node version or
// when `meteor add`ing a cloned package for the first time (node_modules is
// excluded by .gitignore)
if (! files.exists(nodeModulesDir))
if (! files.exists(nodeModulesDir)) {
files.mkdir(nodeModulesDir);
}
var installedDependenciesTree = getInstalledDependenciesTree(packageNpmDir);
var installedDependencies = treeToDependencies(installedDependenciesTree);
@@ -232,8 +242,9 @@ var updateExistingNpmDirectory = function (packageName, newPackageNpmDir,
}
}
if (! quiet)
if (! quiet) {
logUpdateDependencies(packageName, npmDependencies);
}
var preservedShrinkwrap = {dependencies: {}};
_.each(shrinkwrappedDependencies, function (version, name) {
@@ -281,8 +292,9 @@ var updateExistingNpmDirectory = function (packageName, newPackageNpmDir,
var createFreshNpmDirectory = function (packageName, newPackageNpmDir,
packageNpmDir, npmDependencies, quiet) {
if (! quiet)
if (! quiet) {
logUpdateDependencies(packageName, npmDependencies);
}
makeNewPackageNpmDir(newPackageNpmDir);
// install dependencies
@@ -370,8 +382,9 @@ var runNpmCommand = function (args, cwd) {
args.join(' ') + ' ...\n');
}
if (cwd)
if (cwd) {
cwd = files.convertToOSPath(cwd);
}
// It looks like some npm commands (such as build commands, specifically on
// Windows) rely on having a global node binary present.
@@ -389,8 +402,9 @@ var runNpmCommand = function (args, cwd) {
var child_process = require('child_process');
child_process.execFile(
npmPath, args, opts, function (err, stdout, stderr) {
if (meteorNpm._printNpmCalls)
if (meteorNpm._printNpmCalls) {
process.stdout.write(err ? 'failed\n' : 'done\n');
}
future.return({
success: ! err,
@@ -435,8 +449,9 @@ var constructPackageJson = function (packageName, newPackageNpmDir,
var getInstalledDependenciesTree = function (dir) {
var result = runNpmCommand(["ls", "--json"], dir);
if (result.success)
if (result.success) {
return JSON.parse(result.stdout);
}
buildmessage.error(`couldn't read npm version lock information: ${result.error}`);
// Recover by returning false from updateDependencies
@@ -455,10 +470,11 @@ var getShrinkwrappedDependenciesTree = function (dir) {
//
// If more logic is added here, it should probably go in minimizeModule too.
var canonicalVersion = function (depObj) {
if (utils.isUrlWithSha(depObj.from))
if (utils.isUrlWithSha(depObj.from)) {
return depObj.from;
else
} else {
return depObj.version;
}
};
// map the structure returned from `npm ls` or shrinkwrap.json into
@@ -545,9 +561,10 @@ firstTen.join("\n"));
};
var installFromShrinkwrap = function (dir) {
if (! files.exists(files.pathJoin(dir, "npm-shrinkwrap.json")))
if (! files.exists(files.pathJoin(dir, "npm-shrinkwrap.json"))) {
throw new Error(
"Can't call `npm install` without a npm-shrinkwrap.json file present");
}
ensureConnected();

View File

@@ -8,8 +8,9 @@ var files = require('../fs/files.js');
var catalog = require('../packaging/catalog/catalog.js');
function toArray (x) {
if (_.isArray(x))
if (_.isArray(x)) {
return x;
}
return x ? [x] : [];
}
@@ -205,8 +206,9 @@ _.extend(PackageAPI.prototype, {
try {
var parsed = utils.parsePackageConstraint(name);
} catch (e) {
if (!e.versionParserError)
if (!e.versionParserError) {
throw e;
}
buildmessage.error(e.message, {useMyCaller: true});
// recover by ignoring
continue;
@@ -267,8 +269,9 @@ _.extend(PackageAPI.prototype, {
try {
var parsed = utils.parsePackageConstraint(name);
} catch (e) {
if (!e.versionParserError)
if (!e.versionParserError) {
throw e;
}
buildmessage.error(e.message, {useMyCaller: true});
// recover by ignoring
continue;

View File

@@ -92,15 +92,23 @@ var loadOrderSort = function (sourceProcessorSet, arch) {
// deeper paths loaded first.
var len_a = a_parts.length;
var len_b = b_parts.length;
if (len_a < len_b) return 1;
if (len_b < len_a) return -1;
if (len_a < len_b) {
return 1;
}
if (len_b < len_a) {
return -1;
}
// Otherwise compare path components lexicographically.
for (var i = 0; i < len_a; ++i) {
var a_part = a_parts[i];
var b_part = b_parts[i];
if (a_part < b_part) return -1;
if (b_part < a_part) return 1;
if (a_part < b_part) {
return -1;
}
if (b_part < a_part) {
return 1;
}
}
// Never reached unless there are somehow duplicate paths.
@@ -125,7 +133,9 @@ var splitConstraint = function (c) {
// for some reason). Skips lines that start with an exclamation point.
var getExcerptFromReadme = function (text) {
// Don't waste time parsing if the document is empty.
if (! text) return "";
if (! text) {
return "";
}
// Split into lines with Commonmark.
var commonmark = require('commonmark');
@@ -155,7 +165,9 @@ var getExcerptFromReadme = function (text) {
});
// If we have not found anything, we are done.
if (_.isEmpty(relevantNodes)) return "";
if (_.isEmpty(relevantNodes)) {
return "";
}
// For now, we will do the simple thing of just taking the raw markdown from
// the start of the excerpt to the end.
@@ -406,9 +418,10 @@ _.extend(PackageSource.prototype, {
self.name = name;
if (options.sources && ! _.isEmpty(options.sources) &&
(! options.sourceRoot || ! options.serveRoot))
(! options.sourceRoot || ! options.serveRoot)) {
throw new Error("When source files are given, sourceRoot and " +
"serveRoot must be specified");
}
// sourceRoot is a relative file system path, one slash identifies a root
// relative to some starting location
@@ -446,8 +459,9 @@ _.extend(PackageSource.prototype, {
self.architectures.push(sourceArch);
if (! self._checkCrossUnibuildVersionConstraints())
if (! self._checkCrossUnibuildVersionConstraints()) {
throw new Error("only one unibuild, so how can consistency check fail?");
}
},
// Initialize a PackageSource from a package.js-style package directory. Uses
@@ -497,8 +511,9 @@ _.extend(PackageSource.prototype, {
self.isCore = true;
}
}
if (! files.exists(self.sourceRoot))
if (! files.exists(self.sourceRoot)) {
throw new Error("putative package directory " + dir + " doesn't exist?");
}
var fileAndDepLoader = null;
var npmDependencies = null;
@@ -581,8 +596,9 @@ _.extend(PackageSource.prototype, {
var parsedVersion = packageVersionParser.getValidServerVersion(
value);
} catch (e) {
if (!e.versionParserError)
if (!e.versionParserError) {
throw e;
}
buildmessage.error(
"The package version " + value + " (specified with Package.describe) "
+ "is not a valid Meteor package version.\n"
@@ -1006,8 +1022,9 @@ _.extend(PackageSource.prototype, {
try {
utils.validatePackageName(self.name);
} catch (e) {
if (!e.versionParserError)
if (!e.versionParserError) {
throw e;
}
buildmessage.error(e.message);
// recover by ignoring
}
@@ -1116,7 +1133,9 @@ _.extend(PackageSource.prototype, {
newConstraint.push(packages[dep.package]);
}
});
if (_.isEmpty(newConstraint)) return dep;
if (_.isEmpty(newConstraint)) {
return dep;
}
dep.constraint = _.reduce(newConstraint,
function(x, y) {
return x + " || " + y;
@@ -1183,8 +1202,9 @@ _.extend(PackageSource.prototype, {
!! _.find(api.uses[arch], function (u) {
return u.package === "meteor";
});
if (! alreadyDependsOnMeteor)
if (! alreadyDependsOnMeteor) {
api.uses[arch].unshift({ package: "meteor" });
}
}
// Each unibuild has its own separate WatchSet. This is so that, eg, a test
@@ -1297,8 +1317,9 @@ _.extend(PackageSource.prototype, {
try {
var realpath = files.realpath(absPath, realpathCache);
} catch (e) {
if (!e || e.code !== 'ELOOP')
if (!e || e.code !== 'ELOOP') {
throw e;
}
// else leave realpath undefined
}
if (realpath === undefined || _.has(seenPaths, realpath)) {
@@ -1336,8 +1357,10 @@ _.extend(PackageSource.prototype, {
// remove trailing slash
dir = dir.substr(0, dir.length - 1);
if (checkForInfiniteRecursion(dir))
return []; // pretend we found no files
if (checkForInfiniteRecursion(dir)) {
// pretend we found no files
return [];
}
// Find source files in this directory.
sources.push(...readAndWatchDirectory(dir, sourceReadOptions));
@@ -1365,8 +1388,9 @@ _.extend(PackageSource.prototype, {
files.pathSep + 'client' +
files.pathSep + 'compatibility' + files.pathSep;
if ((files.pathSep + relPath).indexOf(clientCompatSubstr) !== -1)
if ((files.pathSep + relPath).indexOf(clientCompatSubstr) !== -1) {
sourceObj.fileOptions = {bare: true};
}
}
return sourceObj;
});
@@ -1378,16 +1402,19 @@ _.extend(PackageSource.prototype, {
const assets = [];
if (!_.isEmpty(assetDirs)) {
if (!_.isEqual(assetDirs, [assetDir]))
if (!_.isEqual(assetDirs, [assetDir])) {
throw new Error("Surprising assetDirs: " + JSON.stringify(assetDirs));
}
while (!_.isEmpty(assetDirs)) {
dir = assetDirs.shift();
// remove trailing slash
dir = dir.substr(0, dir.length - 1);
if (checkForInfiniteRecursion(dir))
return []; // pretend we found no files
if (checkForInfiniteRecursion(dir)) {
// pretend we found no files
return [];
}
// Find asset files in this directory.
var assetsAndSubdirs = readAndWatchDirectory(dir, {
@@ -1446,10 +1473,11 @@ _.extend(PackageSource.prototype, {
options = options || {};
var ret = self._computeDependencyMetadata(options);
if (! ret) {
if (options.logError)
if (options.logError) {
return null;
else
} else {
throw new Error("inconsistent dependency constraint across unibuilds?");
}
}
return ret;
},
@@ -1479,16 +1507,18 @@ _.extend(PackageSource.prototype, {
var processUse = function (use) {
// We don't have to build weak or unordered deps first (eg they can't
// contribute to a plugin).
if (use.weak || use.unordered)
if (use.weak || use.unordered) {
return;
}
// Only include real packages, not isobuild:* pseudo-packages.
if (compiler.isIsobuildFeaturePackage(use.package)) {
return;
}
var packageInfo = packageMap.getInfo(use.package);
if (! packageInfo)
if (! packageInfo) {
throw Error("Depending on unknown package " + use.package);
}
packages[use.package] = true;
};
@@ -1639,8 +1669,9 @@ _.extend(PackageSource.prototype, {
// We can't really have a weak implies (what does that even mean?) but
// we check for that elsewhere.
if ((use.weak && options.skipWeak) ||
(use.unordered && options.skipUnordered))
(use.unordered && options.skipUnordered)) {
return;
}
if (!_.has(dependencies, use.package)) {
dependencies[use.package] = {

View File

@@ -103,8 +103,9 @@ var sessionMethodCaller = function (methodName, options) {
conn.apply(methodName, args, fiberHelpers.firstTimeResolver(fut));
if (options.timeout !== undefined) {
var timer = setTimeout(fiberHelpers.bindEnvironment(function () {
if (!fut.isResolved())
if (!fut.isResolved()) {
fut.throw(new Error('Method call timed out'));
}
}), options.timeout);
}
try {
@@ -113,8 +114,9 @@ var sessionMethodCaller = function (methodName, options) {
if (timer) {
clearTimeout(timer);
}
if (! options.connection)
if (! options.connection) {
conn.close();
}
}
if (result && result.session) {
auth.setSessionId(config.getAccountsDomain(), result.session);
@@ -125,8 +127,9 @@ var sessionMethodCaller = function (methodName, options) {
var readSessionData = function () {
var sessionPath = config.getSessionFilePath();
if (! files.exists(sessionPath))
if (! files.exists(sessionPath)) {
return {};
}
return JSON.parse(files.readFile(sessionPath, { encoding: 'utf8' }));
};
@@ -135,8 +138,9 @@ var writeSessionData = function (data) {
var tries = 0;
while (true) {
if (tries++ > 10)
if (tries++ > 10) {
throw new Error("can't find a unique name for temporary file?");
}
// Create a temporary file in the same directory where we
// ultimately want to write the session file. Use the exclusive
@@ -168,10 +172,12 @@ var writeSessionData = function (data) {
};
var getSession = function (sessionData, domain) {
if (typeof (sessionData.sessions) !== "object")
if (typeof (sessionData.sessions) !== "object") {
sessionData.sessions = {};
if (typeof (sessionData.sessions[domain]) !== "object")
}
if (typeof (sessionData.sessions[domain]) !== "object") {
sessionData.sessions[domain] = {};
}
return sessionData.sessions[domain];
};
@@ -180,9 +186,9 @@ var getSession = function (sessionData, domain) {
// We previously used:
// - "galaxy": a login to a legacy Galaxy prototype server
var ensureSessionType = function (session, type) {
if (! _.has(session, 'type'))
if (! _.has(session, 'type')) {
session.type = type;
else if (session.type !== type) {
} else if (session.type !== type) {
// Blow away whatever was there. We lose pendingRevokes but that's
// OK since this should never happen in normal operation. (It
// would happen if the Meteor Accounts server mode somewhere else
@@ -219,15 +225,17 @@ var logOutSession = function (session) {
delete session.registrationUrl;
if (_.has(session, 'token')) {
if (! (session.pendingRevoke instanceof Array))
if (! (session.pendingRevoke instanceof Array)) {
session.pendingRevoke = [];
}
// Delete the auth token itself, but save the tokenId, which is
// useless for authentication. The next time we're online, we'll
// send the tokenId to the server to revoke the token on the
// server side too.
if (typeof session.tokenId === "string")
if (typeof session.tokenId === "string") {
session.pendingRevoke.push(session.tokenId);
}
delete session.token;
delete session.tokenId;
}
@@ -251,8 +259,9 @@ var removePendingRevoke = function (domain, tokenIds) {
var data = readSessionData();
var session = getSession(data, domain);
session.pendingRevoke = _.difference(session.pendingRevoke, tokenIds);
if (! session.pendingRevoke.length)
if (! session.pendingRevoke.length) {
delete session.pendingRevoke;
}
writeSessionData(data);
};
@@ -277,8 +286,9 @@ var tryRevokeOldTokens = function (options) {
var domainsWithRevokedTokens = [];
_.each(readSessionData().sessions || {}, function (session, domain) {
if (session.pendingRevoke &&
session.pendingRevoke.length)
session.pendingRevoke.length) {
domainsWithRevokedTokens.push(domain);
}
});
var logoutFailWarning = function (domain) {
@@ -296,8 +306,9 @@ var tryRevokeOldTokens = function (options) {
var data = readSessionData();
var session = data.sessions[domain] || {};
var tokenIds = session.pendingRevoke || [];
if (! tokenIds.length)
if (! tokenIds.length) {
return;
}
var url;
@@ -437,12 +448,13 @@ var oauthFlow = function (conn, options) {
var doInteractivePasswordLogin = function (options) {
var loginData = {};
if (_.has(options, 'username'))
if (_.has(options, 'username')) {
loginData.username = options.username;
else if (_.has(options, 'email'))
} else if (_.has(options, 'email')) {
loginData.email = options.email;
else
} else {
throw new Error("Need username or email");
}
if (_.has(options, 'password')) {
loginData.password = options.password;
@@ -457,8 +469,9 @@ var doInteractivePasswordLogin = function (options) {
var conn = options.connection || openAccountsConnection();
var maybeCloseConnection = function () {
if (! options.connection)
if (! options.connection) {
conn.close();
}
};
while (true) {
@@ -577,12 +590,13 @@ exports.logoutCommand = function (options) {
tryRevokeOldTokens({ firstTry: true });
if (wasLoggedIn)
if (wasLoggedIn) {
Console.error("Logged out.");
else
} else {
// We called logOutAllSessions/writeSessionData anyway, out of an
// abundance of caution.
Console.error("Not logged in.");
}
};
// If this is fully set up account (with a username and password), or
@@ -596,16 +610,18 @@ exports.logoutCommand = function (options) {
// credentials). Defaults to false.
var alreadyPolledForRegistration = false;
exports.pollForRegistrationCompletion = function (options) {
if (alreadyPolledForRegistration)
if (alreadyPolledForRegistration) {
return;
}
alreadyPolledForRegistration = true;
options = options || {};
var data = readSessionData();
var session = getSession(data, config.getAccountsDomain());
if (session.username || ! session.token)
if (session.username || ! session.token) {
return;
}
// We are logged in but we don't yet have a username. Ask the server
// if a username was chosen since we last checked.
@@ -626,8 +642,9 @@ exports.pollForRegistrationCompletion = function (options) {
}
connection.call('getUsername', function (err, result) {
if (fut.isResolved())
if (fut.isResolved()) {
return;
}
if (err) {
// If anything went wrong, return null just as we would have if
@@ -766,8 +783,9 @@ exports.registerOrLogIn = withAccountsConnection(function (connection) {
);
} catch (e) {
stopSpinner();
if (e.errorType !== "Meteor.Error")
if (e.errorType !== "Meteor.Error") {
throw e;
}
Console.error(
"When you've picked your password, run " +
Console.command("'meteor login'") + " to log in.");
@@ -811,8 +829,9 @@ exports.maybePrintRegistrationLink = function (options) {
var session = getSession(data, config.getAccountsDomain());
if (session.userId && ! session.username && session.registrationUrl) {
if (options.leadingNewline)
if (options.leadingNewline) {
Console.error();
}
if (options.onlyAllowIfRegistered) {
// A stronger message: we're going to not allow whatever they were trying
// to do!

View File

@@ -33,8 +33,9 @@ var getUniverse = function () {
if (files.inCheckout()) {
var p = files.pathJoin(files.getCurrentToolsDir(), 'universe');
if (files.exists(p))
if (files.exists(p)) {
universe = files.readFile(p, 'utf8').trim();
}
}
}
@@ -47,15 +48,16 @@ var isLocalUniverse = function () {
var localhostOffset = function (portOffset) {
var match = getUniverse().match(/^localhost(:([\d]+))?$/);
if (! match)
if (! match) {
throw new Error("not a local universe?");
}
return "localhost:" + (parseInt(match[2] || "80") + portOffset);
};
var getAuthServiceHost = function () {
if (! isLocalUniverse())
if (! isLocalUniverse()) {
return universe;
else
} else {
// Special case for local development. Point
// $METEOR_CHECKOUT/universe at the place where you are running
// frontpage (eg, localhost:3000), and run the accounts server ten
@@ -63,15 +65,17 @@ var getAuthServiceHost = function () {
// cd meteor-accounts
// ROOT_URL=http://localhost:3010/auth curmeteor -p 3010
return localhostOffset(10);
}
};
// Given a hostname, add "http://" or "https://" as
// appropriate. (localhost gets http; anything else is always https.)
var addScheme = function (host) {
if (host.match(/^localhost(:\d+)?$/))
if (host.match(/^localhost(:\d+)?$/)) {
return "http://" + host;
else
} else {
return "https://" + host;
}
};
var config = exports;
@@ -112,8 +116,9 @@ _.extend(exports, {
// URL for the DDP interface to the meteor build farm, typically
// "https://build.meteor.com".
getBuildFarmUrl: function () {
if (process.env.METEOR_BUILD_FARM_URL)
if (process.env.METEOR_BUILD_FARM_URL) {
return process.env.METEOR_BUILD_FARM_URL;
}
var host = config.getBuildFarmDomain();
return addScheme(host);
@@ -136,8 +141,9 @@ _.extend(exports, {
// base universe port number (that is, the Meteor Accounts port
// number) plus 20.
getPackageServerUrl: function () {
if (process.env.METEOR_PACKAGE_SERVER_URL)
if (process.env.METEOR_PACKAGE_SERVER_URL) {
return process.env.METEOR_PACKAGE_SERVER_URL;
}
var host = config.getPackageServerDomain();
return addScheme(host);
@@ -190,7 +196,9 @@ _.extend(exports, {
// server we actually use.
getPackageServerFilePrefix: function (serverUrl) {
var self = this;
if (!serverUrl) serverUrl = self.getPackageServerUrl();
if (!serverUrl) {
serverUrl = self.getPackageServerUrl();
}
// Chop off http:// and https:// and trailing slashes.
serverUrl = serverUrl.replace(/^\https:\/\//, '');
@@ -270,14 +278,17 @@ _.extend(exports, {
// scheme.
if (process.env.DEPLOY_HOSTNAME) {
host = process.env.DEPLOY_HOSTNAME;
if (host.match(/^http/))
return host; // allow it to contain a URL scheme
if (host.match(/^http/)) {
// allow it to contain a URL scheme
return host;
}
} else {
// Otherwise, base it on the universe.
if (isLocalUniverse())
if (isLocalUniverse()) {
throw new Error("local development of deploy server not supported");
else
} else {
host = getUniverse().replace(/^www\./, 'deploy.');
}
}
return addScheme(host);
@@ -286,8 +297,10 @@ _.extend(exports, {
// URL from which the update manifest may be fetched, eg
// 'https://update.meteor.com/manifest.json'
getUpdateManifestUrl: function () {
if (isLocalUniverse())
u = "www.meteor.com"; // localhost can't run the manifest server
if (isLocalUniverse()) {
// localhost can't run the manifest server
u = "www.meteor.com";
}
var host = getUniverse().replace(/^www\./, 'update.');
return addScheme(host) + "/manifest.json";
@@ -312,10 +325,11 @@ _.extend(exports, {
// privileged port, so you can set DISCOVERY_PORT to override. (A
// better solution would probably be to spin up a local VM.)
getDiscoveryPort: function () {
if (process.env.DISCOVERY_PORT)
if (process.env.DISCOVERY_PORT) {
return parseInt(process.env.DISCOVERY_PORT);
else
} else {
return 443;
}
},
// It's easy to forget that you're in an alternate universe (and
@@ -323,7 +337,8 @@ _.extend(exports, {
// in production mode, print a quick hint about the universe you're
// in.
printUniverseBanner: function () {
if (! config.isProduction())
if (! config.isProduction()) {
process.stderr.write('[Universe: ' + config.getUniverse() + ']\n');
}
}
});

View File

@@ -59,8 +59,9 @@ var deployRpc = function (options) {
options = _.clone(options);
options.headers = _.clone(options.headers || {});
if (options.headers.cookie)
if (options.headers.cookie) {
throw new Error("sorry, can't combine cookie headers yet");
}
// XXX: Reintroduce progress for upload
try {
@@ -172,8 +173,9 @@ var authedRpc = function (options) {
return preflight ? { } : deployRpc(rpcOptions);
}
if (infoResult.errorMessage)
if (infoResult.errorMessage) {
return infoResult;
}
var info = infoResult.payload;
if (! _.has(info, 'protection')) {
@@ -301,8 +303,9 @@ var canonicalizeSite = function (site) {
}
var url = site;
if (!url.match(':\/\/'))
if (!url.match(':\/\/')) {
url = 'http://' + url;
}
var parsed = require('url').parse(url);
@@ -336,12 +339,14 @@ var canonicalizeSite = function (site) {
// stats server.
// - buildOptions: the 'buildOptions' argument to the bundler
var bundleAndDeploy = function (options) {
if (options.recordPackageUsage === undefined)
if (options.recordPackageUsage === undefined) {
options.recordPackageUsage = true;
}
var site = canonicalizeSite(options.site);
if (! site)
if (! site) {
return 1;
}
// We should give a username/password prompt if the user was logged in
// but the credentials are expired, unless the user is logged in but
@@ -392,8 +397,9 @@ var bundleAndDeploy = function (options) {
title: "preparing to deploy",
rootPath: process.cwd()
}, function () {
if (options.settingsFile)
if (options.settingsFile) {
settings = files.getSettings(options.settingsFile);
}
});
if (! messages.hasMessages()) {
@@ -406,8 +412,9 @@ var bundleAndDeploy = function (options) {
providePackageJSONForUnavailableBinaryDeps: !!process.env.METEOR_BINARY_DEP_WORKAROUND,
});
if (bundleResult.errors)
if (bundleResult.errors) {
messages = bundleResult.errors;
}
}
if (messages.hasMessages()) {
@@ -470,8 +477,9 @@ var bundleAndDeploy = function (options) {
var deleteApp = function (site) {
site = canonicalizeSite(site);
if (! site)
if (! site) {
return 1;
}
var result = authedRpc({
method: 'DELETE',
@@ -568,9 +576,10 @@ var checkAuthThenSendRpc = function (site, operation, what) {
// site's database.
var temporaryMongoUrl = function (site) {
site = canonicalizeSite(site);
if (! site)
if (! site) {
// canonicalizeSite printed an error
return null;
}
var result = checkAuthThenSendRpc(site, 'mongo', 'open a mongo connection');
@@ -583,8 +592,9 @@ var temporaryMongoUrl = function (site) {
var logs = function (site) {
site = canonicalizeSite(site);
if (! site)
if (! site) {
return 1;
}
var result = checkAuthThenSendRpc(site, 'logs', 'view logs');
@@ -599,8 +609,9 @@ var logs = function (site) {
var listAuthorized = function (site) {
site = canonicalizeSite(site);
if (! site)
if (! site) {
return 1;
}
var result = deployRpc({
operation: 'info',
@@ -632,11 +643,12 @@ var listAuthorized = function (site) {
Console.info((auth.loggedInUsername() || "<you>"));
_.each(info.authorized, function (username) {
if (username)
if (username) {
// Current username rules don't let you register anything that we might
// want to split over multiple lines (ex: containing a space), but we
// don't want confusion if we ever change some implementation detail.
Console.rawInfo(username + "\n");
}
});
return 0;
}
@@ -645,9 +657,10 @@ var listAuthorized = function (site) {
// action is "add" or "remove"
var changeAuthorized = function (site, action, username) {
site = canonicalizeSite(site);
if (! site)
if (! site) {
// canonicalizeSite will have already printed an error
return 1;
}
var result = authedRpc({
method: 'POST',
@@ -670,9 +683,10 @@ var changeAuthorized = function (site, action, username) {
var claim = function (site) {
site = canonicalizeSite(site);
if (! site)
if (! site) {
// canonicalizeSite will have already printed an error
return 1;
}
// Check to see if it's even a claimable site, so that we can print
// a more appropriate message than we'd get if we called authedRpc
@@ -690,10 +704,11 @@ var claim = function (site) {
}
if (infoResult.payload && infoResult.payload.protection === "account") {
if (infoResult.payload.authorized)
if (infoResult.payload.authorized) {
Console.error("That site already belongs to you.\n");
else
} else {
Console.error("Sorry, that site belongs to someone else.\n");
}
return 1;
}

View File

@@ -43,10 +43,12 @@ var ServiceConnection = function (endpointUrl, options) {
retry: false,
onConnected: function () {
self.connected = true;
if (!self.currentFuture)
if (!self.currentFuture) {
throw Error("nobody waiting for connection?");
if (self.currentFuture !== connectFuture)
}
if (self.currentFuture !== connectFuture) {
throw Error("waiting for something that isn't connection?");
}
self.currentFuture = null;
connectFuture.return();
}
@@ -69,8 +71,9 @@ var ServiceConnection = function (endpointUrl, options) {
//
// This ought to have happened before we successfully connect, unless
// somebody adds other calls to forced reconnect to Meteor...
if (connectFuture.isResolved())
if (connectFuture.isResolved()) {
throw Error("disconnect before connect?");
}
// Otherwise, ignore this error. We're going to reconnect!
return;
}
@@ -99,8 +102,9 @@ _.extend(ServiceConnection.prototype, {
apply: function (...args) {
var self = this;
if (self.currentFuture)
if (self.currentFuture) {
throw Error("Can't wait on two things at once!");
}
self.currentFuture = new Future;
args.push(function (err, result) {
@@ -124,8 +128,9 @@ _.extend(ServiceConnection.prototype, {
subscribeAndWait: function (...args) {
var self = this;
if (self.currentFuture)
if (self.currentFuture) {
throw Error("Can't wait on two things at once!");
}
var subFuture = self.currentFuture = new Future;
args.push({

View File

@@ -131,8 +131,9 @@ exports.updateServerPackageData = function (dataStore, options) {
var _updateServerPackageData = function (dataStore, options) {
var self = this;
options = options || {};
if (dataStore === null)
if (dataStore === null) {
throw Error("Data store expected");
}
var done = false;
var ret = {resetData: false};
@@ -277,11 +278,13 @@ var bundleSource = function (isopack, includeSources, packageDir) {
// from inside an app, whereas the package-source-tree .versions file
// is only used for standalone packages
var packageMapFilename = files.pathJoin(sourcePackageDir, '.versions');
if (files.exists(packageMapFilename))
if (files.exists(packageMapFilename)) {
throw Error(".versions file already exists? " + packageMapFilename);
}
var pluginProviderPackageMap = isopack.pluginProviderPackageMap;
if (! pluginProviderPackageMap)
if (! pluginProviderPackageMap) {
throw Error("no pluginProviderPackageMap on isopack?");
}
var packageMapFile = new projectContextModule.PackageMapFile({
filename: packageMapFilename
});
@@ -390,8 +393,9 @@ var createBuiltPackage = function (conn, isopack) {
buildmessage.enterJob("bundling build for " + name, function () {
bundleResult = bundleBuild(isopack);
});
if (buildmessage.jobHasMessages())
if (buildmessage.jobHasMessages()) {
return;
}
return bundleResult;
};
@@ -408,15 +412,17 @@ var publishBuiltPackage = function (conn, isopack, bundleResult) {
buildArchitectures: isopack.buildArchitectures()
});
});
if (buildmessage.jobHasMessages())
if (buildmessage.jobHasMessages()) {
return;
}
buildmessage.enterJob("uploading build", function () {
uploadFile(uploadInfo.uploadUrl,
bundleResult.buildTarball);
});
if (buildmessage.jobHasMessages())
if (buildmessage.jobHasMessages()) {
return;
}
buildmessage.enterJob('publishing package build for ' + name, function () {
callPackageServerBM(conn, 'publishPackageBuild',
@@ -424,8 +430,9 @@ var publishBuiltPackage = function (conn, isopack, bundleResult) {
bundleResult.tarballHash,
bundleResult.treeHash);
});
if (buildmessage.jobHasMessages())
if (buildmessage.jobHasMessages()) {
return;
}
};
var createAndPublishBuiltPackage = function (conn, isopack) {
@@ -505,19 +512,27 @@ exports.updatePackageMetadata = function (options) {
callPackageServerBM(
conn, "changeVersionMetadata", versionIdentifier, dataToUpdate);
});
if (buildmessage.jobHasMessages()) return;
if (buildmessage.jobHasMessages()) {
return;
}
// Upload the new Readme.
buildmessage.enterJob('uploading documentation', function () {
var readmePath = saveReadmeToTmp(readmeInfo);
var uploadInfo =
callPackageServerBM(conn, "createReadme", versionIdentifier);
if (! uploadInfo) return;
if (! uploadFile(uploadInfo.url, readmePath)) return;
if (! uploadInfo) {
return;
}
if (! uploadFile(uploadInfo.url, readmePath)) {
return;
}
callPackageServerBM(
conn, "publishReadme", uploadInfo.uploadToken, { hash: readmeInfo.hash });
});
if (buildmessage.jobHasMessages()) return;
if (buildmessage.jobHasMessages()) {
return;
}
};
@@ -548,13 +563,15 @@ exports.publishPackage = function (options) {
var name = packageSource.name;
var version = packageSource.version;
if (options.new && options.existingVersion)
if (options.new && options.existingVersion) {
throw Error("is it new or does it exist?!?");
}
// Check that the package name is valid.
utils.validatePackageName(name, { useBuildmessage: true });
if (buildmessage.jobHasMessages())
if (buildmessage.jobHasMessages()) {
return;
}
// Check that we have a version.
if (! version) {
@@ -602,8 +619,9 @@ exports.publishPackage = function (options) {
function () {
return packageSource.processReadme();
});
if (buildmessage.jobHasMessages())
if (buildmessage.jobHasMessages()) {
return;
}
if (readmeInfo && (readmeInfo.hash === files.blankHash)) {
buildmessage.error(
"Your documentation file is blank, so users may have trouble figuring " +
@@ -661,12 +679,14 @@ exports.publishPackage = function (options) {
}
}
});
if (buildmessage.jobHasMessages())
if (buildmessage.jobHasMessages()) {
return;
}
var isopack = projectContext.isopackCache.getIsopack(name);
if (! isopack)
if (! isopack) {
throw Error("no isopack " + name);
}
// If we aren't able to include legacy builds in this version, make sure that
// it has a fake dependency on isobuild:isopack-2 so that old versions of
@@ -684,20 +704,23 @@ exports.publishPackage = function (options) {
var sourceFiles = isopack.getSourceFilesUnderSourceRoot(
packageSource.sourceRoot);
if (! sourceFiles)
if (! sourceFiles) {
throw Error("isopack doesn't know what its source files are?");
}
// We need to have built the test package to get all of its sources, even
// though we're not publishing a BUILD for the test package.
if (packageSource.testName) {
var testIsopack = projectContext.isopackCache.getIsopack(
packageSource.testName);
if (! testIsopack)
if (! testIsopack) {
throw Error("no testIsopack " + packageSource.testName);
}
var testSourceFiles = testIsopack.getSourceFilesUnderSourceRoot(
packageSource.sourceRoot);
if (! testSourceFiles)
if (! testSourceFiles) {
throw Error("test isopack doesn't know what its source files are?");
}
sourceFiles = _.union(sourceFiles, testSourceFiles);
}
@@ -706,8 +729,9 @@ exports.publishPackage = function (options) {
sourceBundleResult = bundleSource(
isopack, sourceFiles, packageSource.sourceRoot);
});
if (buildmessage.jobHasMessages())
if (buildmessage.jobHasMessages()) {
return;
}
// Create the package. Check that the metadata exists.
if (options.new) {
@@ -716,8 +740,9 @@ exports.publishPackage = function (options) {
name: packageSource.name
});
});
if (buildmessage.jobHasMessages())
if (buildmessage.jobHasMessages()) {
return;
}
}
if (options.existingVersion) {
@@ -733,8 +758,9 @@ exports.publishPackage = function (options) {
if (! options.doNotPublishBuild) {
createAndPublishBuiltPackage(conn, isopack);
if (buildmessage.jobHasMessages())
if (buildmessage.jobHasMessages()) {
return;
}
}
// XXX check that we're actually providing something new?
@@ -757,8 +783,9 @@ exports.publishPackage = function (options) {
};
uploadInfo = callPackageServerBM(conn, 'createPackageVersion', uploadRec);
});
if (buildmessage.jobHasMessages())
if (buildmessage.jobHasMessages()) {
return;
}
// XXX If package version already exists, print a nice error message
// telling them to try 'meteor publish-for-arch' if they want to
@@ -769,19 +796,22 @@ exports.publishPackage = function (options) {
buildmessage.enterJob("uploading documentation", function () {
uploadFile(uploadInfo.readmeUrl, readmePath);
});
if (buildmessage.jobHasMessages())
if (buildmessage.jobHasMessages()) {
return;
}
buildmessage.enterJob("uploading source", function () {
uploadFile(uploadInfo.uploadUrl, sourceBundleResult.sourceTarball);
});
if (buildmessage.jobHasMessages())
if (buildmessage.jobHasMessages()) {
return;
}
if (! options.doNotPublishBuild) {
var bundleResult = createBuiltPackage(conn, isopack);
if (buildmessage.jobHasMessages())
if (buildmessage.jobHasMessages()) {
return;
}
}
var hashes = {
@@ -793,13 +823,15 @@ exports.publishPackage = function (options) {
callPackageServerBM(
conn, 'publishPackageVersion', uploadInfo.uploadToken, hashes);
});
if (buildmessage.jobHasMessages())
if (buildmessage.jobHasMessages()) {
return;
}
if (! options.doNotPublishBuild) {
publishBuiltPackage(conn, isopack, bundleResult);
if (buildmessage.jobHasMessages())
if (buildmessage.jobHasMessages()) {
return;
}
}
}

View File

@@ -59,8 +59,9 @@ _.extend(exports.PackageMap.prototype, {
},
getInfo: function (packageName) {
var self = this;
if (_.has(self._map, packageName))
if (_.has(self._map, packageName)) {
return self._map[packageName];
}
return null;
},
makeSubsetMap: function (packageNames) {
@@ -68,8 +69,9 @@ _.extend(exports.PackageMap.prototype, {
var subsetVersions = {};
_.each(packageNames, function (packageName) {
var info = self.getInfo(packageName);
if (!info)
if (!info) {
throw Error("not a subset: " + packageName);
}
subsetVersions[packageName] = info.version;
});
return new exports.PackageMap(subsetVersions, {
@@ -112,10 +114,12 @@ _.extend(exports.PackageMap.prototype, {
var self = this;
return _.all(mapJSON, function (jsonInfo, packageName) {
var thisInfo = self.getInfo(packageName);
if (! thisInfo)
if (! thisInfo) {
return false;
if (jsonInfo.kind !== thisInfo.kind)
}
if (jsonInfo.kind !== thisInfo.kind) {
return false;
}
if (thisInfo.kind === 'local') {
return thisInfo.packageSource.sourceRoot === jsonInfo.sourceRoot;
} else {
@@ -134,8 +138,9 @@ _.extend(exports.PackageMap.prototype, {
exports.PackageMap.fromReleaseVersion = function (releaseVersion) {
var toolPackageVersion = releaseVersion.tool &&
utils.parsePackageAndVersion(releaseVersion.tool);
if (!toolPackageVersion)
if (!toolPackageVersion) {
throw new Error("bad tool in release: " + releaseVersion.tool);
}
var toolPackage = toolPackageVersion.package;
var toolVersion = toolPackageVersion.version;
@@ -177,8 +182,9 @@ _.extend(exports.PackageMapDelta.prototype, {
var self = this;
// Store nothing if nothing has changed.
if (newInfo.version === oldVersion)
if (newInfo.version === oldVersion) {
return;
}
var backwardsIncompatible =
oldVersion !== null &&
@@ -224,8 +230,9 @@ _.extend(exports.PackageMapDelta.prototype, {
}, options);
// Print nothing at all if nothing changed.
if (! self.hasChanges())
if (! self.hasChanges()) {
return;
}
var displayItems = [];
var anyBackwardsIncompatible = false;

View File

@@ -41,15 +41,17 @@ _.extend(Release.prototype, {
getReleaseTrack: function () {
var self = this;
if (! self.isProperRelease())
if (! self.isProperRelease()) {
throw new Error("not a proper release?");
}
return self.name.split('@')[0];
},
getReleaseVersion: function () {
var self = this;
if (! self.isProperRelease())
if (! self.isProperRelease()) {
throw new Error("not a proper release?");
}
return self.name.split('@')[1];
},
@@ -58,8 +60,9 @@ _.extend(Release.prototype, {
getToolsPackage: function () {
var self = this;
if (! self.isProperRelease())
if (! self.isProperRelease()) {
throw new Error("not a proper release?");
}
// XXX validate
return self._manifest.tool.split('@')[0];
},
@@ -69,8 +72,9 @@ _.extend(Release.prototype, {
getToolsVersion: function () {
var self = this;
if (! self.isProperRelease())
if (! self.isProperRelease()) {
throw new Error("not a proper release?");
}
// XXX validate
return self._manifest.tool.split('@')[1];
},
@@ -80,8 +84,9 @@ _.extend(Release.prototype, {
getToolsPackageAtVersion: function () {
var self = this;
if (! self.isProperRelease())
if (! self.isProperRelease()) {
throw new Error("not a proper release?");
}
return self._manifest.tool;
},
@@ -104,23 +109,26 @@ _.extend(Release.prototype, {
getUpgraders: function () {
var self = this;
if (! self.isProperRelease())
if (! self.isProperRelease()) {
throw new Error("not a proper release?");
}
return self._manifest.upgraders || [];
},
getPackages: function () {
var self = this;
if (! self.isProperRelease())
if (! self.isProperRelease()) {
throw new Error("not a proper release?");
}
return self._manifest.packages;
},
getCatalogReleaseData: function () {
var self = this;
if (! self.isProperRelease())
if (! self.isProperRelease()) {
throw new Error("not a proper release?");
}
return self._manifest;
},
@@ -166,11 +174,13 @@ release.explicit = null;
// in the current project. (taking into account release.forced and whether we're
// currently running from a checkout).
release.usingRightReleaseForApp = function (projectContext) {
if (release.current === null)
if (release.current === null) {
throw new Error("no release?");
}
if (! files.usesWarehouse() || release.forced)
if (! files.usesWarehouse() || release.forced) {
return true;
}
return release.current.name === projectContext.releaseFile.fullReleaseName;
};
@@ -179,11 +189,13 @@ release.usingRightReleaseForApp = function (projectContext) {
// for use. May not be called when running from a checkout.
// 'track' is optional (it defaults to the default track).
release.latestKnown = function (track) {
if (! files.usesWarehouse())
if (! files.usesWarehouse()) {
throw new Error("called from checkout?");
}
// For self-test only.
if (process.env.METEOR_TEST_LATEST_RELEASE)
if (process.env.METEOR_TEST_LATEST_RELEASE) {
return process.env.METEOR_TEST_LATEST_RELEASE;
}
var defaultRelease = catalog.official.getDefaultReleaseVersion(track);
@@ -253,8 +265,9 @@ release.load = function (name, options) {
// line (by the user or by the update springboard).
// - explicit: true if the release was specifically requested by the user.
release.setCurrent = function (releaseObject, forced, explicit) {
if (release.current)
if (release.current) {
throw new Error("release set twice?");
}
release.current = releaseObject;
release.forced = !! forced;

View File

@@ -23,8 +23,9 @@ exports.Tropohouse = function (root, options) {
// we are running form a checkout, probably at $CHECKOUT_DIR/.meteor.
var defaultWarehouseDir = function () {
// a hook for tests, or i guess for users.
if (process.env.METEOR_WAREHOUSE_DIR)
if (process.env.METEOR_WAREHOUSE_DIR) {
return process.env.METEOR_WAREHOUSE_DIR;
}
var warehouseBase = files.inCheckout()
? files.getCurrentToolsDir() : files.getHomeDir();
@@ -178,8 +179,9 @@ _.extend(exports.Tropohouse.prototype, {
escapedPackages = files.readdir(packageRootDir);
} catch (e) {
// No packages at all? We're done.
if (e.code === 'ENOENT')
if (e.code === 'ENOENT') {
return;
}
throw e;
}
@@ -233,14 +235,16 @@ _.extend(exports.Tropohouse.prototype, {
versions = files.readdir(packageDir);
} catch (e) {
// Somebody put a file in here or something? Whatever, ignore.
if (e.code === 'ENOENT' || e.code === 'ENOTDIR')
if (e.code === 'ENOENT' || e.code === 'ENOTDIR') {
return;
}
throw e;
}
_.each(versions, function (version) {
// Is this a pre-0.9.0 "warehouse" version with a hash name?
if (/^[a-f0-9]{3,}$/.test(version))
if (/^[a-f0-9]{3,}$/.test(version)) {
return;
}
// Skip the currently-latest tool (ie, don't break top-level meteor
// symlink). This includes both the symlink with its name and the thing
@@ -271,10 +275,12 @@ _.extend(exports.Tropohouse.prototype, {
// archinfo.host().
installed: function (options) {
var self = this;
if (!options.packageName)
if (!options.packageName) {
throw Error("Missing required argument: packageName");
if (!options.version)
}
if (!options.version) {
throw Error("Missing required argument: version");
}
var architectures = options.architectures || [archinfo.host()];
var downloaded = self._alreadyDownloaded({
@@ -317,10 +323,12 @@ _.extend(exports.Tropohouse.prototype, {
var self = this;
var packageName = options.packageName;
var version = options.version;
if (!options.packageName)
if (!options.packageName) {
throw Error("Missing required argument: packageName");
if (!options.version)
}
if (!options.version) {
throw Error("Missing required argument: version");
}
// Figure out what arches (if any) we have loaded for this package version
@@ -387,12 +395,15 @@ _.extend(exports.Tropohouse.prototype, {
var self = this;
buildmessage.assertInJob();
if (!options.packageName)
if (!options.packageName) {
throw Error("Missing required argument: packageName");
if (!options.version)
}
if (!options.version) {
throw Error("Missing required argument: version");
if (!options.architectures)
}
if (!options.architectures) {
throw Error("Missing required argument: architectures");
}
var packageName = options.packageName;
var version = options.version;
@@ -460,8 +471,9 @@ _.extend(exports.Tropohouse.prototype, {
// (ie, this is a warehouse package not a tropohouse package). But
// the versions should not overlap: warehouse versions are truncated
// SHAs whereas tropohouse versions should be semver-like.
if (e.code !== 'ENOENT')
if (e.code !== 'ENOENT') {
throw e;
}
}
// If there's already a package in the tropohouse, start with it.
@@ -483,16 +495,18 @@ _.extend(exports.Tropohouse.prototype, {
var buildTempDir = self._downloadBuildToTempDir(
{ packageName: packageName, version: version }, build);
} catch (e) {
if (!(e instanceof files.OfflineError))
if (!(e instanceof files.OfflineError)) {
throw e;
}
buildmessage.error(e.error.message);
}
buildInputDirs.push(buildTempDir);
buildTempDirs.push(buildTempDir);
});
});
if (buildmessage.jobHasMessages())
if (buildmessage.jobHasMessages()) {
return;
}
// We need to turn our builds into a single isopack.
var isopack = new Isopack();
@@ -538,8 +552,9 @@ _.extend(exports.Tropohouse.prototype, {
var downloader;
var downloaders = [];
packageMap.eachPackage(function (packageName, info) {
if (info.kind !== 'versioned')
if (info.kind !== 'versioned') {
return;
}
buildmessage.enterJob(
"checking for " + packageName + "@" + info.version,
function () {
@@ -552,19 +567,22 @@ _.extend(exports.Tropohouse.prototype, {
downloaders = null;
return;
}
if (downloader && downloaders)
if (downloader && downloaders) {
downloaders.push(downloader);
}
}
);
});
// Did anything fail? Don't download anything.
if (! downloaders)
if (! downloaders) {
return;
}
// Nothing to download? Great.
if (! downloaders.length)
if (! downloaders.length) {
return;
}
// Just one package to download? Use a good message.
if (downloaders.length === 1) {

View File

@@ -25,8 +25,9 @@ exports.tryToDownloadUpdate = function (options) {
// Don't run more than one check simultaneously. It should be
// harmless but having two downloads happening simultaneously (and
// two sets of messages being printed) would be confusing.
if (checkInProgress)
if (checkInProgress) {
return;
}
checkInProgress = true;
checkForUpdate(!! options.showBanner, !! options.printErrors);
checkInProgress = false;
@@ -56,8 +57,9 @@ var checkForUpdate = function (showBanner, printErrors) {
}
}
if (!release.current.isProperRelease())
if (!release.current.isProperRelease()) {
return;
}
updateMeteorToolSymlink(printErrors);
@@ -105,8 +107,9 @@ var maybeShowBanners = function () {
// We now consider printing some simpler banners, if this isn't the latest
// release. But if the user specified a release manually with --release, we
// don't bother: we only want to tell users about ways to update *their app*.
if (release.forced)
if (release.forced) {
return;
}
const catalogUtils = require('./catalog/catalog-utils.js');
@@ -155,15 +158,18 @@ var updateMeteorToolSymlink = function (printErrors) {
// symlink to go to the default track.)
var latestReleaseVersion = catalog.official.getDefaultReleaseVersion();
// Maybe you're on some random track with nothing recommended. That's OK.
if (!latestReleaseVersion)
if (!latestReleaseVersion) {
return;
}
var latestRelease = catalog.official.getReleaseVersion(
latestReleaseVersion.track, latestReleaseVersion.version);
if (!latestRelease)
if (!latestRelease) {
throw Error("latest release doesn't exist?");
if (!latestRelease.tool)
}
if (!latestRelease.tool) {
throw Error("latest release doesn't have a tool?");
}
var latestReleaseToolParts = latestRelease.tool.split('@');
var latestReleaseToolPackage = latestReleaseToolParts[0];
@@ -202,8 +208,9 @@ var updateMeteorToolSymlink = function (printErrors) {
// XXX maybe we shouldn't throw from this background thing
// counter: this is super weird and should never ever happen.
if (!toolRecord)
if (!toolRecord) {
throw Error("latest release has no tool?");
}
tropohouse.default.linkToLatestMeteor(files.pathJoin(
relativeToolPath, toolRecord.path, 'meteor'));

View File

@@ -58,14 +58,16 @@ _.extend(warehouse, {
// $HOME/.meteor.
getWarehouseDir: function () {
// a hook for tests, or i guess for users.
if (process.env.METEOR_WAREHOUSE_DIR)
if (process.env.METEOR_WAREHOUSE_DIR) {
return files.convertToStandardPath(process.env.METEOR_WAREHOUSE_DIR);
}
// This function should never be called unless we have a warehouse
// (an installed version, or with process.env.METEOR_WAREHOUSE_DIR
// set)
if (!files.usesWarehouse())
if (!files.usesWarehouse()) {
throw new Error("There's no warehouse in a git checkout");
}
return files.pathJoin(files.getHomeDir(), '.meteor');
},
@@ -97,8 +99,9 @@ _.extend(warehouse, {
// - warehouse.NoSuchReleaseError if we talked to the server and it
// told us that no release named 'release' exists.
ensureReleaseExistsAndReturnManifest: function (release, quiet) {
if (!files.usesWarehouse())
if (!files.usesWarehouse()) {
throw new Error("Not in a warehouse but requesting a manifest!");
}
return warehouse._populateWarehouseForRelease(release, !quiet);
},
@@ -161,8 +164,9 @@ _.extend(warehouse, {
newPieces.packages[name] = {version: version, needsDownload: false};
}
});
if (newPieces.tools || !_.isEmpty(newPieces.packages))
if (newPieces.tools || !_.isEmpty(newPieces.packages)) {
return newPieces;
}
return null;
},
@@ -208,10 +212,12 @@ _.extend(warehouse, {
// For automated self-test. If METEOR_TEST_FAIL_RELEASE_DOWNLOAD
// is 'offline' or 'not-found', make release downloads fail.
if (process.env.METEOR_TEST_FAIL_RELEASE_DOWNLOAD === "offline")
if (process.env.METEOR_TEST_FAIL_RELEASE_DOWNLOAD === "offline") {
throw new files.OfflineError(new Error("scripted failure for tests"));
if (process.env.METEOR_TEST_FAIL_RELEASE_DOWNLOAD === "not-found")
}
if (process.env.METEOR_TEST_FAIL_RELEASE_DOWNLOAD === "not-found") {
throw new warehouse.NoSuchReleaseError;
}
try {
var result = httpHelpers.request(
@@ -220,10 +226,11 @@ _.extend(warehouse, {
throw new files.OfflineError(e);
}
if (result.response.statusCode !== 200)
if (result.response.statusCode !== 200) {
// We actually got some response, so we're probably online and we
// just can't find the release.
throw new warehouse.NoSuchReleaseError;
}
releaseManifestText = result.body;
}
@@ -232,8 +239,9 @@ _.extend(warehouse, {
var newPieces = warehouse._calculateNewPiecesForRelease(releaseManifest);
if (releaseAlreadyExists && !newPieces)
if (releaseAlreadyExists && !newPieces) {
return releaseManifest;
}
if (newPieces && showInstalling) {
console.log("Installing Meteor %s:", releaseVersion);
@@ -256,8 +264,9 @@ _.extend(warehouse, {
warehouse._platform(),
warehouse.getWarehouseDir());
} catch (e) {
if (showInstalling)
if (showInstalling) {
console.error("Failed to load tools for release " + releaseVersion);
}
throw e;
}
@@ -272,8 +281,9 @@ _.extend(warehouse, {
var packagesToDownload = {};
_.each(newPieces && newPieces.packages, function (packageInfo, name) {
if (packageInfo.needsDownload)
if (packageInfo.needsDownload) {
packagesToDownload[name] = packageInfo.version;
}
});
if (!_.isEmpty(packagesToDownload)) {
try {
@@ -281,9 +291,10 @@ _.extend(warehouse, {
warehouse._platform(),
warehouse.getWarehouseDir());
} catch (e) {
if (showInstalling)
if (showInstalling) {
console.error("Failed to load packages for release " +
releaseVersion);
}
throw e;
}
}
@@ -328,8 +339,9 @@ _.extend(warehouse, {
} catch (e) {
// If two processes populate the warehouse in parallel, the other
// process may have deleted the fresh file. That's OK!
if (e.code === "ENOENT")
if (e.code === "ENOENT") {
return;
}
throw e;
}
};
@@ -364,8 +376,9 @@ _.extend(warehouse, {
});
files.extractTarGz(
toolsTarball, files.pathJoin(warehouseDirectory, 'tools', toolsVersion));
if (!dontWriteFreshFile)
if (!dontWriteFreshFile) {
files.writeFile(warehouse.getToolsFreshFile(toolsVersion), '');
}
},
// this function is also used by bless-release.js
@@ -383,20 +396,22 @@ _.extend(warehouse, {
var tarball = httpHelpers.getUrl({url: packageUrl, encoding: null});
files.extractTarGz(tarball, packageDir);
if (!dontWriteFreshFile)
if (!dontWriteFreshFile) {
files.writeFile(warehouse.getPackageFreshFile(name, version), '');
}
});
},
_platform: function () {
// Normalize from Node "os.arch()" to "uname -m".
var arch = os.arch();
if (arch === "ia32")
if (arch === "ia32") {
arch = "i686";
else if (arch === "x64")
} else if (arch === "x64") {
arch = "x86_64";
else
} else {
throw new Error("Unsupported architecture " + arch);
}
return os.type() + "_" + arch;
}
});

View File

@@ -131,8 +131,9 @@ class Runner {
buildmessage.enterJob({ title: "starting your app" }, function () {
self.appRunner.start();
});
if (! self.quiet && ! self.stopped)
if (! self.quiet && ! self.stopped) {
runLog.log("Started your app.", { arrow: true });
}
}
if (! self.stopped && ! self.quiet) {
@@ -149,8 +150,9 @@ class Runner {
buildmessage.enterJob({ title: "starting Selenium" }, function () {
self.selenium.start();
});
if (! self.quiet && ! self.stopped)
if (! self.quiet && ! self.stopped) {
runLog.log("Started Selenium.", { arrow: true });
}
}
// XXX It'd be nice to (cosmetically) handle failure better. Right
@@ -180,8 +182,9 @@ class Runner {
// Idempotent
stop() {
const self = this;
if (self.stopped)
if (self.stopped) {
return;
}
self.stopped = true;
self.proxy.stop();
@@ -206,10 +209,12 @@ class Runner {
} else {
self.appPort = require('../utils/utils.js').randomPort();
}
if (self.proxy)
if (self.proxy) {
self.proxy.proxyToPort = self.appPort;
if (self.appRunner)
}
if (self.appRunner) {
self.appRunner.port = self.appPort;
}
}
}
@@ -321,10 +326,11 @@ exports.run = function (options) {
}
if (result.outcome === "wrong-release") {
if (once)
if (once) {
// We lost a race where the user ran 'meteor update' and 'meteor
// run --once' simultaneously.
throw new Error("wrong release?");
}
// If the user did not specify a --release on the command line,
// and simultaneously runs `meteor update` during this run, just

View File

@@ -78,8 +78,9 @@ _.extend(AppProcess.prototype, {
start: function () {
var self = this;
if (self.proc)
if (self.proc) {
throw new Error("already started?");
}
// Start the app!
self.proc = self._spawn();
@@ -146,8 +147,9 @@ _.extend(AppProcess.prototype, {
_maybeCallOnExit: function (code, signal) {
var self = this;
if (self.madeExitCallback)
if (self.madeExitCallback) {
return;
}
self.madeExitCallback = true;
self.onExit && self.onExit(code, signal);
},
@@ -386,8 +388,9 @@ _.extend(AppRunner.prototype, {
start: function () {
var self = this;
if (self.fiber)
if (self.fiber) {
throw new Error("already started?");
}
self.startFuture = new Future;
// XXX I think it's correct to not try to use bindEnvironment here:
@@ -407,11 +410,14 @@ _.extend(AppRunner.prototype, {
stop: function () {
var self = this;
if (! self.fiber)
return; // nothing to do
if (! self.fiber) {
// nothing to do
return;
}
if (self.exitFuture)
if (self.exitFuture) {
throw new Error("another fiber already stopping?");
}
// The existence of this future makes the fiber break out of its loop.
self.exitFuture = new Future;
@@ -592,8 +598,9 @@ _.extend(AppRunner.prototype, {
var bundleResult;
var bundleResultOrRunResult = bundleApp();
if (bundleResultOrRunResult.runResult)
if (bundleResultOrRunResult.runResult) {
return bundleResultOrRunResult.runResult;
}
bundleResult = bundleResultOrRunResult.bundleResult;
firstRun = false;
@@ -605,8 +612,9 @@ _.extend(AppRunner.prototype, {
title: "preparing to run",
rootPath: process.cwd()
}, function () {
if (self.settingsFile)
if (self.settingsFile) {
settings = files.getSettings(self.settingsFile, settingsWatchSet);
}
});
if (settingsMessages.hasMessages()) {
return {
@@ -667,10 +675,12 @@ _.extend(AppRunner.prototype, {
// Atomically (1) see if we've been stop()'d, (2) if not, create a
// future that can be used to stop() us once we start running.
if (self.exitFuture)
if (self.exitFuture) {
return { outcome: 'stopped' };
if (self.runFuture)
}
if (self.runFuture) {
throw new Error("already have future?");
}
var runFuture = self.runFuture = new Future;
// Run the program
@@ -696,8 +706,9 @@ _.extend(AppRunner.prototype, {
onListen: function () {
self.proxy.setMode("proxy");
options.onListen && options.onListen();
if (self.startFuture)
if (self.startFuture) {
self.startFuture['return']();
}
},
nodeOptions: getNodeOptionsFromEnvironment(),
nodePath: _.map(bundleResult.nodePath, files.convertToOSPath),
@@ -777,14 +788,16 @@ _.extend(AppRunner.prototype, {
try {
while (ret.outcome === 'changed-refreshable') {
if (! canRefreshClient)
if (! canRefreshClient) {
throw Error("Can't refresh client?");
}
// We stay in this loop as long as only refreshable assets have changed.
// When ret.refreshable becomes false, we restart the server.
bundleResultOrRunResult = bundleApp();
if (bundleResultOrRunResult.runResult)
if (bundleResultOrRunResult.runResult) {
return bundleResultOrRunResult.runResult;
}
bundleResult = bundleResultOrRunResult.bundleResult;
maybePrintLintWarnings(bundleResult);
@@ -824,8 +837,9 @@ _.extend(AppRunner.prototype, {
_runFutureReturn: function (value) {
var self = this;
if (!self.runFuture)
if (!self.runFuture) {
return;
}
var runFuture = self.runFuture;
self.runFuture = null;
runFuture['return'](value);
@@ -833,8 +847,9 @@ _.extend(AppRunner.prototype, {
_watchFutureReturn: function () {
var self = this;
if (!self.watchFuture)
if (!self.watchFuture) {
return;
}
var watchFuture = self.watchFuture;
self.watchFuture = null;
watchFuture.return();
@@ -857,8 +872,9 @@ _.extend(AppRunner.prototype, {
var runResult = self._runOnce({
onListen: function () {
if (! self.noRestartBanner && ! firstRun)
if (! self.noRestartBanner && ! firstRun) {
runLog.logRestart();
}
},
beforeRun: resetCrashCount,
firstRun: firstRun
@@ -866,12 +882,14 @@ _.extend(AppRunner.prototype, {
firstRun = false;
clearTimeout(crashTimer);
if (runResult.outcome !== "terminated")
if (runResult.outcome !== "terminated") {
crashCount = 0;
}
var wantExit = self.onRunEnd ? !self.onRunEnd(runResult) : false;
if (wantExit || self.exitFuture || runResult.outcome === "stopped")
if (wantExit || self.exitFuture || runResult.outcome === "stopped") {
break;
}
if (runResult.outcome === "wrong-release" ||
runResult.outcome === "conflicting-versions") {
@@ -893,10 +911,9 @@ _.extend(AppRunner.prototype, {
}
}
else if (runResult.outcome === "changed")
else if (runResult.outcome === "changed") {
continue;
else if (runResult.outcome === "terminated") {
} else if (runResult.outcome === "terminated") {
if (runResult.signal) {
runLog.log('Exited from signal: ' + runResult.signal, { arrow: true });
} else if (runResult.code !== undefined) {
@@ -906,8 +923,9 @@ _.extend(AppRunner.prototype, {
}
crashCount ++;
if (crashCount < 3)
if (crashCount < 3) {
continue;
}
if (self.watchForChanges) {
runLog.log("Your application is crashing. " +
@@ -924,8 +942,9 @@ _.extend(AppRunner.prototype, {
if (self.watchForChanges) {
self.watchFuture = new Future;
if (!runResult.watchSet)
if (!runResult.watchSet) {
throw Error("watching for changes with no watchSet?");
}
// XXX reference to watcher is lost later?
var watcher = new watch.Watcher({
watchSet: runResult.watchSet,
@@ -938,8 +957,9 @@ _.extend(AppRunner.prototype, {
// on it.
self.watchFuture && self.watchFuture.wait();
// While we were waiting, did somebody stop() us?
if (self.exitFuture)
if (self.exitFuture) {
break;
}
runLog.log("Modified -- restarting.", { arrow: true });
Console.enableProgressDisplay(true);
continue;
@@ -949,10 +969,12 @@ _.extend(AppRunner.prototype, {
}
// Giving up for good.
if (self.exitFuture)
if (self.exitFuture) {
self.exitFuture['return']();
if (self.startFuture)
}
if (self.startFuture) {
self.startFuture['return']();
}
self.fiber = null;
}

View File

@@ -92,12 +92,12 @@ _.extend(RunLog.prototype, {
self._record(obj);
self._clearSpecial();
if (self.rawLogs)
if (self.rawLogs) {
Console[isStderr ? "rawError" : "rawInfo"](line + "\n");
else
} else {
// XXX deal with test server logging differently?!
Console.rawInfo(Log.format(obj, { color: true }) + "\n");
// XXX deal with test server logging differently?!
}
},
// Log the message.
@@ -155,8 +155,9 @@ _.extend(RunLog.prototype, {
}
var message = "=> Meteor server restarted";
if (self.consecutiveRestartMessages > 1)
if (self.consecutiveRestartMessages > 1) {
message += " (x" + self.consecutiveRestartMessages + ")";
}
// no newline, so that we can overwrite it if we get another
// restart message right after this one
process.stdout.write(message);
@@ -182,8 +183,9 @@ _.extend(RunLog.prototype, {
}
var message = "=> Client modified -- refreshing";
if (self.consecutiveClientRestartMessages > 1)
if (self.consecutiveClientRestartMessages > 1) {
message += " (x" + self.consecutiveClientRestartMessages + ")";
}
// no newline, so that we can overwrite it if we get another
// restart message right after this one
process.stdout.write(message);

View File

@@ -21,9 +21,15 @@ var runMongoShell = function (url) {
var ssl = require('querystring').parse(mongoUrl.query).ssl === "true";
var args = [];
if (ssl) args.push('--ssl');
if (auth) args.push('-u', auth[0]);
if (auth) args.push('-p', auth[1]);
if (ssl) {
args.push('--ssl');
}
if (auth) {
args.push('-u', auth[0]);
}
if (auth) {
args.push('-p', auth[1]);
}
args.push(mongoUrl.hostname + ':' + mongoUrl.port + mongoUrl.pathname);
child_process.spawn(files.convertToOSPath(mongoPath),
@@ -288,10 +294,11 @@ var findMongoAndKillItDead = function (port, dbPath) {
// dead.
for (var attempts = 1; attempts <= 40; attempts ++) {
var signal = 0;
if (attempts === 1)
if (attempts === 1) {
signal = 'SIGINT';
else if (attempts === 20 || attempts === 30)
} else if (attempts === 20 || attempts === 30) {
signal = 'SIGKILL';
}
try {
process.kill(pid, signal);
@@ -347,8 +354,9 @@ var launchMongo = function (options) {
// start our stub (fake-mongod) which can then be remote-controlled
// by the test.
if (process.env.METEOR_TEST_FAKE_MONGOD_CONTROL_PORT) {
if (options.multiple)
if (options.multiple) {
throw Error("Can't specify multiple with fake mongod");
}
var fakeMongodCommand =
process.platform === "win32" ? "fake-mongod.bat" : "fake-mongod";
@@ -378,8 +386,9 @@ var launchMongo = function (options) {
var handle = {
stop: function () {
if (stopped)
if (stopped) {
return;
}
stopped = true;
_.each(subHandles, function (handle) {
handle.stop();
@@ -412,8 +421,9 @@ var launchMongo = function (options) {
matchingPortFileExists = +(files.readFile(portFile)) === port;
portFileExists = true;
} catch (e) {
if (!e || e.code !== 'ENOENT')
if (!e || e.code !== 'ENOENT') {
throw e;
}
}
// If this is the first time we're using this DB, or we changed port since
@@ -428,14 +438,16 @@ var launchMongo = function (options) {
if (!matchingPortFileExists) {
// Delete the port file if it exists, so we don't mistakenly believe
// that the DB is still configured.
if (portFileExists)
if (portFileExists) {
files.unlink(portFile);
}
try {
var dbFiles = files.readdir(dbPath);
} catch (e) {
if (!e || e.code !== 'ENOENT')
if (!e || e.code !== 'ENOENT') {
throw e;
}
}
_.each(dbFiles, function (dbFile) {
if (/^local\./.test(dbFile)) {
@@ -448,8 +460,9 @@ var launchMongo = function (options) {
// Let's not actually start a process if we yielded (eg during
// findMongoAndKillItDead) and we decided to stop in the middle (eg, because
// we're in multiple mode and another process exited).
if (stopped)
if (stopped) {
return;
}
proc = spawnMongod(mongod_path, port, dbPath, replSetName);
@@ -484,8 +497,9 @@ var launchMongo = function (options) {
var readyToTalkFuture = new Future;
var maybeReadyToTalk = function () {
if (readyToTalkFuture.isResolved())
if (readyToTalkFuture.isResolved()) {
return;
}
if (listening && (noOplog || replSetReadyToBeInitiated || replSetReady)) {
proc.stdout.removeListener('data', stdoutOnData);
readyToTalkFuture.return();
@@ -544,8 +558,9 @@ var launchMongo = function (options) {
new mongoNpmModule.Server('127.0.0.1', options.port, {poolSize: 1}),
{safe: true});
yieldingMethod(db, 'open');
if (stopped)
if (stopped) {
return;
}
var configuration = {
_id: replSetName,
members: [{_id: 0, host: '127.0.0.1:' + options.port, priority: 100}]
@@ -564,8 +579,9 @@ var launchMongo = function (options) {
var initiateResult = yieldingMethod(
db.admin(), 'command', {replSetInitiate: configuration});
if (stopped)
if (stopped) {
return;
}
// why this isn't in the error is unclear.
if (initiateResult && initiateResult.documents
&& initiateResult.documents[0]
@@ -580,8 +596,9 @@ var launchMongo = function (options) {
while (!stopped) {
var status = yieldingMethod(db.admin(), 'command',
{replSetGetStatus: 1});
if (!(status && status.documents && status.documents[0]))
if (!(status && status.documents && status.documents[0])) {
throw status;
}
status = status.documents[0];
if (!status.ok) {
if (status.startupStatus === 6) { // "SOON"
@@ -631,8 +648,9 @@ var launchMongo = function (options) {
} catch (e) {
// If the process has exited, we're doing another form of error
// handling. No need to throw random low-level errors farther.
if (!stopped || (e instanceof StoppedDuringLaunch))
if (!stopped || (e instanceof StoppedDuringLaunch)) {
throw e;
}
}
};
@@ -642,8 +660,9 @@ var launchMongo = function (options) {
_.each(_.range(3), function (i) {
// Did we get stopped (eg, by one of the processes exiting) by now? Then
// don't start anything new.
if (stopped)
if (stopped) {
return;
}
var dbPath = files.pathJoin(options.appDir, '.meteor', 'local', 'dbs', ''+i);
launchOneMongoAndWaitForReadyForInitiate(dbPath, options.port + i);
});
@@ -663,12 +682,14 @@ var launchMongo = function (options) {
}
}
} catch (e) {
if (!(e instanceof StoppedDuringLaunch))
if (!(e instanceof StoppedDuringLaunch)) {
throw e;
}
}
if (stopped)
if (stopped) {
return null;
}
return handle;
};
@@ -708,18 +729,21 @@ _.extend(MRp, {
start: function () {
var self = this;
if (self.handle)
if (self.handle) {
throw new Error("already running?");
}
self._startOrRestart();
// Did we properly start up? Great!
if (self.handle)
if (self.handle) {
return;
}
// Are we shutting down? OK.
if (self.shuttingDown)
if (self.shuttingDown) {
return;
}
// Otherwise, wait for a successful _startOrRestart, or a failure.
if (!self.startupFuture) {
@@ -742,8 +766,9 @@ _.extend(MRp, {
_startOrRestart: function () {
var self = this;
if (self.handle)
if (self.handle) {
throw new Error("already running?");
}
var allowKilling = self.multiple || self.firstStart;
self.firstStart = false;
@@ -778,8 +803,9 @@ _.extend(MRp, {
// If Mongo exited because (or rather, anytime after) we told it
// to exit, great, nothing to do. Otherwise, we'll print an error
// and try to restart.
if (self.shuttingDown)
if (self.shuttingDown) {
return;
}
// Only print an error if we tried to kill Mongo and something went
// wrong. If we didn't try to kill Mongo, we'll do that on the next
@@ -805,8 +831,9 @@ _.extend(MRp, {
// timer instead of looking at the current date, we avoid getting
// confused by time changes.)
self.errorCount ++;
if (self.errorTimer)
if (self.errorTimer) {
clearTimeout(self.errorTimer);
}
self.errorTimer = setTimeout(function () {
self.errorTimer = null;
self.errorCount = 0;
@@ -861,8 +888,9 @@ _.extend(MRp, {
stop: function () {
var self = this;
if (self.shuttingDown)
if (self.shuttingDown) {
return;
}
self.shuttingDown = true;

View File

@@ -28,8 +28,9 @@ _.extend(Proxy.prototype, {
start: function () {
var self = this;
if (self.server)
if (self.server) {
throw new Error("already running?");
}
self.started = false;
@@ -127,8 +128,9 @@ _.extend(Proxy.prototype, {
stop: function () {
var self = this;
if (! self.server)
if (! self.server) {
return;
}
if (! self.started) {
// This probably means that we failed to listen. However, there could be a
@@ -167,8 +169,9 @@ _.extend(Proxy.prototype, {
var self = this;
while (self.httpQueue.length) {
if (self.mode !== "errorpage" && self.mode !== "proxy")
if (self.mode !== "errorpage" && self.mode !== "proxy") {
break;
}
var c = self.httpQueue.shift();
if (self.mode === "errorpage") {
@@ -181,8 +184,9 @@ _.extend(Proxy.prototype, {
}
while (self.websocketQueue.length) {
if (self.mode !== "proxy")
if (self.mode !== "proxy") {
break;
}
var c = self.websocketQueue.shift();
self.proxy.ws(c.req, c.socket, c.head, {

View File

@@ -51,8 +51,9 @@ _.extend(Selenium.prototype, {
start: function () {
var self = this;
if (self.server)
if (self.server) {
throw new Error("already running?");
}
self.xunitLines = [];
@@ -94,8 +95,9 @@ _.extend(Selenium.prototype, {
stop: function () {
var self = this;
if (! self.driver)
if (! self.driver) {
return;
}
_promiseToFuture(self.driver.close()).wait();
_promiseToFuture(self.driver.quit()).wait();
@@ -169,7 +171,9 @@ _.extend(Selenium.prototype, {
return;
}
msg = match[3];
if (msg === DUMMY_FLUSH) return;
if (msg === DUMMY_FLUSH) {
return;
}
if (msg.indexOf(MAGIC_PREFIX) === 0) {
msg = msg.substring(MAGIC_PREFIX.length);
var colonIndex = msg.indexOf(': ');

View File

@@ -15,8 +15,9 @@ _.extend(Updater.prototype, {
start: function () {
var self = this;
if (self.timer)
if (self.timer) {
throw new Error("already running?");
}
// Check every 3 hours. (Should not share buildmessage state with
// the main fiber.)
@@ -50,8 +51,9 @@ _.extend(Updater.prototype, {
stop: function () {
var self = this;
if (self.timer)
if (self.timer) {
return;
}
clearInterval(self.timer);
self.timer = null;
}

View File

@@ -54,7 +54,9 @@ var checkCordovaPlugins = selftest.markStack(function(sand, plugins) {
var i = 0;
_.each(cordovaPlugins, function(line) {
if (!line || line === '') return;
if (!line || line === '') {
return;
}
// XXX should check for the version as well?
selftest.expectEqual(line.split(' ')[0], plugins[i]);
i++;
@@ -67,7 +69,9 @@ var checkCordovaPluginExists = selftest.markStack(function(sand, plugin) {
var cordovaPlugins = getCordovaPluginsList(sand);
var found = false;
cordovaPlugins = cordovaPlugins.map(function (line) {
if (line && line !== '') return line.split(' ')[0];
if (line && line !== '') {
return line.split(' ')[0];
}
});
selftest.expectTrue(_.contains(cordovaPlugins, plugin));
});
@@ -88,7 +92,9 @@ var checkUserPlugins = function(sand, plugins) {
var lines = sand.read(".meteor/cordova-plugins").split("\n");
var depend = {};
_.each(lines, function(line) {
if (!line) return;
if (!line) {
return;
}
// plugins are stored of the form foo@1.0.0, so this should give us an
// array [foo, 1.0.0].
var split = line.split('@');

View File

@@ -8,8 +8,9 @@ var release = require('../packaging/release.js');
// old tests don't get to test --release, and always run this release
var maybeFixRelease = function (env) {
if (release.current && release.current.isProperRelease())
if (release.current && release.current.isProperRelease()) {
env.METEOR_SPRINGBOARD_RELEASE = release.current.name;
}
return env;
};

View File

@@ -45,7 +45,9 @@ var checkPackages = selftest.markStack(function(sand, packages) {
var lines = sand.read(".meteor/packages").split("\n");
var i = 0;
_.each(lines, function(line) {
if (!line) return;
if (!line) {
return;
}
// If the specified package contains an @ sign, then it has a version
// number, so we should match everything.
if (packages[i].split('@').length > 1) {
@@ -80,7 +82,9 @@ var checkVersions = selftest.markStack(function(sand, packages) {
var lines = sand.read(".meteor/versions").split("\n");
var depend = {};
_.each(lines, function(line) {
if (!line) return;
if (!line) {
return;
}
// Packages are stored of the form foo@1.0.0, so this should give us an
// array [foo, 1.0.0].
var split = line.split('@');
@@ -141,13 +145,17 @@ _.extend(DataStub.prototype, {
getSortedVersions: function (p) {
var self = this;
var rec = self.packages[p];
if (!rec) return null;
if (!rec) {
return null;
}
return rec.versions;
},
getPackage: function (p) {
var self = this;
var rec = self.packages[p];
if (!rec) return null;
if (!rec) {
return null;
}
return rec.record;
},
getAllReleaseTracks: function () {
@@ -156,13 +164,17 @@ _.extend(DataStub.prototype, {
getSortedRecommendedReleaseVersions: function (t) {
var self = this;
var rec = self.releases[t];
if (!rec) return null;
if (!rec) {
return null;
}
return rec.versions;
},
getReleaseVersion: function (t, v) {
var self = this;
var rec = self.releases[t];
if (!rec) return null;
if (!rec) {
return null;
}
return rec.records[v];
}
});

View File

@@ -338,7 +338,9 @@ selftest.define("package-depends-on-either-version",
var lines = s.read(".meteor/versions").split("\n");
var depend = {};
_.each(lines, function(line) {
if (!line) return;
if (!line) {
return;
}
// Packages are stored of the form foo@1.0.0, so this should give us an
// array [foo, 1.0.0].
var split = line.split('@');

View File

@@ -200,10 +200,11 @@ selftest.define("checkout", ['checkout'], function () {
selftest.define("download and springboard to pre-0.9.0 release", ['net', 'slow'], function () {
var s, run;
if (files.inCheckout())
if (files.inCheckout()) {
s = new Sandbox({ warehouse: { v1: { tools: 'tools1', latest: true } } });
else
} else {
s = new Sandbox;
}
// End-to-end, online test of downloading and springboarding. This
// release was built from the

View File

@@ -279,9 +279,10 @@ var fetchPackageUsageForApp = function (identifier) {
}
});
if (! found)
if (! found) {
selftest.fail("Couldn't find app identifier in usage " +
"returned from package stats server");
}
return found;
};

View File

@@ -4,8 +4,9 @@ var files = require('../fs/files.js');
var catalog = require('../packaging/catalog/catalog.js');
function matchPath (text, doubleBS) {
if (process.platform === 'win32')
if (process.platform === 'win32') {
return text.replace(/\//g, doubleBS ? '\\\\' : '\\');
}
return text;
}
function matchPathRegexp (regexp) {

View File

@@ -19,8 +19,10 @@ selftest.define('subset generator', function () {
out = [];
utils.generateSubsetsOfIncreasingSize(['a', 'b', 'c'], function (x) {
out.push(x);
if (x[1] === 'c')
return true; // stop iterating
if (x[1] === 'c') {
// stop iterating
return true;
}
});
selftest.expectEqual(out, [
[],

View File

@@ -140,8 +140,12 @@ selftest.define("wipe all packages", function () {
// Check that all other packages are wiped
_.each(files.readdir(files.pathJoin(s.warehouse, 'packages')), function (p) {
if (p[0] === '.') return;
if (p === 'meteor-tool') return;
if (p[0] === '.') {
return;
}
if (p === 'meteor-tool') {
return;
}
var contents = files.readdir(files.pathJoin(s.warehouse, 'packages', p));
contents = _.filter(contents, notHidden);
selftest.expectTrue(contents.length === 0);

View File

@@ -129,8 +129,9 @@ var ensureIsopacketsLoadable = function () {
var messages = Console.withProgressDisplayVisible(function () {
return buildmessage.capture(function () {
_.each(ISOPACKETS, function (packages, isopacketName) {
if (failedPackageBuild)
if (failedPackageBuild) {
return;
}
var isopacketRoot = isopacketPath(isopacketName);
var existingBuildinfo = files.readJSONOrNull(
@@ -162,8 +163,9 @@ var ensureIsopacketsLoadable = function () {
}, function () {
// Build the packages into the in-memory IsopackCache.
isopacketBuildContext.isopackCache.buildLocalPackages(packages);
if (buildmessage.jobHasMessages())
if (buildmessage.jobHasMessages()) {
return;
}
// Now bundle them into a program.
var built = bundler.buildJsImage({
@@ -172,8 +174,9 @@ var ensureIsopacketsLoadable = function () {
isopackCache: isopacketBuildContext.isopackCache,
use: packages
});
if (buildmessage.jobHasMessages())
if (buildmessage.jobHasMessages()) {
return;
}
var builder = new Builder({outputPath: isopacketRoot});
builder.writeJson('isopacket-buildinfo.json', {
@@ -200,8 +203,9 @@ var ensureIsopacketsLoadable = function () {
// Returns a new all-local-packages catalog to be used for building isopackets.
var newIsopacketBuildingCatalog = function () {
if (! files.inCheckout())
if (! files.inCheckout()) {
throw Error("No need to build isopackets unless in checkout!");
}
var catalogLocal = require('../packaging/catalog/catalog-local.js');
var isopacketCatalog = new catalogLocal.LocalCatalog;

View File

@@ -24,16 +24,20 @@ var RequireInvocation = function (name, filename) {
RequireInvocation.prototype.isOurCode = function () {
var self = this;
if (! self.filename)
if (! self.filename) {
return self.name === 'TOP';
}
if (! self.name.match(/\//))
return false; // we always require our stuff via a path
if (! self.name.match(/\//)) {
// we always require our stuff via a path
return false;
}
var ourSource = path.resolve(__dirname);
var required = path.resolve(path.dirname(self.filename), self.name);
if (ourSource.length > required.length)
if (ourSource.length > required.length) {
return false;
}
return required.substr(0, ourSource.length) === ourSource;
};
@@ -47,10 +51,12 @@ RequireInvocation.prototype.why = function () {
walk = walk.parent;
}
if (! walk)
if (! walk) {
return "???";
if (last)
}
if (last) {
return path.basename(walk.name) + ":" + path.basename(last.name);
}
return path.basename(walk.name);
};
@@ -88,8 +94,9 @@ exports.printReport = function () {
childTime += child.totalTime;
});
if (inv.totalTime !== null)
if (inv.totalTime !== null) {
inv.selfTime = inv.totalTime - childTime;
}
};
computeTimes(currentInvocation);
@@ -97,9 +104,10 @@ exports.printReport = function () {
var summarize = function (inv, depth) {
// var padding = (new Array(depth*2 + 1)).join(' ');
// console.log(padding + inv.name + " [" + inv.selfTime + "]");
if (! (inv.name in summary))
if (! (inv.name in summary)) {
summary[inv.name] = { name: inv.name, time: 0, ours: inv.isOurCode(),
via: {} };
}
summary[inv.name].time += inv.selfTime;
if (! inv.isOurCode()) {
summary[inv.name].via[inv.why()] = true;
@@ -115,19 +123,22 @@ exports.printReport = function () {
var ourTotal = 0, otherTotal = 0;
_.each(times, function (item) {
var line = (item.time * 1000).toFixed(2) + " " + item.name;
if (! item.ours)
if (! item.ours) {
line += " [via " + _.keys(item.via).join(", ") + "]";
}
console.log(line);
if (item.ours)
if (item.ours) {
ourTotal += item.time;
else
} else {
otherTotal += item.time;
}
});
var grandTotal = currentInvocation.totalTime;
if (grandTotal - ourTotal - otherTotal > 1/1000)
if (grandTotal - ourTotal - otherTotal > 1/1000) {
throw new Error("Times don't add up");
}
console.log("TOTAL: ours " + (ourTotal * 1000).toFixed(2) +
", other " + (otherTotal * 1000).toFixed(2) +
", grand total " + (grandTotal * 1000).toFixed(2));

View File

@@ -171,8 +171,9 @@ var bucketTimes = {};
var spaces = function (x) {
var s = '';
for (var i = 0; i < x; ++i)
for (var i = 0; i < x; ++i) {
s += ' ';
}
return s;
};
@@ -186,18 +187,21 @@ var start = function () {
};
var Profile = function (bucketName, f) {
if (! enabled)
if (! enabled) {
return f;
}
return function (...args) {
if (! running)
if (! running) {
return f.apply(this, args);
}
var name;
if (_.isFunction(bucketName))
if (_.isFunction(bucketName)) {
name = bucketName.apply(this, args);
else
} else {
name = bucketName;
}
var currentEntry;
if (Fiber.current) {
@@ -224,7 +228,9 @@ var Profile = function (bucketName, f) {
currentEntry.pop();
}
if (err) throw err;
if (err) {
throw err;
}
};
};
@@ -276,7 +282,9 @@ var isLeaf = function (entry) {
};
var reportOnLeaf = function (level, entry) {
if (entryTime(entry) < filter) return;
if (entryTime(entry) < filter) {
return;
}
print(
level,
_.last(entry) + ": " + entryTime(entry).toFixed(1));
@@ -299,7 +307,9 @@ var injectOtherTime = function (entry) {
};
var reportOnParent = function (level, entry) {
if (entryTime(entry) < filter) return;
if (entryTime(entry) < filter) {
return;
}
print(level, entryName(entry) + ": " + entryTime(entry).toFixed(1));
_.each(children(entry), function (child) {
reportOn(level + 1, child);
@@ -307,10 +317,11 @@ var reportOnParent = function (level, entry) {
};
var reportOn = function (level, entry) {
if (hasChildren(entry))
if (hasChildren(entry)) {
reportOnParent(level, entry);
else
} else {
reportOnLeaf(level, entry);
}
};
var reportHierarchy = function () {
@@ -346,7 +357,9 @@ var reportTotals = function () {
});
var grandTotal = 0;
_.each(totals, function (total) {
if (total.time < filter) return;
if (total.time < filter) {
return;
}
print(0, total.name + ": " + total.time.toFixed(1));
grandTotal += total.time;
});
@@ -361,8 +374,9 @@ var setupReport = function () {
};
var report = function () {
if (! enabled)
if (! enabled) {
return;
}
running = false;
print(0, '');
setupReport();

View File

@@ -79,8 +79,9 @@ var expectThrows = markStack(function (f) {
threw = true;
}
if (! threw)
if (! threw) {
throw new TestFailure("expected-exception");
}
});
// Execute a command synchronously, discarding stderr.
@@ -132,12 +133,14 @@ var ROOT_PACKAGES_TO_BUILD_IN_SANDBOX = [
];
var setUpBuiltPackageTropohouse = function () {
if (builtPackageTropohouseDir)
if (builtPackageTropohouseDir) {
return;
}
builtPackageTropohouseDir = files.mkdtemp('built-package-tropohouse');
if (config.getPackagesDirectoryName() !== 'packages')
if (config.getPackagesDirectoryName() !== 'packages') {
throw Error("running self-test with METEOR_PACKAGE_SERVER_URL set?");
}
var tropohouse = new tropohouseModule.Tropohouse(builtPackageTropohouseDir);
tropohouseLocalCatalog = newSelfTestCatalog();
@@ -176,8 +179,9 @@ var setUpBuiltPackageTropohouse = function () {
};
var newSelfTestCatalog = function () {
if (! files.inCheckout())
if (! files.inCheckout()) {
throw Error("Only can build packages from a checkout");
}
var catalogLocal = require('../packaging/catalog/catalog-local.js');
var selfTestCatalog = new catalogLocal.LocalCatalog;
@@ -229,8 +233,9 @@ _.extend(Matcher.prototype, {
match: function (pattern, timeout, strict) {
var self = this;
if (self.matchFuture)
if (self.matchFuture) {
throw new Error("already have a match pending?");
}
self.matchPattern = pattern;
self.matchStrict = strict;
var f = self.matchFuture = new Future;
@@ -251,8 +256,9 @@ _.extend(Matcher.prototype, {
try {
return f.wait();
} finally {
if (timer)
if (timer) {
clearTimeout(timer);
}
}
},
@@ -275,8 +281,9 @@ _.extend(Matcher.prototype, {
var self = this;
var f = self.matchFuture;
if (! f)
if (! f) {
return;
}
var ret = null;
@@ -361,8 +368,9 @@ _.extend(OutputLog.prototype, {
write: function (channel, text) {
var self = this;
if (! _.has(self.buffers, 'channel'))
if (! _.has(self.buffers, 'channel')) {
self.buffers[channel] = { text: '', offset: 0};
}
var b = self.buffers[channel];
while (text.length) {
@@ -410,13 +418,15 @@ _.extend(OutputLog.prototype, {
forbid: function (pattern, channel) {
var self = this;
_.each(self.lines, function (line) {
if (channel && channel !== line.channel)
if (channel && channel !== line.channel) {
return;
}
var match = (pattern instanceof RegExp) ?
(line.text.match(pattern)) : (line.text.indexOf(pattern) !== -1);
if (match)
if (match) {
throw new TestFailure('forbidden-string-present', { run: self.run });
}
});
},
@@ -510,8 +520,9 @@ var Sandbox = function (options) {
}
if (_.has(options, 'warehouse')) {
if (!files.inCheckout())
if (!files.inCheckout()) {
throw Error("make only use a fake warehouse in a checkout");
}
self.warehouse = files.pathJoin(self.root, 'tropohouse');
self._makeWarehouse(options.warehouse);
}
@@ -548,10 +559,11 @@ var Sandbox = function (options) {
var meteorScript = process.platform === "win32" ? "meteor.bat" : "meteor";
// Figure out the 'meteor' to run
if (self.warehouse)
if (self.warehouse) {
self.execPath = files.pathJoin(self.warehouse, meteorScript);
else
} else {
self.execPath = files.pathJoin(files.getCurrentToolsDir(), meteorScript);
}
};
_.extend(Sandbox.prototype, {
@@ -630,8 +642,9 @@ _.extend(Sandbox.prototype, {
upgradersFile.appendUpgraders(upgraders.allUpgraders());
}
if (options.dontPrepareApp)
if (options.dontPrepareApp) {
return;
}
// Prepare the app (ie, build or download packages). We give this a nice
// long timeout, which allows the next command to not need a bloated
@@ -731,10 +744,11 @@ _.extend(Sandbox.prototype, {
read: function (filename) {
var self = this;
var file = files.pathJoin(self.cwd, filename);
if (!files.exists(file))
if (!files.exists(file)) {
return null;
else
} else {
return files.readFile(files.pathJoin(self.cwd, filename), 'utf8');
}
},
// Copy the contents of one file to another. In these series of tests, we often
@@ -803,8 +817,9 @@ _.extend(Sandbox.prototype, {
// By default (ie, with no mock warehouse and no --release arg) we should be
// testing the actual release this is built in, so we pretend that it is the
// latest release.
if (!self.warehouse && release.current.isProperRelease())
if (!self.warehouse && release.current.isProperRelease()) {
env.METEOR_TEST_LATEST_RELEASE = release.current.name;
}
return env;
},
@@ -845,13 +860,15 @@ _.extend(Sandbox.prototype, {
tropohouseIsopackCache.eachBuiltIsopack(function (packageName, isopack) {
var packageRec = tropohouseLocalCatalog.getPackage(packageName);
if (! packageRec)
if (! packageRec) {
throw Error("no package record for " + packageName);
}
stubCatalog.collections.packages.push(packageRec);
var versionRec = tropohouseLocalCatalog.getLatestVersion(packageName);
if (! versionRec)
if (! versionRec) {
throw Error("no version record for " + packageName);
}
stubCatalog.collections.versions.push(versionRec);
stubCatalog.collections.builds.push({
@@ -867,8 +884,9 @@ _.extend(Sandbox.prototype, {
}
});
if (! toolPackageVersion)
if (! toolPackageVersion) {
throw Error("no meteor-tool?");
}
stubCatalog.collections.releaseTracks.push({
name: catalog.DEFAULT_TRACK,
@@ -992,11 +1010,13 @@ _.extend(BrowserStackClient.prototype, {
var self = this;
// memoize the key
if (browserStackKey === null)
if (browserStackKey === null) {
browserStackKey = self._getBrowserStackKey();
if (! browserStackKey)
}
if (! browserStackKey) {
throw new Error("BrowserStack key not found. Ensure that you " +
"have installed your S3 credentials.");
}
var capabilities = {
'browserName' : self.browserName,
@@ -1010,8 +1030,9 @@ _.extend(BrowserStackClient.prototype, {
}
self._launchBrowserStackTunnel(function (error) {
if (error)
if (error) {
throw error;
}
self.driver = new webdriver.Builder().
usingServer('http://hub.browserstack.com/wd/hub').
@@ -1067,8 +1088,9 @@ _.extend(BrowserStackClient.prototype, {
// Called when the SSH tunnel is established.
self.tunnelProcess.stdout.on('data', function(data) {
if (data.toString().match(/You can now access your local server/))
if (data.toString().match(/You can now access your local server/)) {
callback();
}
});
}
});
@@ -1136,8 +1158,9 @@ _.extend(Run.prototype, {
args: function (...args) {
var self = this;
if (self.proc)
if (self.proc) {
throw new Error("already started?");
}
_.each(args, function (a) {
if (typeof a !== "object") {
@@ -1154,8 +1177,9 @@ _.extend(Run.prototype, {
connectClient: function () {
var self = this;
if (! self.client)
if (! self.client) {
throw new Error("Must create Run with a client to use connectClient().");
}
self._ensureStarted();
self.client.connect();
@@ -1164,8 +1188,9 @@ _.extend(Run.prototype, {
_exited: function (status) {
var self = this;
if (self.exitStatus !== undefined)
if (self.exitStatus !== undefined) {
throw new Error("already exited?");
}
self.client && self.client.stop();
@@ -1183,8 +1208,9 @@ _.extend(Run.prototype, {
_ensureStarted: function () {
var self = this;
if (self.proc)
if (self.proc) {
return;
}
var env = _.clone(process.env);
_.extend(env, self.env);
@@ -1196,18 +1222,21 @@ _.extend(Run.prototype, {
});
self.proc.on('close', function (code, signal) {
if (self.exitStatus === undefined)
if (self.exitStatus === undefined) {
self._exited({ code: code, signal: signal });
}
});
self.proc.on('exit', function (code, signal) {
if (self.exitStatus === undefined)
if (self.exitStatus === undefined) {
self._exited({ code: code, signal: signal });
}
});
self.proc.on('error', function (err) {
if (self.exitStatus === undefined)
if (self.exitStatus === undefined) {
self._exited(null);
}
});
self.proc.stdout.setEncoding('utf8');
@@ -1333,8 +1362,9 @@ _.extend(Run.prototype, {
}
}
if (! self.exitStatus)
if (! self.exitStatus) {
throw new TestFailure('spawn-failure', { run: self });
}
if (code !== undefined && self.exitStatus.code !== code) {
throw new TestFailure('wrong-exit-code', {
expected: { code: code },
@@ -1379,8 +1409,9 @@ _.extend(Run.prototype, {
// Kills the running process and it's child processes
_killProcess: function () {
if (!this.proc)
if (!this.proc) {
throw new Error("Unexpected: `this.proc` undefined when calling _killProcess");
}
if (process.platform === "win32") {
// looks like in Windows `self.proc.kill()` doesn't kill child
@@ -1403,8 +1434,9 @@ _.extend(Run.prototype, {
tellMongo: markStack(function (command) {
var self = this;
if (! self.fakeMongoPort)
if (! self.fakeMongoPort) {
throw new Error("fakeMongo option on sandbox must be set");
}
self._ensureStarted();
@@ -1432,29 +1464,35 @@ _.extend(Run.prototype, {
(function () {
var fut = new Future;
var conn = net.connect(self.fakeMongoPort, function () {
if (fut)
if (fut) {
fut['return'](true);
}
});
conn.setNoDelay();
conn.on('error', function () {
if (fut)
if (fut) {
fut['return'](false);
}
});
setTimeout(function () {
if (fut)
fut['return'](false); // 100ms connection timeout
if (fut) {
// 100ms connection timeout
fut['return'](false);
}
}, 100);
// This is all arranged so that if a previous attempt
// belatedly succeeds, somehow, we ignore it.
if (fut.wait())
if (fut.wait()) {
self.fakeMongoConnection = conn;
}
fut = null;
})();
}
if (! self.fakeMongoConnection)
if (! self.fakeMongoConnection) {
throw new TestFailure("mongo-not-running", { run: self });
}
}
self.fakeMongoConnection.write(JSON.stringify(command) + "\n");
@@ -1500,8 +1538,9 @@ var fileBeingLoaded = null;
var fileBeingLoadedHash = null;
var runningTest = null;
var getAllTests = function () {
if (allTests)
if (allTests) {
return allTests;
}
allTests = [];
// Load all files in the 'tests' directory that end in .js. They
@@ -1514,8 +1553,9 @@ var getAllTests = function () {
return;
}
try {
if (fileBeingLoaded)
if (fileBeingLoaded) {
throw new Error("called recursively?");
}
fileBeingLoaded = files.pathBasename(n, '.js');
var fullPath = files.pathJoin(testdir, n);
@@ -1762,10 +1802,12 @@ var getTestStateFilePath = function () {
var readTestState = function () {
var testStateFile = getTestStateFilePath();
var testState;
if (files.exists(testStateFile))
if (files.exists(testStateFile)) {
testState = JSON.parse(files.readFile(testStateFile, 'utf8'));
if (! testState || testState.version !== 1)
}
if (! testState || testState.version !== 1) {
testState = { version: 1, lastPassedHashes: {} };
}
return testState;
};
@@ -1899,8 +1941,9 @@ var runTests = function (options) {
testList.saveTestState();
if (totalRun > 0)
if (totalRun > 0) {
Console.error();
}
Console.error(testList.generateSkipReport());
@@ -1909,8 +1952,9 @@ var runTests = function (options) {
return 0;
} else if (failedTests.length === 0) {
var disclaimers = '';
if (testList.filteredTests.length < testList.allTests.length)
if (testList.filteredTests.length < testList.allTests.length) {
disclaimers += " other";
}
Console.error("All" + disclaimers + " tests passed.");
return 0;
} else {

View File

@@ -131,8 +131,9 @@ var host = function () {
if (! _host) {
var run = function (...args) {
var result = utils.execFileSync(args[0], args.slice(1)).stdout;
if (! result)
if (! result) {
throw new Error("can't get arch with " + args.join(" ") + "?");
}
return result.replace(/\s*$/, ''); // trailing whitespace
};
@@ -142,28 +143,29 @@ var host = function () {
// Can't just test uname -m = x86_64, because Snow Leopard can
// return other values.
if (run('uname', '-p') !== "i386" ||
run('sysctl', '-n', 'hw.cpu64bit_capable') !== "1")
run('sysctl', '-n', 'hw.cpu64bit_capable') !== "1") {
throw new Error("Only 64-bit Intel processors are supported on OS X");
}
_host = "os.osx.x86_64";
}
else if (platform === "linux") {
var machine = run('uname', '-m');
if (_.contains(["i386", "i686", "x86"], machine))
if (_.contains(["i386", "i686", "x86"], machine)) {
_host = "os.linux.x86_32";
else if (_.contains(["x86_64", "amd64", "ia64"], machine))
} else if (_.contains(["x86_64", "amd64", "ia64"], machine)) {
_host = "os.linux.x86_64";
else
} else {
throw new Error("Unsupported architecture: " + machine);
}
}
else if (platform === "win32") {
// We also use 32 bit builds on 64 bit Windows architectures.
_host = "os.windows.x86_32";
}
else
} else {
throw new Error("Unsupported operating system: " + platform);
}
}
return _host;
@@ -192,12 +194,14 @@ var mostSpecificMatch = function (host, programs) {
var best = null;
_.each(programs, function (p) {
if (seen[p])
if (seen[p]) {
throw new Error("Duplicate architecture: " + p);
}
seen[p] = true;
if (archinfo.matches(host, p) &&
(! best || p.length > best.length))
(! best || p.length > best.length)) {
best = p;
}
});
return best;
@@ -213,8 +217,9 @@ var mostSpecificMatch = function (host, programs) {
// 'os.linux.x86_64', return 'os.linux.x86_64'. For 'os' and 'browser', throw an
// exception.
var leastSpecificDescription = function (programs) {
if (programs.length === 0)
if (programs.length === 0) {
return '';
}
// Find the longest string
var longest = _.max(programs, function (p) { return p.length; });
@@ -224,17 +229,19 @@ var leastSpecificDescription = function (programs) {
// compatible with the most specific then it must be the least
// specific compatible description.
_.each(programs, function (p) {
if (! archinfo.matches(longest, p))
if (! archinfo.matches(longest, p)) {
throw new Error("Incompatible architectures: '" + p + "' and '" +
longest + "'");
}
});
return longest;
};
var withoutSpecificOs = function (arch) {
if (arch.substr(0, 3) === 'os.')
if (arch.substr(0, 3) === 'os.') {
return 'os';
}
return arch;
};

View File

@@ -102,14 +102,17 @@ _.extend(Job.prototype, {
}
}
if (! frame.func && ! where)
return; // that's a pretty lame stack frame
if (! frame.func && ! where) {
// that's a pretty lame stack frame
return;
}
line += " at ";
if (frame.func)
if (frame.func) {
line += frame.func + " (" + where + ")\n";
else
} else {
line += where + "\n";
}
});
line += "\n";
}
@@ -223,8 +226,9 @@ var getCurrentProgressTracker = function () {
var addChildTracker = function (title) {
var options = {};
if (title !== undefined)
if (title !== undefined) {
options.title = title;
}
return getCurrentProgressTracker().addChildTask(options);
};
@@ -242,8 +246,9 @@ var capture = function (options, f) {
var parentMessageSet = currentMessageSet.get();
var title;
if (typeof options === "object" && options.title)
if (typeof options === "object" && options.title) {
title = options.title;
}
var progress = addChildTracker(title);
currentProgress.withValue(progress, function () {
@@ -371,8 +376,9 @@ var enterJob = function (options, f) {
// (including subjobs created inside this job), else false.
var jobHasMessages = function () {
var search = function (job) {
if (job.hasMessages())
if (job.hasMessages()) {
return true;
}
return !! _.find(job.children, search);
};
@@ -418,14 +424,18 @@ var markBoundary = function (f) {
var error = function (message, options) {
options = options || {};
if (options.downcase)
if (options.downcase) {
message = message.slice(0,1).toLowerCase() + message.slice(1);
}
if (! currentJob.get())
if (! currentJob.get()) {
throw new Error("Error: " + message);
}
if (options.secondary && jobHasMessages())
return; // skip it
if (options.secondary && jobHasMessages()) {
// skip it
return;
}
var info = _.extend({
message: message
@@ -510,22 +520,26 @@ var exception = function (error) {
};
var assertInJob = function () {
if (! currentJob.get())
if (! currentJob.get()) {
throw new Error("Expected to be in a buildmessage job");
}
};
var assertInCapture = function () {
if (! currentMessageSet.get())
if (! currentMessageSet.get()) {
throw new Error("Expected to be in a buildmessage capture");
}
};
var mergeMessagesIntoCurrentJob = function (innerMessages) {
var outerMessages = currentMessageSet.get();
if (! outerMessages)
if (! outerMessages) {
throw new Error("Expected to be in a buildmessage capture");
}
var outerJob = currentJob.get();
if (! outerJob)
if (! outerJob) {
throw new Error("Expected to be in a buildmessage job");
}
_.each(innerMessages.jobs, function (j) {
outerJob.children.push(j);
});

View File

@@ -14,10 +14,11 @@ var _ = require('underscore');
// ]
// }
var convertBySchema = function (val, schema) {
if (schema === true)
if (schema === true) {
return convert(val);
else if (schema === false)
} else if (schema === false) {
return val;
}
if (_.isArray(schema)) {
if (schema.length !== 1) {
@@ -33,13 +34,15 @@ var convertBySchema = function (val, schema) {
});
}
if (! _.isObject(schema))
if (! _.isObject(schema)) {
throw new Error("Unexpected type of schema: " + typeof(schema));
}
var ret = _.clone(val);
_.each(schema, function (subschema, key) {
if (_.has(ret, key))
if (_.has(ret, key)) {
ret[key] = convertBySchema(val[key], subschema);
}
});
return ret;

View File

@@ -16,8 +16,9 @@ exports.parallelEach = function (collection, callback, context) {
exports.firstTimeResolver = function (fut) {
var resolver = fut.resolver();
return function (err, val) {
if (fut.isResolved())
if (fut.isResolved()) {
return;
}
resolver(err, val);
};
};
@@ -28,10 +29,12 @@ exports.firstTimeResolver = function (fut) {
// the other be throw-only.)
exports.waitForOne = function (...futures) {
var fiber = Fiber.current;
if (!fiber)
if (!fiber) {
throw Error("Can't waitForOne without a fiber");
if (futures.length === 0)
}
if (futures.length === 0) {
throw Error("Must wait for at least one future");
}
var combinedFuture = new Future;
for (var i = 0; i < futures.length; ++i) {
@@ -91,10 +94,12 @@ _.extend(exports.EnvironmentVariable.prototype, {
var self = this;
exports.nodeCodeMustBeInFiber();
if (!Fiber.current._meteorDynamics)
if (!Fiber.current._meteorDynamics) {
return self.defaultValue;
if (!_.has(Fiber.current._meteorDynamics, self.slot))
}
if (!_.has(Fiber.current._meteorDynamics, self.slot)) {
return self.defaultValue;
}
return Fiber.current._meteorDynamics[self.slot];
},
@@ -102,8 +107,9 @@ _.extend(exports.EnvironmentVariable.prototype, {
var self = this;
exports.nodeCodeMustBeInFiber();
if (!Fiber.current._meteorDynamics)
if (!Fiber.current._meteorDynamics) {
Fiber.current._meteorDynamics = {};
}
var currentValues = Fiber.current._meteorDynamics;
var saved = _.has(currentValues, self.slot)
@@ -140,8 +146,9 @@ exports.bindEnvironment = function (func) {
}
};
if (Fiber.current)
if (Fiber.current) {
return runWithEnvironment();
}
Fiber(runWithEnvironment).run();
};
};

View File

@@ -64,15 +64,16 @@ _.extend(WritableWithProgress.prototype, {
var getUserAgent = function () {
var version;
if (release.current)
if (release.current) {
version = release.current.isCheckout() ? 'checkout' : release.current.name;
else
} else {
// This happens when we haven't finished starting up yet (say, the
// user passed --release 1.2.3 and we have to download 1.2.3
// before we can get going), or if we are using an installed copy
// of Meteor to 'meteor update'ing a project that was created by a
// checkout and doesn't have a version yet.
version = files.inCheckout() ? 'checkout' : files.getToolsVersion();
}
return util.format('Meteor/%s OS/%s (%s; %s; %s;)', version,
os.platform(), os.type(), os.release(), os.arch());
@@ -121,10 +122,11 @@ _.extend(exports, {
// the session file afterwards.
request: function (urlOrOptions, callback) {
var options;
if (!_.isObject(urlOrOptions))
if (!_.isObject(urlOrOptions)) {
options = { url: urlOrOptions };
else
} else {
options = _.clone(urlOrOptions);
}
var bodyStream;
if (_.has(options, 'bodyStream')) {
@@ -187,15 +189,18 @@ _.extend(exports, {
delete options.useAuthHeader;
if (useSessionHeader || useAuthHeader) {
var sessionHeader = auth.getSessionId(config.getAccountsDomain());
if (sessionHeader)
if (sessionHeader) {
options.headers['X-Meteor-Session'] = sessionHeader;
if (callback)
}
if (callback) {
throw new Error("session header can't be used with callback");
}
}
if (useAuthHeader) {
var authHeader = auth.getSessionToken(config.getAccountsDomain());
if (authHeader)
if (authHeader) {
options.headers['X-Meteor-Auth'] = authHeader;
}
}
var fut;
@@ -210,8 +215,9 @@ _.extend(exports, {
var setCookie = {};
_.each(response.headers["set-cookie"] || [], function (h) {
var match = h.match(/^([^=\s]+)=([^;\s]+)/);
if (match)
if (match) {
setCookie[match[1]] = match[2];
}
});
if (useSessionHeader && _.has(response.headers, "x-meteor-session")) {

View File

@@ -154,7 +154,9 @@ exports.getHost = function (...args) {
// scutil --get ComputerName
// This can contain spaces. See
// http://osxdaily.com/2012/10/24/set-the-hostname-computer-name-and-bonjour-name-separately-in-os-x/
if (! ret) attempt("scutil", "--get", "ComputerName");
if (! ret) {
attempt("scutil", "--get", "ComputerName");
}
}
if (archinfo.matches(archinfo.host(), 'os.osx') ||
@@ -162,13 +164,17 @@ exports.getHost = function (...args) {
// On Unix-like platforms, try passing -s to hostname to strip off
// the domain name, to reduce the extent to which the output
// varies with DNS.
if (! ret) attempt("hostname", "-s");
if (! ret) {
attempt("hostname", "-s");
}
}
// Try "hostname" on any platform. It should work on
// Windows. Unknown platforms that have a command called "hostname"
// that deletes all of your files deserve what the get.
if (! ret) attempt("hostname");
if (! ret) {
attempt("hostname");
}
// Otherwise, see what Node can come up with.
return ret || os.hostname();
@@ -182,8 +188,9 @@ exports.getAgentInfo = function () {
var ret = {};
var host = utils.getHost();
if (host)
if (host) {
ret.host = host;
}
ret.agent = "Meteor";
ret.agentVersion =
files.inCheckout() ? "checkout" : files.getToolsVersion();
@@ -196,8 +203,9 @@ exports.getAgentInfo = function () {
// called within a fiber, and blocks only the calling fiber, not the
// whole program.)
exports.sleepMs = function (ms) {
if (ms <= 0)
if (ms <= 0) {
return;
}
var fut = new Future;
setTimeout(function () { fut['return']() }, ms);
@@ -221,8 +229,9 @@ exports.parsePackageConstraint = function (constraintString, options) {
try {
return packageVersionParser.parsePackageConstraint(constraintString);
} catch (e) {
if (! (e.versionParserError && options && options.useBuildmessage))
if (! (e.versionParserError && options && options.useBuildmessage)) {
throw e;
}
buildmessage.error(e.message, { file: options.buildmessageFile });
return null;
}
@@ -232,8 +241,9 @@ exports.validatePackageName = function (name, options) {
try {
return packageVersionParser.validatePackageName(name, options);
} catch (e) {
if (! (e.versionParserError && options && options.useBuildmessage))
if (! (e.versionParserError && options && options.useBuildmessage)) {
throw e;
}
buildmessage.error(e.message, { file: options.buildmessageFile });
return null;
}
@@ -297,8 +307,9 @@ exports.isValidPackageName = function (packageName) {
exports.validatePackageName(packageName);
return true;
} catch (e) {
if (!e.versionParserError)
if (!e.versionParserError) {
throw e;
}
return false;
}
};
@@ -307,8 +318,9 @@ exports.validatePackageNameOrExit = function (packageName, options) {
try {
exports.validatePackageName(packageName, options);
} catch (e) {
if (!e.versionParserError)
if (!e.versionParserError) {
throw e;
}
var Console = require('../console/console.js').Console;
Console.error(e.message, Console.options({ bulletPoint: "Error: " }));
// lazy-load main: old bundler tests fail if you add a circular require to
@@ -351,8 +363,9 @@ exports.timeoutScaleFactor = timeoutScaleFactor;
// before '.', this means that 1.2 will sort before 1.2.3.)
exports.defaultOrderKeyForReleaseVersion = function (v) {
var m = v.match(/^(\d{1,4}(?:\.\d{1,4})*)(?:-([-A-Za-z.]{1,15})(\d{0,4}))?$/);
if (!m)
if (!m) {
return null;
}
var numberPart = m[1];
var prereleaseTag = m[2];
var prereleaseNumber = m[3];
@@ -361,14 +374,16 @@ exports.defaultOrderKeyForReleaseVersion = function (v) {
return x.length > 1 && x[0] === '0';
};
var leftPad = function (chr, len, str) {
if (str.length > len)
if (str.length > len) {
throw Error("too long to pad!");
}
var padding = new Array(len - str.length + 1).join(chr);
return padding + str;
};
var rightPad = function (chr, len, str) {
if (str.length > len)
if (str.length > len) {
throw Error("too long to pad!");
}
var padding = new Array(len - str.length + 1).join(chr);
return str + padding;
};
@@ -376,20 +391,24 @@ exports.defaultOrderKeyForReleaseVersion = function (v) {
// Versions must have no redundant leading zeroes, or else this encoding would
// be ambiguous.
var numbers = numberPart.split('.');
if (_.any(numbers, hasRedundantLeadingZero))
if (_.any(numbers, hasRedundantLeadingZero)) {
return null;
if (prereleaseNumber && hasRedundantLeadingZero(prereleaseNumber))
}
if (prereleaseNumber && hasRedundantLeadingZero(prereleaseNumber)) {
return null;
}
// First, put together the non-prerelease part.
var ret = _.map(numbers, _.partial(leftPad, '0', 4)).join('.');
if (!prereleaseTag)
if (!prereleaseTag) {
return ret + '$';
}
ret += '!' + rightPad('!', 15, prereleaseTag);
if (prereleaseNumber)
if (prereleaseNumber) {
ret += leftPad('0', 4, prereleaseNumber);
}
return ret + '$';
};
@@ -447,8 +466,9 @@ exports.generateSubsetsOfIncreasingSize = function (total, cb) {
generateSubsetsOfFixedSize(goalSize, []);
}
} catch (e) {
if (!(e instanceof Done))
if (!(e instanceof Done)) {
throw e;
}
}
};
@@ -544,8 +564,9 @@ exports.execFileAsync = function (file, args, opts) {
var logOutput = fiberHelpers.bindEnvironment(function (line) {
if (opts.verbose) {
line = mapper(line);
if (line)
if (line) {
console.log(line);
}
}
});
@@ -627,7 +648,9 @@ _.extend(exports.ThrottledYield.prototype, {
// date object and returns a long-form human-readable date (ex: December 9th,
// 2014) or unknown for null.
exports.longformDate = function (date) {
if (! date) return "Unknown";
if (! date) {
return "Unknown";
}
var moment = require('moment');
var pubDate = moment(date).format('MMMM Do, YYYY');
return pubDate;
@@ -647,7 +670,9 @@ exports.sha256 = function (contents) {
};
exports.sourceMapLength = function (sm) {
if (! sm) return 0;
if (! sm) {
return 0;
}
// sum the length of sources and the mappings, the size of
// metadata is ignored, but it is not a big deal
return sm.mappings.length