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

View File

@@ -39,7 +39,9 @@ var getReleaseVersionPublishedOn = function (versionRecord) {
var toolName = toolPackage[0]; var toolName = toolPackage[0];
var toolVersion = toolPackage[1]; var toolVersion = toolPackage[1];
var toolRecord = catalog.official.getVersion(toolName, toolVersion); var toolRecord = catalog.official.getVersion(toolName, toolVersion);
if (! toolRecord || ! toolRecord.published) return null; if (! toolRecord || ! toolRecord.published) {
return null;
}
return new Date(toolRecord.published); return new Date(toolRecord.published);
}; };
@@ -243,8 +245,9 @@ _.extend(PkgExports.prototype, {
var strExports = _.map(self.data, function (exp) { var strExports = _.map(self.data, function (exp) {
// If this export is valid for all architectures, don't specify // If this export is valid for all architectures, don't specify
// architectures here. // architectures here.
if (exp.architectures.length === compiler.ALL_ARCHES.length) if (exp.architectures.length === compiler.ALL_ARCHES.length) {
return exp.name; return exp.name;
}
// Don't split descriptions of individual pkgExports between lines. // Don't split descriptions of individual pkgExports between lines.
return Console.noWrap( return Console.noWrap(
@@ -269,7 +272,9 @@ var PkgImplies = function (pkgDeps) {
// and save their architectures. Also, we want to replace 'os' with // and save their architectures. Also, we want to replace 'os' with
// 'server', as with exports. // 'server', as with exports.
_.each(ref.references, function (r) { _.each(ref.references, function (r) {
if (! r.implied) return; if (! r.implied) {
return;
}
var archName = (r.arch === "os") ? "server" : r.arch; var archName = (r.arch === "os") ? "server" : r.arch;
architectures.push(archName); architectures.push(archName);
}); });
@@ -294,8 +299,9 @@ _.extend(PkgImplies.prototype, {
var self = this; var self = this;
var strImplies = _.map(self.data, function (ref) { var strImplies = _.map(self.data, function (ref) {
// If an imply is valid for all architectures, don't specify it here. // 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; return ref.name;
}
// Don't split descriptions of individual implies between lines. // Don't split descriptions of individual implies between lines.
return Console.noWrap( return Console.noWrap(
@@ -638,7 +644,9 @@ _.extend(PackageQuery.prototype, {
if (self.showArchitecturesOS) { if (self.showArchitecturesOS) {
var allBuilds = catalog.official.getAllBuilds(self.name, version); var allBuilds = catalog.official.getAllBuilds(self.name, version);
var architectures = _.map(allBuilds, function (build) { var architectures = _.map(allBuilds, function (build) {
if (! build['buildArchitectures']) return "unknown"; if (! build['buildArchitectures']) {
return "unknown";
}
var archOS = var archOS =
_.filter(build.buildArchitectures.split('+'), function (arch) { _.filter(build.buildArchitectures.split('+'), function (arch) {
return ( arch !== "web.browser" ) && ( arch !== "web.cordova" ); return ( arch !== "web.browser" ) && ( arch !== "web.cordova" );
@@ -1493,8 +1501,9 @@ main.registerCommand({
var filterBroken = function (match, isRelease, name) { var filterBroken = function (match, isRelease, name) {
// If the package does not match, or it is not a package at all or if we // 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. // don't want to filter anyway, we do not care.
if (!match || isRelease) if (!match || isRelease) {
return match; return match;
}
var vr; var vr;
if (!options["show-all"]) { if (!options["show-all"]) {
// If we can't find a version in the local catalog, we want to get the // 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) { if (!rec) {
// Not a package! But is it a release track? // Not a package! But is it a release track?
rec = catalog.official.getReleaseTrack(name); rec = catalog.official.getReleaseTrack(name);
if (rec) if (rec) {
rel = true; rel = true;
}
} }
return { record: rec, isRelease: rel }; return { record: rec, isRelease: rel };
}; };
@@ -330,8 +331,9 @@ main.registerCommand({
} }
var packageName = localVersionRecord.packageName; var packageName = localVersionRecord.packageName;
var packageSource = projectContext.localCatalog.getPackageSource(packageName); var packageSource = projectContext.localCatalog.getPackageSource(packageName);
if (! packageSource) if (! packageSource) {
throw Error("no PackageSource for " + packageName); throw Error("no PackageSource for " + packageName);
}
// Anything published to the server must explicitly set a version. // Anything published to the server must explicitly set a version.
if (! packageSource.versionExplicitlyProvided) { if (! packageSource.versionExplicitlyProvided) {
@@ -385,8 +387,9 @@ main.registerCommand({
} }
// If we're already using this package, that's OK; no need to override. // 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; return;
}
projectContext.projectConstraintsFile.addConstraints( projectContext.projectConstraintsFile.addConstraints(
[utils.parsePackageConstraint(name)]); [utils.parsePackageConstraint(name)]);
}); });
@@ -655,8 +658,9 @@ main.registerCommand({
}); });
var isopk = projectContext.isopackCache.getIsopack(name); var isopk = projectContext.isopackCache.getIsopack(name);
if (! isopk) if (! isopk) {
throw Error("didn't build isopack for " + name); throw Error("didn't build isopack for " + name);
}
var conn; var conn;
try { try {
@@ -873,8 +877,9 @@ main.registerCommand({
buildmessage.enterJob("checking consistency of " + packageName, function () { buildmessage.enterJob("checking consistency of " + packageName, function () {
var packageSource = projectContext.localCatalog.getPackageSource( var packageSource = projectContext.localCatalog.getPackageSource(
packageName); packageName);
if (! packageSource) if (! packageSource) {
throw Error("no PackageSource for built package " + packageName); throw Error("no PackageSource for built package " + packageName);
}
if (! packageSource.versionExplicitlyProvided) { if (! packageSource.versionExplicitlyProvided) {
buildmessage.error( buildmessage.error(
@@ -914,8 +919,9 @@ main.registerCommand({
return; return;
} else { } else {
var isopk = projectContext.isopackCache.getIsopack(packageName); var isopk = projectContext.isopackCache.getIsopack(packageName);
if (! isopk) if (! isopk) {
throw Error("no isopack for " + packageName); throw Error("no isopack for " + packageName);
}
var existingBuild = var existingBuild =
catalog.official.getBuildWithPreciseBuildArchitectures( catalog.official.getBuildWithPreciseBuildArchitectures(
@@ -957,12 +963,14 @@ main.registerCommand({
"publishing package " + packageName, "publishing package " + packageName,
function () { function () {
var isopk = projectContext.isopackCache.getIsopack(packageName); var isopk = projectContext.isopackCache.getIsopack(packageName);
if (! isopk) if (! isopk) {
throw Error("no isopack for " + packageName); throw Error("no isopack for " + packageName);
}
var packageSource = projectContext.localCatalog.getPackageSource( var packageSource = projectContext.localCatalog.getPackageSource(
packageName); packageName);
if (! packageSource) if (! packageSource) {
throw Error("no PackageSource for built package " + packageName); throw Error("no PackageSource for built package " + packageName);
}
var binary = isopk.platformSpecific(); var binary = isopk.platformSpecific();
packageClient.publishPackage({ packageClient.publishPackage({
@@ -972,8 +980,9 @@ main.registerCommand({
new: ! catalog.official.getPackage(packageName), new: ! catalog.official.getPackage(packageName),
doNotPublishBuild: binary doNotPublishBuild: binary
}); });
if (buildmessage.jobHasMessages()) if (buildmessage.jobHasMessages()) {
return; return;
}
Console.info( Console.info(
'Published ' + packageName + '@' + packageSource.version + '.'); 'Published ' + packageName + '@' + packageSource.version + '.');
@@ -1003,8 +1012,9 @@ main.registerCommand({
packageClient.callPackageServerBM( packageClient.callPackageServerBM(
conn, 'createReleaseTrack', { name: relConf.track } ); conn, 'createReleaseTrack', { name: relConf.track } );
}); });
if (buildmessage.jobHasMessages()) if (buildmessage.jobHasMessages()) {
return; return;
}
} }
buildmessage.enterJob("creating a new release version", function () { buildmessage.enterJob("creating a new release version", function () {
@@ -1122,12 +1132,14 @@ main.registerCommand({
var packageName = constraint.package; var packageName = constraint.package;
// Skip isobuild:* pseudo-packages. // Skip isobuild:* pseudo-packages.
if (compiler.isIsobuildFeaturePackage(packageName)) if (compiler.isIsobuildFeaturePackage(packageName)) {
return; return;
}
var mapInfo = projectContext.packageMap.getInfo(packageName); var mapInfo = projectContext.packageMap.getInfo(packageName);
if (! mapInfo) if (! mapInfo) {
throw Error("no version for used package " + packageName); throw Error("no version for used package " + packageName);
}
var versionRecord = projectContext.projectCatalog.getVersion( var versionRecord = projectContext.projectCatalog.getVersion(
packageName, mapInfo.version); packageName, mapInfo.version);
if (! versionRecord) { if (! versionRecord) {
@@ -1309,8 +1321,9 @@ var maybeUpdateRelease = function (options) {
// At this point we should have a release. (If we didn't to start // 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, // with, #UpdateSpringboard fixed that.) And it can't be a checkout,
// because we checked for that at the very beginning. // 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?"); 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 // 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 // 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 solutionReleaseVersion = _.find(releaseVersionsToTry, function (versionToTry) {
var releaseRecord = catalog.official.getReleaseVersion( var releaseRecord = catalog.official.getReleaseVersion(
releaseTrack, versionToTry); releaseTrack, versionToTry);
if (!releaseRecord) if (!releaseRecord) {
throw Error("missing release record?"); throw Error("missing release record?");
}
// Reset the project context and pretend we're using the potential release. // Reset the project context and pretend we're using the potential release.
projectContext.reset({ releaseForConstraints: releaseRecord }); projectContext.reset({ releaseForConstraints: releaseRecord });
@@ -1611,8 +1625,9 @@ main.registerCommand({
var upgradeIndirectDepPatchVersions = false; var upgradeIndirectDepPatchVersions = false;
if (options.args.length === 0) { if (options.args.length === 0) {
projectContext.projectConstraintsFile.eachConstraint(function (constraint) { projectContext.projectConstraintsFile.eachConstraint(function (constraint) {
if (! compiler.isIsobuildFeaturePackage(constraint.package)) if (! compiler.isIsobuildFeaturePackage(constraint.package)) {
upgradePackageNames.push(constraint.package); upgradePackageNames.push(constraint.package);
}
}); });
upgradeIndirectDepPatchVersions = true; upgradeIndirectDepPatchVersions = true;
} else { } else {
@@ -1645,8 +1660,9 @@ main.registerCommand({
main.captureAndExit( main.captureAndExit(
"=> Errors while upgrading packages:", "upgrading packages", function () { "=> Errors while upgrading packages:", "upgrading packages", function () {
projectContext.resolveConstraints(); projectContext.resolveConstraints();
if (buildmessage.jobHasMessages()) if (buildmessage.jobHasMessages()) {
return; return;
}
// If the user explicitly mentioned some packages to upgrade, they must // If the user explicitly mentioned some packages to upgrade, they must
// actually end up in our solution! // actually end up in our solution!
@@ -1655,8 +1671,9 @@ main.registerCommand({
buildmessage.error(packageName + ': package is not in the project'); buildmessage.error(packageName + ': package is not in the project');
} }
}); });
if (buildmessage.jobHasMessages()) if (buildmessage.jobHasMessages()) {
return; return;
}
// Finish preparing the project. // Finish preparing the project.
projectContext.prepareProjectForBuild(); projectContext.prepareProjectForBuild();
@@ -1894,7 +1911,9 @@ main.registerCommand({
changed && projectContext.cordovaPluginsFile.write(plugins); 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 // Messages that we should print if we make any changes, but that don't count
// as errors. // as errors.
@@ -1910,8 +1929,9 @@ main.registerCommand({
var constraint = utils.parsePackageConstraint(packageReq, { var constraint = utils.parsePackageConstraint(packageReq, {
useBuildmessage: true useBuildmessage: true
}); });
if (buildmessage.jobHasMessages()) if (buildmessage.jobHasMessages()) {
return; return;
}
// It's OK to make errors based on looking at the catalog, because this // It's OK to make errors based on looking at the catalog, because this
// is a OnceAtStart command. // is a OnceAtStart command.
@@ -1923,8 +1943,9 @@ main.registerCommand({
} }
_.each(constraint.versionConstraint.alternatives, function (subConstr) { _.each(constraint.versionConstraint.alternatives, function (subConstr) {
if (subConstr.versionString === null) if (subConstr.versionString === null) {
return; return;
}
// Figure out if this version exists either in the official catalog or // Figure out if this version exists either in the official catalog or
// the local catalog. (This isn't the same as using the combined // 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 // catalog, since it's OK to type "meteor add foo@1.0.0" if the local
@@ -1942,8 +1963,9 @@ main.registerCommand({
subConstr.versionString); subConstr.versionString);
} }
}); });
if (buildmessage.jobHasMessages()) if (buildmessage.jobHasMessages()) {
return; return;
}
var current = projectContext.projectConstraintsFile.getConstraint( var current = projectContext.projectConstraintsFile.getConstraint(
constraint.package); constraint.package);
@@ -2082,7 +2104,9 @@ main.registerCommand({
changed && projectContext.cordovaPluginsFile.write(plugins); 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 // 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 // user. Because removing each package is a completely atomic operation that
@@ -2102,8 +2126,9 @@ main.registerCommand({
packagesToRemove.push(packageName); packagesToRemove.push(packageName);
} }
}); });
if (! packagesToRemove.length) if (! packagesToRemove.length) {
return exitCode; return exitCode;
}
// Remove the packages from the in-memory representation of .meteor/packages. // Remove the packages from the in-memory representation of .meteor/packages.
projectContext.projectConstraintsFile.removePackages(packagesToRemove); projectContext.projectConstraintsFile.removePackages(packagesToRemove);
@@ -2230,10 +2255,11 @@ main.registerCommand({
Console.info(); Console.info();
Console.info("The maintainers for " + name + " are:"); Console.info("The maintainers for " + name + " are:");
_.each(record.maintainers, function (user) { _.each(record.maintainers, function (user) {
if (! user || !user.username) if (! user || !user.username) {
Console.rawInfo("<unknown>" + "\n"); Console.rawInfo("<unknown>" + "\n");
else } else {
Console.rawInfo(user.username + "\n"); Console.rawInfo(user.username + "\n");
}
}); });
return 0; return 0;
}); });
@@ -2280,8 +2306,9 @@ main.registerCommand({
var toolPackageVersion = releaseRecord.tool && var toolPackageVersion = releaseRecord.tool &&
utils.parsePackageAndVersion(releaseRecord.tool); utils.parsePackageAndVersion(releaseRecord.tool);
if (!toolPackageVersion) if (!toolPackageVersion) {
throw new Error("bad tool in release: " + releaseRecord.tool); throw new Error("bad tool in release: " + releaseRecord.tool);
}
var toolPackage = toolPackageVersion.package; var toolPackage = toolPackageVersion.package;
var toolVersion = toolPackageVersion.version; var toolVersion = toolPackageVersion.version;
@@ -2416,8 +2443,9 @@ main.registerCommand({
var toolIsopack = new isopack.Isopack; var toolIsopack = new isopack.Isopack;
toolIsopack.initFromPath(toolPackage, toolIsopackPath); toolIsopack.initFromPath(toolPackage, toolIsopackPath);
var toolRecord = _.findWhere(toolIsopack.toolsOnDisk, {arch: osArch}); var toolRecord = _.findWhere(toolIsopack.toolsOnDisk, {arch: osArch});
if (!toolRecord) if (!toolRecord) {
throw Error("missing tool for " + osArch); throw Error("missing tool for " + osArch);
}
tmpTropo.linkToLatestMeteor(files.pathJoin( tmpTropo.linkToLatestMeteor(files.pathJoin(
tmpTropo.packagePath(toolPackage, toolVersion, true), 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 // In the future, you should be able to make this default to some
// other domain you control, rather than 'meteor.com'. // other domain you control, rather than 'meteor.com'.
var qualifySitename = function (site) { var qualifySitename = function (site) {
if (site.indexOf(".") === -1) if (site.indexOf(".") === -1) {
site = site + ".meteor.com"; 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); site = site.substring(0, site.length - 1);
}
return site; return site;
}; };
@@ -187,8 +189,9 @@ main.registerCommand({
catalogRefresh: new catalog.Refresh.Never() catalogRefresh: new catalog.Refresh.Never()
}, function (options) { }, function (options) {
if (release.current === null) { if (release.current === null) {
if (! options.appDir) if (! options.appDir) {
throw new Error("missing release, but not in an app?"); throw new Error("missing release, but not in an app?");
}
Console.error( Console.error(
"This project was created with a checkout of Meteor, rather than an " + "This project was created with a checkout of Meteor, rather than an " +
"official release, and doesn't have a release number associated with " + "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; appPort = appPortMatch[2] ? parseInt(appPortMatch[2]) : null;
} }
if (options['raw-logs']) if (options['raw-logs']) {
runLog.setRawLogs(true); runLog.setRawLogs(true);
}
// Velocity testing. Sets up a DDP connection to the app process and // Velocity testing. Sets up a DDP connection to the app process and
// runs phantomjs. // runs phantomjs.
@@ -516,10 +520,11 @@ main.registerCommand({
return transform(f); return transform(f);
}, },
transformContents: function (contents, f) { transformContents: function (contents, f) {
if ((/(\.html|\.js|\.css)/).test(f)) if ((/(\.html|\.js|\.css)/).test(f)) {
return new Buffer(transform(contents.toString())); return new Buffer(transform(contents.toString()));
else } else {
return contents; return contents;
}
}, },
ignore: [/^local$/] ignore: [/^local$/]
}); });
@@ -578,12 +583,13 @@ main.registerCommand({
}; };
var appPathAsEntered; var appPathAsEntered;
if (options.args.length === 1) if (options.args.length === 1) {
appPathAsEntered = options.args[0]; appPathAsEntered = options.args[0];
else if (options.example) } else if (options.example) {
appPathAsEntered = options.example; appPathAsEntered = options.example;
else } else {
throw new main.ShowUsage; throw new main.ShowUsage;
}
var appPath = files.pathResolve(appPathAsEntered); var appPath = files.pathResolve(appPathAsEntered);
if (files.findAppDir(appPath)) { if (files.findAppDir(appPath)) {
@@ -682,10 +688,11 @@ ${nonCodeFileExts.join(', ')}
return transform(f); return transform(f);
}, },
transformContents: function (contents, f) { transformContents: function (contents, f) {
if ((/(\.html|\.js|\.css)/).test(f)) if ((/(\.html|\.js|\.css)/).test(f)) {
return new Buffer(transform(contents.toString())); return new Buffer(transform(contents.toString()));
else } else {
return contents; return contents;
}
}, },
ignore: toIgnore ignore: toIgnore
}); });
@@ -704,13 +711,15 @@ ${nonCodeFileExts.join(', ')}
main.captureAndExit("=> Errors while creating your project", function () { main.captureAndExit("=> Errors while creating your project", function () {
projectContext.readProjectMetadata(); projectContext.readProjectMetadata();
if (buildmessage.jobHasMessages()) if (buildmessage.jobHasMessages()) {
return; return;
}
projectContext.releaseFile.write( projectContext.releaseFile.write(
release.current.isCheckout() ? "none" : release.current.name); release.current.isCheckout() ? "none" : release.current.name);
if (buildmessage.jobHasMessages()) if (buildmessage.jobHasMessages()) {
return; return;
}
// Any upgrader that is in this version of Meteor doesn't need to be run on // Any upgrader that is in this version of Meteor doesn't need to be run on
// this project. // this project.
@@ -934,8 +943,9 @@ on an OS X system.");
return 1; return 1;
} }
if (! options._serverOnly) if (! options._serverOnly) {
files.mkdir_p(outputPath); files.mkdir_p(outputPath);
}
if (! options.directory) { if (! options.directory) {
main.captureAndExit('', 'creating server tarball', () => { main.captureAndExit('', 'creating server tarball', () => {
@@ -971,7 +981,9 @@ on an OS X system.");
{ title: `building Cordova app for \ { title: `building Cordova app for \
${cordova.displayNameForPlatform(platform)}` }, () => { ${cordova.displayNameForPlatform(platform)}` }, () => {
let buildOptions = []; let buildOptions = [];
if (!options.debug) buildOptions.push('--release'); if (!options.debug) {
buildOptions.push('--release');
}
cordovaProject.buildForPlatform(platform, buildOptions); cordovaProject.buildForPlatform(platform, buildOptions);
const buildPath = files.pathJoin( const buildPath = files.pathJoin(
@@ -1154,15 +1166,17 @@ to this command.`);
mongoUrl = deploy.temporaryMongoUrl(site); mongoUrl = deploy.temporaryMongoUrl(site);
usedMeteorAccount = true; usedMeteorAccount = true;
if (! mongoUrl) if (! mongoUrl) {
// temporaryMongoUrl() will have printed an error message // temporaryMongoUrl() will have printed an error message
return 1; return 1;
}
} }
if (options.url) { if (options.url) {
console.log(mongoUrl); console.log(mongoUrl);
} else { } else {
if (usedMeteorAccount) if (usedMeteorAccount) {
auth.maybePrintRegistrationLink(); auth.maybePrintRegistrationLink();
}
process.stdin.pause(); process.stdin.pause();
var runMongo = require('../runners/run-mongo.js'); var runMongo = require('../runners/run-mongo.js');
runMongo.runMongoShell(mongoUrl); runMongo.runMongoShell(mongoUrl);
@@ -1263,8 +1277,9 @@ main.registerCommand({
"To instantly deploy your app on a free testing server,", "To instantly deploy your app on a free testing server,",
"just enter your email address!"); "just enter your email address!");
Console.error(); Console.error();
if (! auth.registerOrLogIn()) if (! auth.registerOrLogIn()) {
return 1; return 1;
}
} }
// Override architecture iff applicable. // Override architecture iff applicable.
@@ -1375,12 +1390,13 @@ main.registerCommand({
return 1; return 1;
} }
if (options.add) if (options.add) {
return deploy.changeAuthorized(site, "add", options.add); return deploy.changeAuthorized(site, "add", options.add);
else if (options.remove) } else if (options.remove) {
return deploy.changeAuthorized(site, "remove", options.remove); return deploy.changeAuthorized(site, "remove", options.remove);
else } else {
return deploy.listAuthorized(site); return deploy.listAuthorized(site);
}
}); });
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
@@ -1499,8 +1515,9 @@ main.registerCommand({
// Download packages for our architecture, and for the deploy server's // Download packages for our architecture, and for the deploy server's
// architecture if we're deploying. // architecture if we're deploying.
var serverArchitectures = [archinfo.host()]; var serverArchitectures = [archinfo.host()];
if (options.deploy && DEPLOY_ARCH !== archinfo.host()) if (options.deploy && DEPLOY_ARCH !== archinfo.host()) {
serverArchitectures.push(DEPLOY_ARCH); serverArchitectures.push(DEPLOY_ARCH);
}
// XXX Because every run uses a new app with its own IsopackCache directory, // 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 // this always does a clean build of all packages. Maybe we can speed up
@@ -1940,8 +1957,9 @@ main.registerCommand({
try { try {
require('../utils/http-helpers.js').getUrl("http://www.google.com/"); require('../utils/http-helpers.js').getUrl("http://www.google.com/");
} catch (e) { } catch (e) {
if (e instanceof files.OfflineError) if (e instanceof files.OfflineError) {
offline = true; offline = true;
}
} }
} }
@@ -1949,8 +1967,9 @@ main.registerCommand({
try { try {
return new RegExp(str); return new RegExp(str);
} catch (e) { } catch (e) {
if (!(e instanceof SyntaxError)) if (!(e instanceof SyntaxError)) {
throw e; throw e;
}
Console.error("Bad regular expression: " + str); Console.error("Bad regular expression: " + str);
return null; return null;
} }
@@ -2250,17 +2269,20 @@ main.registerCommand({
catalogRefresh: new catalog.Refresh.Never() catalogRefresh: new catalog.Refresh.Never()
}, function (options) { }, function (options) {
var p = function (key) { var p = function (key) {
if (_.has(options, key)) if (_.has(options, key)) {
return JSON.stringify(options[key]); return JSON.stringify(options[key]);
}
return 'none'; return 'none';
}; };
Console.info(p('ething') + " " + p('port') + " " + p('changed') + Console.info(p('ething') + " " + p('port') + " " + p('changed') +
" " + p('args')); " " + p('args'));
if (options.url) if (options.url) {
Console.info('url'); Console.info('url');
if (options['delete']) }
if (options['delete']) {
Console.info('delete'); Console.info('delete');
}
}); });
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////

View File

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

View File

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

View File

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

View File

@@ -76,11 +76,15 @@ yet supported.`);
const outdated = _.some(minPlatformVersions, (minVersion, platform) => { const outdated = _.some(minPlatformVersions, (minVersion, platform) => {
// If the platform is not installed, it cannot be outdated // 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); const installedVersion = this.installedVersionForPlatform(platform);
// If we cannot establish the installed version, we consider it outdated // If we cannot establish the installed version, we consider it outdated
if (!installedVersion) return true; if (!installedVersion) {
return true;
}
return semver.lt(installedVersion, minVersion); return semver.lt(installedVersion, minVersion);
}); });
@@ -116,7 +120,9 @@ outdated platforms`);
builder.processControlFile(); builder.processControlFile();
if (buildmessage.jobHasMessages()) return; if (buildmessage.jobHasMessages()) {
return;
}
// Don't copy resources (they will be copied as part of the prepare) // Don't copy resources (they will be copied as part of the prepare)
builder.writeConfigXmlAndCopyResources(false); builder.writeConfigXmlAndCopyResources(false);
@@ -153,7 +159,9 @@ outdated platforms`);
builder.processControlFile(); builder.processControlFile();
if (buildmessage.jobHasMessages()) return; if (buildmessage.jobHasMessages()) {
return;
}
builder.writeConfigXmlAndCopyResources(); builder.writeConfigXmlAndCopyResources();
builder.copyWWW(bundlePath); builder.copyWWW(bundlePath);
@@ -345,7 +353,9 @@ from Cordova project`, async () => {
const installedPlatforms = this.listInstalledPlatforms(); const installedPlatforms = this.listInstalledPlatforms();
for (platform of platforms) { for (platform of platforms) {
if (_.contains(installedPlatforms, platform)) continue; if (_.contains(installedPlatforms, platform)) {
continue;
}
this.addPlatform(platform); this.addPlatform(platform);
} }
@@ -461,7 +471,9 @@ to Cordova project`, async () => {
// plugins is an array of plugin IDs. // plugins is an array of plugin IDs.
removePlugins(plugins) { removePlugins(plugins) {
if (_.isEmpty(plugins)) return; if (_.isEmpty(plugins)) {
return;
}
this.runCommands(`removing plugins ${plugins} \ this.runCommands(`removing plugins ${plugins} \
from Cordova project`, async () => { from Cordova project`, async () => {
@@ -487,7 +499,9 @@ from Cordova project`, async () => {
// SHA reference. // SHA reference.
pluginVersions = convertPluginVersions(pluginVersions); pluginVersions = convertPluginVersions(pluginVersions);
if (buildmessage.jobHasMessages()) return; if (buildmessage.jobHasMessages()) {
return;
}
// Also, we warn if any App.configurePlugin calls in mobile-config.js // 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 // 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) { function logFromAndroidLogcatLine(Log, line) {
// Ignore lines indicating beginning of logging // Ignore lines indicating beginning of logging
if (line.match(/^--------- beginning of /)) return null; if (line.match(/^--------- beginning of /)) {
return null;
}
// Matches logcat brief format // Matches logcat brief format
// "I/Tag( PID): message" // "I/Tag( PID): message"
@@ -209,7 +211,9 @@ function logFromAndroidLogcatLine(Log, line) {
}; };
function logFromConsoleOutput(Log, message, filename, lineNumber) { function logFromConsoleOutput(Log, message, filename, lineNumber) {
if (isDebugOutput(message) && !Console.verbose) return null; if (isDebugOutput(message) && !Console.verbose) {
return null;
}
filename = filename.replace(/\?.*$/, ''); filename = filename.replace(/\?.*$/, '');

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -106,8 +106,9 @@ export class CompilerPluginProcessor {
_.each(sourceBatch.resourceSlots, function (resourceSlot) { _.each(sourceBatch.resourceSlots, function (resourceSlot) {
var sourceProcessor = resourceSlot.sourceProcessor; var sourceProcessor = resourceSlot.sourceProcessor;
// Skip non-sources. // Skip non-sources.
if (! sourceProcessor) if (! sourceProcessor) {
return; return;
}
if (! _.has(sourceProcessorsWithSlots, sourceProcessor.id)) { if (! _.has(sourceProcessorsWithSlots, sourceProcessor.id)) {
sourceProcessorsWithSlots[sourceProcessor.id] = { sourceProcessorsWithSlots[sourceProcessor.id] = {
@@ -352,8 +353,9 @@ class ResourceSlot {
addStylesheet(options) { addStylesheet(options) {
const self = this; const self = this;
if (! self.sourceProcessor) if (! self.sourceProcessor) {
throw Error("addStylesheet on non-source ResourceSlot?"); throw Error("addStylesheet on non-source ResourceSlot?");
}
self.outputResources.push({ self.outputResources.push({
type: "css", type: "css",
@@ -370,8 +372,9 @@ class ResourceSlot {
addJavaScript(options) { addJavaScript(options) {
const self = this; const self = this;
// #HardcodeJs this gets called by constructor in the "js" case // #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?"); throw Error("addJavaScript on non-source ResourceSlot?");
}
// By default, use the 'bare' option given to addFiles, but allow the option // By default, use the 'bare' option given to addFiles, but allow the option
// passed to addJavaScript to override it. // passed to addJavaScript to override it.
@@ -399,8 +402,9 @@ class ResourceSlot {
addAsset(options) { addAsset(options) {
const self = this; const self = this;
if (! self.sourceProcessor) if (! self.sourceProcessor) {
throw Error("addAsset on non-source ResourceSlot?"); throw Error("addAsset on non-source ResourceSlot?");
}
if (! (options.data instanceof Buffer)) { if (! (options.data instanceof Buffer)) {
if (_.isString(options.data)) { if (_.isString(options.data)) {
@@ -424,13 +428,16 @@ class ResourceSlot {
const self = this; const self = this;
const unibuild = self.packageSourceBatch.unibuild; 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 " + throw new Error("Document sections can only be emitted to " +
"web targets"); "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'"); 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"); throw new Error("'data' option to appendDocument must be a string");
}
self.outputResources.push({ self.outputResources.push({
type: options.section, type: options.section,
@@ -625,8 +632,9 @@ class PackageSourceBatch {
diskCached = files.readJSONOrNull(cacheFilename); diskCached = files.readJSONOrNull(cacheFilename);
} catch (e) { } catch (e) {
// Ignore JSON parse errors; pretend there was no cache. // Ignore JSON parse errors; pretend there was no cache.
if (!(e instanceof SyntaxError)) if (!(e instanceof SyntaxError)) {
throw e; throw e;
}
} }
if (diskCached && diskCached instanceof Array) { if (diskCached && diskCached instanceof Array) {
// Fix the non-JSON part of our return value. // 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. // and have the runner restart.
pluginWatchSet.merge(buildResult.watchSet); pluginWatchSet.merge(buildResult.watchSet);
if (buildmessage.jobHasMessages()) if (buildmessage.jobHasMessages()) {
return; return;
}
_.each(buildResult.usedPackageNames, function (packageName) { _.each(buildResult.usedPackageNames, function (packageName) {
pluginProviderPackageNames[packageName] = true; pluginProviderPackageNames[packageName] = true;
}); });
// Register the built plugin's code. // Register the built plugin's code.
if (!_.has(plugins, info.name)) if (!_.has(plugins, info.name)) {
plugins[info.name] = {}; plugins[info.name] = {};
}
plugins[info.name][buildResult.image.arch] = buildResult.image; plugins[info.name][buildResult.image.arch] = buildResult.image;
}); });
}); });
@@ -169,8 +171,9 @@ compiler.compile = Profile(function (packageSource, options) {
}); });
_.each(packageSource.architectures, function (architecture) { _.each(packageSource.architectures, function (architecture) {
if (architecture.arch === 'web.cordova' && ! includeCordovaUnibuild) if (architecture.arch === 'web.cordova' && ! includeCordovaUnibuild) {
return; return;
}
var unibuildResult = compileUnibuild({ var unibuildResult = compileUnibuild({
isopack: isopk, isopack: isopk,
@@ -664,8 +667,9 @@ function runLinters({inputSourceArch, isopackCache, sources,
// version when we're bundling for Linux. // version when we're bundling for Linux.
allowWrongPlatform: true, allowWrongPlatform: true,
}, (unibuild) => { }, (unibuild) => {
if (unibuild.pkg.name === inputSourceArch.pkg.name) if (unibuild.pkg.name === inputSourceArch.pkg.name) {
return; return;
}
_.each(unibuild.declaredExports, (symbol) => { _.each(unibuild.declaredExports, (symbol) => {
if (! symbol.testOnly || inputSourceArch.isTest) { if (! symbol.testOnly || inputSourceArch.isTest) {
globalImports.push(symbol.name); 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 // 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. // another arch), skip without even reading the file into a WatchSet.
if (classification.type === 'wrong-arch' || if (classification.type === 'wrong-arch' ||
classification.type === 'unmatched') classification.type === 'unmatched') {
return; return;
}
// We shouldn't ever add a legacy handler and we're not hardcoding JS for // 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. // linters, so we should always have SourceProcessor if anything matches.
if (! classification.sourceProcessors) { if (! classification.sourceProcessors) {
@@ -723,12 +728,15 @@ function runLinters({inputSourceArch, isopackCache, sources,
const linter = sourceProcessor.userPlugin.processFilesForPackage; const linter = sourceProcessor.userPlugin.processFilesForPackage;
function archToString(arch) { function archToString(arch) {
if (arch.match(/web\.cordova/)) if (arch.match(/web\.cordova/)) {
return "Cordova"; return "Cordova";
if (arch.match(/web\..*/)) }
if (arch.match(/web\..*/)) {
return "Client"; return "Client";
if (arch.match(/os.*/)) }
if (arch.match(/os.*/)) {
return "Server"; return "Server";
}
throw new Error("Don't know how to display the arch: " + arch); 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 // the implies field is on the target unibuild, but we really only care
// about packages.) // about packages.)
var activePluginPackages = [isopk]; var activePluginPackages = [isopk];
if (pluginProviderPackageNames) if (pluginProviderPackageNames) {
pluginProviderPackageNames[isopk.name] = true; pluginProviderPackageNames[isopk.name] = true;
}
// We don't use plugins from weak dependencies, because the ability // We don't use plugins from weak dependencies, because the ability
// to compile a certain type of file shouldn't depend on whether or // to compile a certain type of file shouldn't depend on whether or
@@ -790,16 +799,18 @@ export function getActivePluginPackages(isopk, {
skipUnordered: true skipUnordered: true
// implicitly skip weak deps by not specifying acceptableWeakPackages option // implicitly skip weak deps by not specifying acceptableWeakPackages option
}, function (unibuild) { }, function (unibuild) {
if (unibuild.pkg.name === isopk.name) if (unibuild.pkg.name === isopk.name) {
return; return;
}
if (pluginProviderPackageNames) { if (pluginProviderPackageNames) {
pluginProviderPackageNames[unibuild.pkg.name] = true; pluginProviderPackageNames[unibuild.pkg.name] = true;
} }
if (pluginProviderWatchSet) { if (pluginProviderWatchSet) {
pluginProviderWatchSet.merge(unibuild.pkg.pluginWatchSet); pluginProviderWatchSet.merge(unibuild.pkg.pluginWatchSet);
} }
if (_.isEmpty(unibuild.pkg.plugins)) if (_.isEmpty(unibuild.pkg.plugins)) {
return; return;
}
activePluginPackages.push(unibuild.pkg); activePluginPackages.push(unibuild.pkg);
}); });
@@ -825,10 +836,12 @@ compiler.eachUsedUnibuild = function (
var processedUnibuildId = {}; var processedUnibuildId = {};
var usesToProcess = []; var usesToProcess = [];
_.each(dependencies, function (use) { _.each(dependencies, function (use) {
if (options.skipUnordered && use.unordered) if (options.skipUnordered && use.unordered) {
return; return;
if (use.weak && !_.has(acceptableWeakPackages, use.package)) }
if (use.weak && !_.has(acceptableWeakPackages, use.package)) {
return; return;
}
usesToProcess.push(use); usesToProcess.push(use);
}); });
@@ -836,18 +849,21 @@ compiler.eachUsedUnibuild = function (
var use = usesToProcess.shift(); var use = usesToProcess.shift();
// We only care about real packages, not isobuild:* psuedo-packages. // We only care about real packages, not isobuild:* psuedo-packages.
if (isIsobuildFeaturePackage(use.package)) if (isIsobuildFeaturePackage(use.package)) {
continue; continue;
}
var usedPackage = isopackCache.getIsopack(use.package); var usedPackage = isopackCache.getIsopack(use.package);
// Ignore this package if we were told to skip debug-only packages and it is // Ignore this package if we were told to skip debug-only packages and it is
// debug-only. // debug-only.
if (usedPackage.debugOnly && options.skipDebugOnly) if (usedPackage.debugOnly && options.skipDebugOnly) {
continue; continue;
}
// Ditto prodOnly. // Ditto prodOnly.
if (usedPackage.prodOnly && options.skipProdOnly) if (usedPackage.prodOnly && options.skipProdOnly) {
continue; continue;
}
var unibuild = usedPackage.getUnibuildAtArch(arch, {allowWrongPlatform}); var unibuild = usedPackage.getUnibuildAtArch(arch, {allowWrongPlatform});
if (!unibuild) { if (!unibuild) {
@@ -856,8 +872,9 @@ compiler.eachUsedUnibuild = function (
continue; continue;
} }
if (_.has(processedUnibuildId, unibuild.id)) if (_.has(processedUnibuildId, unibuild.id)) {
continue; continue;
}
processedUnibuildId[unibuild.id] = true; processedUnibuildId[unibuild.id] = true;
callback(unibuild, { callback(unibuild, {

View File

@@ -60,8 +60,9 @@ _.extend(exports.IsopackCache.prototype, {
var self = this; var self = this;
buildmessage.assertInCapture(); buildmessage.assertInCapture();
if (self.cacheDir) if (self.cacheDir) {
files.mkdir_p(self.cacheDir); files.mkdir_p(self.cacheDir);
}
var onStack = {}; var onStack = {};
if (rootPackageNames) { if (rootPackageNames) {
@@ -104,8 +105,9 @@ _.extend(exports.IsopackCache.prototype, {
// package whose dependencies have all already been built. // package whose dependencies have all already been built.
getIsopack: function (name) { getIsopack: function (name) {
var self = this; var self = this;
if (! _.has(self._isopacks, name)) if (! _.has(self._isopacks, name)) {
throw Error("isopack " + name + " not yet loaded?"); throw Error("isopack " + name + " not yet loaded?");
}
return self._isopacks[name]; return self._isopacks[name];
}, },
@@ -119,8 +121,9 @@ _.extend(exports.IsopackCache.prototype, {
_ensurePackageLoaded: function (name, onStack) { _ensurePackageLoaded: function (name, onStack) {
var self = this; var self = this;
buildmessage.assertInCapture(); buildmessage.assertInCapture();
if (_.has(self._isopacks, name)) if (_.has(self._isopacks, name)) {
return; return;
}
var ensureLoaded = function (depName) { var ensureLoaded = function (depName) {
if (_.has(onStack, depName)) { if (_.has(onStack, depName)) {
@@ -135,8 +138,9 @@ _.extend(exports.IsopackCache.prototype, {
}; };
var packageInfo = self._packageMap.getInfo(name); var packageInfo = self._packageMap.getInfo(name);
if (! packageInfo) if (! packageInfo) {
throw Error("Depend on unknown package " + name + "?"); throw Error("Depend on unknown package " + name + "?");
}
var previousIsopack = null; var previousIsopack = null;
if (self._previousIsopackCache && if (self._previousIsopackCache &&
_.has(self._previousIsopackCache._isopacks, name)) { _.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 // If we failed to load something that this package depends on, don't
// load it. // load it.
if (buildmessage.jobHasMessages()) if (buildmessage.jobHasMessages()) {
return; return;
}
self._loadLocalPackage(name, packageInfo, previousIsopack); self._loadLocalPackage(name, packageInfo, previousIsopack);
}); });
} else if (packageInfo.kind === 'versioned') { } 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 // 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 // packages to load, but we should still recover by putting it in
// self._isopacks. // self._isopacks.
if (buildmessage.jobHasMessages()) if (buildmessage.jobHasMessages()) {
return; return;
}
packagesToLoad = isopack.getStrongOrderedUsedAndImpliedPackages(); packagesToLoad = isopack.getStrongOrderedUsedAndImpliedPackages();
}); });
} }
@@ -322,8 +328,9 @@ _.extend(exports.IsopackCache.prototype, {
var self = this; var self = this;
// If there isn't an isopack-buildinfo.json file, then we definitely aren't // If there isn't an isopack-buildinfo.json file, then we definitely aren't
// up to date! // up to date!
if (! isopackBuildInfoJson) if (! isopackBuildInfoJson) {
return false; return false;
}
// If we include Cordova but this Isopack doesn't, or via versa, then we're // If we include Cordova but this Isopack doesn't, or via versa, then we're
// not up to date. // not up to date.
@@ -414,10 +421,12 @@ _.extend(exports.IsopackCache.prototype, {
}, },
_shouldLintPackage(packageSource) { _shouldLintPackage(packageSource) {
if (this._lintLocalPackages) if (this._lintLocalPackages) {
return true; return true;
if (! this._lintPackageWithSourceRoot) }
if (! this._lintPackageWithSourceRoot) {
return false; return false;
}
return this._lintPackageWithSourceRoot === packageSource.sourceRoot; 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 Profile = require('../tool-env/profile.js').Profile;
var rejectBadPath = function (p) { var rejectBadPath = function (p) {
if (p.match(/\.\./)) if (p.match(/\.\./)) {
throw new Error("bad path: " + p); throw new Error("bad path: " + p);
}
}; };
/////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////
@@ -239,10 +240,12 @@ Isopack.convertIsopackFormat = Profile(
var toPos = _.indexOf(Isopack.knownFormats, toFormat); var toPos = _.indexOf(Isopack.knownFormats, toFormat);
var step = fromPos < toPos ? 1 : -1; var step = fromPos < toPos ? 1 : -1;
if (fromPos === -1) if (fromPos === -1) {
throw new Error("Can't convert from unknown Isopack format: " + fromFormat); 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); throw new Error("Can't convert to unknown Isopack format: " + toFormat);
}
while (fromPos !== toPos) { while (fromPos !== toPos) {
if (step > 0) { if (step > 0) {
@@ -361,8 +364,9 @@ _.extend(Isopack.prototype, {
anySourceFiles = true; anySourceFiles = true;
var relativePath = files.pathRelative(sourceRoot, filename); var relativePath = files.pathRelative(sourceRoot, filename);
// We only want files that are actually under sourceRoot. // We only want files that are actually under sourceRoot.
if (relativePath.substr(0, 3) === '..' + files.pathSep) if (relativePath.substr(0, 3) === '..' + files.pathSep) {
return; return;
}
sourceFiles[relativePath] = true; sourceFiles[relativePath] = true;
}); });
}; };
@@ -374,8 +378,9 @@ _.extend(Isopack.prototype, {
// Were we actually built from source or loaded from an IsopackCache? If so // 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, // then there should be at least one source file in some WatchSet. If not,
// return null. // return null.
if (! anySourceFiles) if (! anySourceFiles) {
return null; return null;
}
return _.keys(sourceFiles); return _.keys(sourceFiles);
}), }),
@@ -467,8 +472,9 @@ _.extend(Isopack.prototype, {
_checkPluginsInitialized: function () { _checkPluginsInitialized: function () {
var self = this; var self = this;
if (self._pluginsInitialized) if (self._pluginsInitialized) {
return; return;
}
throw Error("plugins not yet initialized?"); throw Error("plugins not yet initialized?");
}, },
@@ -479,8 +485,9 @@ _.extend(Isopack.prototype, {
buildmessage.assertInJob(); buildmessage.assertInJob();
if (self._pluginsInitialized) if (self._pluginsInitialized) {
return; return;
}
self.sourceProcessors.compiler = new buildPluginModule.SourceProcessorSet( self.sourceProcessors.compiler = new buildPluginModule.SourceProcessorSet(
self.displayName(), { hardcodeJs: true, singlePackage: true }); self.displayName(), { hardcodeJs: true, singlePackage: true });
@@ -892,8 +899,9 @@ _.extend(Isopack.prototype, {
// PackageMap which can be subset to create a new PackageMap object.) // PackageMap which can be subset to create a new PackageMap object.)
var unibuildWatchSets = {}; var unibuildWatchSets = {};
if (options.isopackBuildInfoJson) { if (options.isopackBuildInfoJson) {
if (! options.firstIsopack) if (! options.firstIsopack) {
throw Error("can't merge isopacks with buildinfo"); throw Error("can't merge isopacks with buildinfo");
}
// XXX should comprehensively sanitize (eg, typecheck) everything // XXX should comprehensively sanitize (eg, typecheck) everything
// read from json files // read from json files
@@ -948,8 +956,9 @@ _.extend(Isopack.prototype, {
var alreadyHaveUnibuild = _.find(self.unibuilds, function (unibuild) { var alreadyHaveUnibuild = _.find(self.unibuilds, function (unibuild) {
return unibuild.arch === unibuildMeta.arch; return unibuild.arch === unibuildMeta.arch;
}); });
if (alreadyHaveUnibuild) if (alreadyHaveUnibuild) {
return; return;
}
var unibuildJson = JSON.parse( var unibuildJson = JSON.parse(
files.readFile(files.pathJoin(dir, unibuildMeta.path))); files.readFile(files.pathJoin(dir, unibuildMeta.path)));
@@ -1038,9 +1047,10 @@ _.extend(Isopack.prototype, {
servePath: resource.servePath || undefined, servePath: resource.servePath || undefined,
path: resource.path || undefined path: resource.path || undefined
}); });
} else } else {
throw new Error("bad resource type in isopack: " + throw new Error("bad resource type in isopack: " +
JSON.stringify(resource.type)); JSON.stringify(resource.type));
}
}); });
var declaredExports; var declaredExports;
@@ -1296,8 +1306,9 @@ _.extend(Isopack.prototype, {
concat[resource.type].push(new Buffer("\n", "utf8")); concat[resource.type].push(new Buffer("\n", "utf8"));
offset[resource.type]++; offset[resource.type]++;
} }
if (! (resource.data instanceof Buffer)) if (! (resource.data instanceof Buffer)) {
throw new Error("Resource data must be a Buffer"); throw new Error("Resource data must be a Buffer");
}
unibuildJson.resources.push({ unibuildJson.resources.push({
type: resource.type, type: resource.type,
file: files.pathJoin(unibuildDir, resource.type), file: files.pathJoin(unibuildDir, resource.type),
@@ -1318,8 +1329,10 @@ _.extend(Isopack.prototype, {
// Output other resources each to their own file // Output other resources each to their own file
_.each(unibuild.resources, function (resource) { _.each(unibuild.resources, function (resource) {
if (_.contains(["head", "body"], resource.type)) if (_.contains(["head", "body"], resource.type)) {
return; // already did this one // already did this one
return;
}
// If we're going to write a legacy prelink file later, track the // 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, // original form of the resource object (with the source in a Buffer,
@@ -1481,8 +1494,9 @@ _.extend(Isopack.prototype, {
packageVariables = []; packageVariables = [];
var packageVariableNames = {}; var packageVariableNames = {};
_.each(unibuild.declaredExports, function (symbol) { _.each(unibuild.declaredExports, function (symbol) {
if (_.has(packageVariableNames, symbol.name)) if (_.has(packageVariableNames, symbol.name)) {
return; return;
}
packageVariables.push({ packageVariables.push({
name: symbol.name, name: symbol.name,
export: symbol.testOnly? "tests" : true export: symbol.testOnly? "tests" : true
@@ -1512,8 +1526,9 @@ _.extend(Isopack.prototype, {
prelinkData = new Buffer(prelinkFile.source, 'utf8'); prelinkData = new Buffer(prelinkFile.source, 'utf8');
_.each(results.assignedVariables, function (name) { _.each(results.assignedVariables, function (name) {
if (_.has(packageVariableNames, name)) if (_.has(packageVariableNames, name)) {
return; return;
}
packageVariables.push({ packageVariables.push({
name: name name: name
}); });
@@ -1724,8 +1739,9 @@ _.extend(Isopack.prototype, {
title: "compiling " + isopacketName + " packages for the tool" title: "compiling " + isopacketName + " packages for the tool"
}, function () { }, function () {
isopacketBuildContext.isopackCache.buildLocalPackages(packages); isopacketBuildContext.isopackCache.buildLocalPackages(packages);
if (buildmessage.jobHasMessages()) if (buildmessage.jobHasMessages()) {
return; return;
}
var image = bundler.buildJsImage({ var image = bundler.buildJsImage({
name: "isopacket-" + isopacketName, name: "isopacket-" + isopacketName,
@@ -1733,8 +1749,9 @@ _.extend(Isopack.prototype, {
isopackCache: isopacketBuildContext.isopackCache, isopackCache: isopacketBuildContext.isopackCache,
use: packages use: packages
}).image; }).image;
if (buildmessage.jobHasMessages()) if (buildmessage.jobHasMessages()) {
return; return;
}
image.write( image.write(
builder.enter(files.pathJoin('isopackets', isopacketName))); builder.enter(files.pathJoin('isopackets', isopacketName)));
@@ -1798,8 +1815,9 @@ _.extend(Isopack.prototype, {
var self = this; var self = this;
var packages = {}; var packages = {};
var processUse = function (use) { var processUse = function (use) {
if (use.weak || use.unordered) if (use.weak || use.unordered) {
return; return;
}
// Only include real packages, not isobuild:* pseudo-packages. // Only include real packages, not isobuild:* pseudo-packages.
if (compiler.isIsobuildFeaturePackage(use.package)) { if (compiler.isIsobuildFeaturePackage(use.package)) {
return; return;

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -41,15 +41,17 @@ _.extend(Release.prototype, {
getReleaseTrack: function () { getReleaseTrack: function () {
var self = this; var self = this;
if (! self.isProperRelease()) if (! self.isProperRelease()) {
throw new Error("not a proper release?"); throw new Error("not a proper release?");
}
return self.name.split('@')[0]; return self.name.split('@')[0];
}, },
getReleaseVersion: function () { getReleaseVersion: function () {
var self = this; var self = this;
if (! self.isProperRelease()) if (! self.isProperRelease()) {
throw new Error("not a proper release?"); throw new Error("not a proper release?");
}
return self.name.split('@')[1]; return self.name.split('@')[1];
}, },
@@ -58,8 +60,9 @@ _.extend(Release.prototype, {
getToolsPackage: function () { getToolsPackage: function () {
var self = this; var self = this;
if (! self.isProperRelease()) if (! self.isProperRelease()) {
throw new Error("not a proper release?"); throw new Error("not a proper release?");
}
// XXX validate // XXX validate
return self._manifest.tool.split('@')[0]; return self._manifest.tool.split('@')[0];
}, },
@@ -69,8 +72,9 @@ _.extend(Release.prototype, {
getToolsVersion: function () { getToolsVersion: function () {
var self = this; var self = this;
if (! self.isProperRelease()) if (! self.isProperRelease()) {
throw new Error("not a proper release?"); throw new Error("not a proper release?");
}
// XXX validate // XXX validate
return self._manifest.tool.split('@')[1]; return self._manifest.tool.split('@')[1];
}, },
@@ -80,8 +84,9 @@ _.extend(Release.prototype, {
getToolsPackageAtVersion: function () { getToolsPackageAtVersion: function () {
var self = this; var self = this;
if (! self.isProperRelease()) if (! self.isProperRelease()) {
throw new Error("not a proper release?"); throw new Error("not a proper release?");
}
return self._manifest.tool; return self._manifest.tool;
}, },
@@ -104,23 +109,26 @@ _.extend(Release.prototype, {
getUpgraders: function () { getUpgraders: function () {
var self = this; var self = this;
if (! self.isProperRelease()) if (! self.isProperRelease()) {
throw new Error("not a proper release?"); throw new Error("not a proper release?");
}
return self._manifest.upgraders || []; return self._manifest.upgraders || [];
}, },
getPackages: function () { getPackages: function () {
var self = this; var self = this;
if (! self.isProperRelease()) if (! self.isProperRelease()) {
throw new Error("not a proper release?"); throw new Error("not a proper release?");
}
return self._manifest.packages; return self._manifest.packages;
}, },
getCatalogReleaseData: function () { getCatalogReleaseData: function () {
var self = this; var self = this;
if (! self.isProperRelease()) if (! self.isProperRelease()) {
throw new Error("not a proper release?"); throw new Error("not a proper release?");
}
return self._manifest; return self._manifest;
}, },
@@ -166,11 +174,13 @@ release.explicit = null;
// in the current project. (taking into account release.forced and whether we're // in the current project. (taking into account release.forced and whether we're
// currently running from a checkout). // currently running from a checkout).
release.usingRightReleaseForApp = function (projectContext) { release.usingRightReleaseForApp = function (projectContext) {
if (release.current === null) if (release.current === null) {
throw new Error("no release?"); throw new Error("no release?");
}
if (! files.usesWarehouse() || release.forced) if (! files.usesWarehouse() || release.forced) {
return true; return true;
}
return release.current.name === projectContext.releaseFile.fullReleaseName; 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. // for use. May not be called when running from a checkout.
// 'track' is optional (it defaults to the default track). // 'track' is optional (it defaults to the default track).
release.latestKnown = function (track) { release.latestKnown = function (track) {
if (! files.usesWarehouse()) if (! files.usesWarehouse()) {
throw new Error("called from checkout?"); throw new Error("called from checkout?");
}
// For self-test only. // 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; return process.env.METEOR_TEST_LATEST_RELEASE;
}
var defaultRelease = catalog.official.getDefaultReleaseVersion(track); var defaultRelease = catalog.official.getDefaultReleaseVersion(track);
@@ -253,8 +265,9 @@ release.load = function (name, options) {
// line (by the user or by the update springboard). // line (by the user or by the update springboard).
// - explicit: true if the release was specifically requested by the user. // - explicit: true if the release was specifically requested by the user.
release.setCurrent = function (releaseObject, forced, explicit) { release.setCurrent = function (releaseObject, forced, explicit) {
if (release.current) if (release.current) {
throw new Error("release set twice?"); throw new Error("release set twice?");
}
release.current = releaseObject; release.current = releaseObject;
release.forced = !! forced; 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. // we are running form a checkout, probably at $CHECKOUT_DIR/.meteor.
var defaultWarehouseDir = function () { var defaultWarehouseDir = function () {
// a hook for tests, or i guess for users. // 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; return process.env.METEOR_WAREHOUSE_DIR;
}
var warehouseBase = files.inCheckout() var warehouseBase = files.inCheckout()
? files.getCurrentToolsDir() : files.getHomeDir(); ? files.getCurrentToolsDir() : files.getHomeDir();
@@ -178,8 +179,9 @@ _.extend(exports.Tropohouse.prototype, {
escapedPackages = files.readdir(packageRootDir); escapedPackages = files.readdir(packageRootDir);
} catch (e) { } catch (e) {
// No packages at all? We're done. // No packages at all? We're done.
if (e.code === 'ENOENT') if (e.code === 'ENOENT') {
return; return;
}
throw e; throw e;
} }
@@ -233,14 +235,16 @@ _.extend(exports.Tropohouse.prototype, {
versions = files.readdir(packageDir); versions = files.readdir(packageDir);
} catch (e) { } catch (e) {
// Somebody put a file in here or something? Whatever, ignore. // 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; return;
}
throw e; throw e;
} }
_.each(versions, function (version) { _.each(versions, function (version) {
// Is this a pre-0.9.0 "warehouse" version with a hash name? // 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; return;
}
// Skip the currently-latest tool (ie, don't break top-level meteor // Skip the currently-latest tool (ie, don't break top-level meteor
// symlink). This includes both the symlink with its name and the thing // symlink). This includes both the symlink with its name and the thing
@@ -271,10 +275,12 @@ _.extend(exports.Tropohouse.prototype, {
// archinfo.host(). // archinfo.host().
installed: function (options) { installed: function (options) {
var self = this; var self = this;
if (!options.packageName) if (!options.packageName) {
throw Error("Missing required argument: packageName"); throw Error("Missing required argument: packageName");
if (!options.version) }
if (!options.version) {
throw Error("Missing required argument: version"); throw Error("Missing required argument: version");
}
var architectures = options.architectures || [archinfo.host()]; var architectures = options.architectures || [archinfo.host()];
var downloaded = self._alreadyDownloaded({ var downloaded = self._alreadyDownloaded({
@@ -317,10 +323,12 @@ _.extend(exports.Tropohouse.prototype, {
var self = this; var self = this;
var packageName = options.packageName; var packageName = options.packageName;
var version = options.version; var version = options.version;
if (!options.packageName) if (!options.packageName) {
throw Error("Missing required argument: packageName"); throw Error("Missing required argument: packageName");
if (!options.version) }
if (!options.version) {
throw Error("Missing required argument: version"); throw Error("Missing required argument: version");
}
// Figure out what arches (if any) we have loaded for this package 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; var self = this;
buildmessage.assertInJob(); buildmessage.assertInJob();
if (!options.packageName) if (!options.packageName) {
throw Error("Missing required argument: packageName"); throw Error("Missing required argument: packageName");
if (!options.version) }
if (!options.version) {
throw Error("Missing required argument: version"); throw Error("Missing required argument: version");
if (!options.architectures) }
if (!options.architectures) {
throw Error("Missing required argument: architectures"); throw Error("Missing required argument: architectures");
}
var packageName = options.packageName; var packageName = options.packageName;
var version = options.version; var version = options.version;
@@ -460,8 +471,9 @@ _.extend(exports.Tropohouse.prototype, {
// (ie, this is a warehouse package not a tropohouse package). But // (ie, this is a warehouse package not a tropohouse package). But
// the versions should not overlap: warehouse versions are truncated // the versions should not overlap: warehouse versions are truncated
// SHAs whereas tropohouse versions should be semver-like. // SHAs whereas tropohouse versions should be semver-like.
if (e.code !== 'ENOENT') if (e.code !== 'ENOENT') {
throw e; throw e;
}
} }
// If there's already a package in the tropohouse, start with it. // If there's already a package in the tropohouse, start with it.
@@ -483,16 +495,18 @@ _.extend(exports.Tropohouse.prototype, {
var buildTempDir = self._downloadBuildToTempDir( var buildTempDir = self._downloadBuildToTempDir(
{ packageName: packageName, version: version }, build); { packageName: packageName, version: version }, build);
} catch (e) { } catch (e) {
if (!(e instanceof files.OfflineError)) if (!(e instanceof files.OfflineError)) {
throw e; throw e;
}
buildmessage.error(e.error.message); buildmessage.error(e.error.message);
} }
buildInputDirs.push(buildTempDir); buildInputDirs.push(buildTempDir);
buildTempDirs.push(buildTempDir); buildTempDirs.push(buildTempDir);
}); });
}); });
if (buildmessage.jobHasMessages()) if (buildmessage.jobHasMessages()) {
return; return;
}
// We need to turn our builds into a single isopack. // We need to turn our builds into a single isopack.
var isopack = new Isopack(); var isopack = new Isopack();
@@ -538,8 +552,9 @@ _.extend(exports.Tropohouse.prototype, {
var downloader; var downloader;
var downloaders = []; var downloaders = [];
packageMap.eachPackage(function (packageName, info) { packageMap.eachPackage(function (packageName, info) {
if (info.kind !== 'versioned') if (info.kind !== 'versioned') {
return; return;
}
buildmessage.enterJob( buildmessage.enterJob(
"checking for " + packageName + "@" + info.version, "checking for " + packageName + "@" + info.version,
function () { function () {
@@ -552,19 +567,22 @@ _.extend(exports.Tropohouse.prototype, {
downloaders = null; downloaders = null;
return; return;
} }
if (downloader && downloaders) if (downloader && downloaders) {
downloaders.push(downloader); downloaders.push(downloader);
}
} }
); );
}); });
// Did anything fail? Don't download anything. // Did anything fail? Don't download anything.
if (! downloaders) if (! downloaders) {
return; return;
}
// Nothing to download? Great. // Nothing to download? Great.
if (! downloaders.length) if (! downloaders.length) {
return; return;
}
// Just one package to download? Use a good message. // Just one package to download? Use a good message.
if (downloaders.length === 1) { 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 // Don't run more than one check simultaneously. It should be
// harmless but having two downloads happening simultaneously (and // harmless but having two downloads happening simultaneously (and
// two sets of messages being printed) would be confusing. // two sets of messages being printed) would be confusing.
if (checkInProgress) if (checkInProgress) {
return; return;
}
checkInProgress = true; checkInProgress = true;
checkForUpdate(!! options.showBanner, !! options.printErrors); checkForUpdate(!! options.showBanner, !! options.printErrors);
checkInProgress = false; checkInProgress = false;
@@ -56,8 +57,9 @@ var checkForUpdate = function (showBanner, printErrors) {
} }
} }
if (!release.current.isProperRelease()) if (!release.current.isProperRelease()) {
return; return;
}
updateMeteorToolSymlink(printErrors); updateMeteorToolSymlink(printErrors);
@@ -105,8 +107,9 @@ var maybeShowBanners = function () {
// We now consider printing some simpler banners, if this isn't the latest // 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 // 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*. // don't bother: we only want to tell users about ways to update *their app*.
if (release.forced) if (release.forced) {
return; return;
}
const catalogUtils = require('./catalog/catalog-utils.js'); const catalogUtils = require('./catalog/catalog-utils.js');
@@ -155,15 +158,18 @@ var updateMeteorToolSymlink = function (printErrors) {
// symlink to go to the default track.) // symlink to go to the default track.)
var latestReleaseVersion = catalog.official.getDefaultReleaseVersion(); var latestReleaseVersion = catalog.official.getDefaultReleaseVersion();
// Maybe you're on some random track with nothing recommended. That's OK. // Maybe you're on some random track with nothing recommended. That's OK.
if (!latestReleaseVersion) if (!latestReleaseVersion) {
return; return;
}
var latestRelease = catalog.official.getReleaseVersion( var latestRelease = catalog.official.getReleaseVersion(
latestReleaseVersion.track, latestReleaseVersion.version); latestReleaseVersion.track, latestReleaseVersion.version);
if (!latestRelease) if (!latestRelease) {
throw Error("latest release doesn't exist?"); throw Error("latest release doesn't exist?");
if (!latestRelease.tool) }
if (!latestRelease.tool) {
throw Error("latest release doesn't have a tool?"); throw Error("latest release doesn't have a tool?");
}
var latestReleaseToolParts = latestRelease.tool.split('@'); var latestReleaseToolParts = latestRelease.tool.split('@');
var latestReleaseToolPackage = latestReleaseToolParts[0]; var latestReleaseToolPackage = latestReleaseToolParts[0];
@@ -202,8 +208,9 @@ var updateMeteorToolSymlink = function (printErrors) {
// XXX maybe we shouldn't throw from this background thing // XXX maybe we shouldn't throw from this background thing
// counter: this is super weird and should never ever happen. // counter: this is super weird and should never ever happen.
if (!toolRecord) if (!toolRecord) {
throw Error("latest release has no tool?"); throw Error("latest release has no tool?");
}
tropohouse.default.linkToLatestMeteor(files.pathJoin( tropohouse.default.linkToLatestMeteor(files.pathJoin(
relativeToolPath, toolRecord.path, 'meteor')); relativeToolPath, toolRecord.path, 'meteor'));

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -54,7 +54,9 @@ var checkCordovaPlugins = selftest.markStack(function(sand, plugins) {
var i = 0; var i = 0;
_.each(cordovaPlugins, function(line) { _.each(cordovaPlugins, function(line) {
if (!line || line === '') return; if (!line || line === '') {
return;
}
// XXX should check for the version as well? // XXX should check for the version as well?
selftest.expectEqual(line.split(' ')[0], plugins[i]); selftest.expectEqual(line.split(' ')[0], plugins[i]);
i++; i++;
@@ -67,7 +69,9 @@ var checkCordovaPluginExists = selftest.markStack(function(sand, plugin) {
var cordovaPlugins = getCordovaPluginsList(sand); var cordovaPlugins = getCordovaPluginsList(sand);
var found = false; var found = false;
cordovaPlugins = cordovaPlugins.map(function (line) { cordovaPlugins = cordovaPlugins.map(function (line) {
if (line && line !== '') return line.split(' ')[0]; if (line && line !== '') {
return line.split(' ')[0];
}
}); });
selftest.expectTrue(_.contains(cordovaPlugins, plugin)); selftest.expectTrue(_.contains(cordovaPlugins, plugin));
}); });
@@ -88,7 +92,9 @@ var checkUserPlugins = function(sand, plugins) {
var lines = sand.read(".meteor/cordova-plugins").split("\n"); var lines = sand.read(".meteor/cordova-plugins").split("\n");
var depend = {}; var depend = {};
_.each(lines, function(line) { _.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 // plugins are stored of the form foo@1.0.0, so this should give us an
// array [foo, 1.0.0]. // array [foo, 1.0.0].
var split = line.split('@'); 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 // old tests don't get to test --release, and always run this release
var maybeFixRelease = function (env) { var maybeFixRelease = function (env) {
if (release.current && release.current.isProperRelease()) if (release.current && release.current.isProperRelease()) {
env.METEOR_SPRINGBOARD_RELEASE = release.current.name; env.METEOR_SPRINGBOARD_RELEASE = release.current.name;
}
return env; return env;
}; };

View File

@@ -45,7 +45,9 @@ var checkPackages = selftest.markStack(function(sand, packages) {
var lines = sand.read(".meteor/packages").split("\n"); var lines = sand.read(".meteor/packages").split("\n");
var i = 0; var i = 0;
_.each(lines, function(line) { _.each(lines, function(line) {
if (!line) return; if (!line) {
return;
}
// If the specified package contains an @ sign, then it has a version // If the specified package contains an @ sign, then it has a version
// number, so we should match everything. // number, so we should match everything.
if (packages[i].split('@').length > 1) { 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 lines = sand.read(".meteor/versions").split("\n");
var depend = {}; var depend = {};
_.each(lines, function(line) { _.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 // Packages are stored of the form foo@1.0.0, so this should give us an
// array [foo, 1.0.0]. // array [foo, 1.0.0].
var split = line.split('@'); var split = line.split('@');
@@ -141,13 +145,17 @@ _.extend(DataStub.prototype, {
getSortedVersions: function (p) { getSortedVersions: function (p) {
var self = this; var self = this;
var rec = self.packages[p]; var rec = self.packages[p];
if (!rec) return null; if (!rec) {
return null;
}
return rec.versions; return rec.versions;
}, },
getPackage: function (p) { getPackage: function (p) {
var self = this; var self = this;
var rec = self.packages[p]; var rec = self.packages[p];
if (!rec) return null; if (!rec) {
return null;
}
return rec.record; return rec.record;
}, },
getAllReleaseTracks: function () { getAllReleaseTracks: function () {
@@ -156,13 +164,17 @@ _.extend(DataStub.prototype, {
getSortedRecommendedReleaseVersions: function (t) { getSortedRecommendedReleaseVersions: function (t) {
var self = this; var self = this;
var rec = self.releases[t]; var rec = self.releases[t];
if (!rec) return null; if (!rec) {
return null;
}
return rec.versions; return rec.versions;
}, },
getReleaseVersion: function (t, v) { getReleaseVersion: function (t, v) {
var self = this; var self = this;
var rec = self.releases[t]; var rec = self.releases[t];
if (!rec) return null; if (!rec) {
return null;
}
return rec.records[v]; 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 lines = s.read(".meteor/versions").split("\n");
var depend = {}; var depend = {};
_.each(lines, function(line) { _.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 // Packages are stored of the form foo@1.0.0, so this should give us an
// array [foo, 1.0.0]. // array [foo, 1.0.0].
var split = line.split('@'); 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 () { selftest.define("download and springboard to pre-0.9.0 release", ['net', 'slow'], function () {
var s, run; var s, run;
if (files.inCheckout()) if (files.inCheckout()) {
s = new Sandbox({ warehouse: { v1: { tools: 'tools1', latest: true } } }); s = new Sandbox({ warehouse: { v1: { tools: 'tools1', latest: true } } });
else } else {
s = new Sandbox; s = new Sandbox;
}
// End-to-end, online test of downloading and springboarding. This // End-to-end, online test of downloading and springboarding. This
// release was built from the // 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 " + selftest.fail("Couldn't find app identifier in usage " +
"returned from package stats server"); "returned from package stats server");
}
return found; return found;
}; };

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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