Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

feat: pass argument to main function #5

Open
wants to merge 10 commits into
base: master
Choose a base branch
from
2 changes: 1 addition & 1 deletion .npmignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
node_modules/
assets/screenshot.png
assets/screenshot.png
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@
const path = require("path");
const fs = require("mz/fs");
const linter = require("addons-linter");
const withTmpDir = require("./helpers/tmp-dir");
const cmdRunner = require("./helpers/cmd-runner");
const withTmpDir = require("../helpers/tmp-dir");
const cmdRunner = require("../helpers/cmd-runner");

const execDirPath = path.join(__dirname, "..", "bin");
const execDirPath = path.join(__dirname, "..", "..", "bin");

describe("main", () => {
test("creates files including manifest with correct name", () => withTmpDir(
Expand Down
23 changes: 23 additions & 0 deletions __tests__/unit/errors.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
"use strict";

const UsageError = require("../../errors").UsageError;
const onlyInstancesOf = require("../../errors").onlyInstancesOf;

describe("onlyInstancesOf", () => {
test("catches specified error", () => {
return Promise.reject(new UsageError("fake usage error"))
.catch(onlyInstancesOf(UsageError, (error) => {
expect(error).toBeInstanceOf(UsageError);
}));
});

test("throws other errors", () => {
return Promise.reject(new Error("fake error"))
.catch(onlyInstancesOf(UsageError, () => {
throw new Error("Unexpectedly caught the wrong error");
}))
.catch((error) => {
expect(error.message).toMatch(/fake error/);
});
});
});
127 changes: 127 additions & 0 deletions __tests__/unit/index.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
"use strict";

const path = require("path");
const fs = require("mz/fs");
const withTmpDir = require("../helpers/tmp-dir");
const UsageError = require("../../errors").UsageError;
const main = require("../../index").main;
const getProjectCreatedMessage =
require("../../index").getProjectCreatedMessage;

describe("main", () => {
test("returns project path and creation message", () => withTmpDir(
async (tmpPath) => {
const projName = "target";
const targetDir = path.join(tmpPath, projName);
const dirname = path.join(__dirname, "..", "..");
const expectedMessage = await getProjectCreatedMessage(targetDir, dirname);

const result = await main({
dirPath: projName,
baseDir: tmpPath,
});
expect(result.projectPath).toEqual(targetDir);
expect(result.projectCreatedMessage).toEqual(expectedMessage);
})
);

test("creates files, readme and manifest with correct name", () => withTmpDir(
async (tmpPath) => {
const projName = "target";
const targetDir = path.join(tmpPath, projName);

await main({
dirPath: projName,
baseDir: tmpPath,
});

const contentStat = await fs.stat(path.join(targetDir, "content.js"));
expect(contentStat.isFile()).toBeTruthy();

const bgStat = await fs.stat(path.join(targetDir, "background.js"));
expect(bgStat.isFile()).toBeTruthy();

const rmStat = await fs.stat(path.join(targetDir, "README.md"));
expect(rmStat.isFile()).toBeTruthy();

const manifest = await fs.readFile(path.join(targetDir, "manifest.json"), "utf-8");
const parsed = JSON.parse(manifest);
expect(parsed.name).toEqual(projName);
})
);

test("calls all of its necessary dependencies", () => withTmpDir(
async (tmpPath) => {
const projName = "target";

jest.mock("../../dependencies-main");
const dependenciesMain = require("../../dependencies-main");

await main({
dirPath: projName,
baseDir: tmpPath,
dependencies: dependenciesMain,
});

expect(dependenciesMain.getProjectManifest.mock.calls.length).toBe(1);
expect(dependenciesMain.getProjectManifest.mock.calls[0][0]).toBe(projName);

expect(dependenciesMain.getPlaceholderIcon.mock.calls.length).toBe(1);

expect(dependenciesMain.getProjectReadme.mock.calls.length).toBe(1);
expect(dependenciesMain.getProjectReadme.mock.calls[0][0]).toBe(projName);
})
);

test("throws Usage Error when directory already exists", () => withTmpDir(
async (tmpPath) => {
const projName = "target";
const targetDir = path.join(tmpPath, projName);
await fs.mkdir(targetDir);

await expect(main({
dirPath: projName,
baseDir: tmpPath,
})).rejects
.toBeInstanceOf(UsageError);

await expect(main({
dirPath: projName,
baseDir: tmpPath,
})).rejects
.toMatchObject({
message: expect.stringMatching(/dir already exists/),
});
})
);

test("throws error when one of dependencies throws", () => withTmpDir(
async (tmpPath) => {
const projName = "target";

jest.mock("../../dependencies-main");
const dependenciesMain = require("../../dependencies-main");
dependenciesMain.getPlaceholderIcon = jest.fn(() => {
throw new Error("error");
});

await expect(main({
dirPath: projName,
baseDir: tmpPath,
dependencies: dependenciesMain,
})).rejects
.toMatchObject({
message: expect.stringMatching(/error/),
});
})
);
});

describe("getProjectCreatedMessage", () => {
test("returns message with correct directory", async () => {
const targetDir = path.join("target");
const returnedMessage = await getProjectCreatedMessage(targetDir);

expect(returnedMessage).toMatch(new RegExp(targetDir));
});
});
23 changes: 22 additions & 1 deletion bin/create-webextension
Original file line number Diff line number Diff line change
@@ -1,3 +1,24 @@
#!/usr/bin/env node
const chalk = require("chalk");
const UsageError = require("../errors").UsageError;
const onlyInstancesOf = require("../errors").onlyInstancesOf;

require("..").main();

const USAGE_MSG = `Usage: create-webextension project_dir_name`;

if (!process.argv[2]) {
console.error(`${chalk.red("Missing project dir name.")}\n`);
console.log(USAGE_MSG);
process.exit(1);
}

require("..").main({dirPath: process.argv[2]})
.then(({projectCreatedMessage}) => console.log(projectCreatedMessage))
.catch(onlyInstancesOf(UsageError, (error) => {
console.error(`${chalk.red(error.message)}\n`);
process.exit(1);
}))
.catch((error) => {
console.error(`${chalk.red(error.message)}: ${error.stack}\n`); // or something similar that prints both the message and the stack
process.exit(1);
});
49 changes: 49 additions & 0 deletions dependencies-main.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
const path = require("path");
const fs = require("mz/fs");

const README = `
This project contains a blank WebExtension addon, a "white canvas" for your new experiment of
extending and remixing the Web.
`;

exports.getProjectReadme = function getProjectReadme(
projectDirName,
MORE_INFO_MSG
) {
return fs.readFile(path.join(__dirname, "assets", "webextension-logo.ascii"))
.then(() => {
return `# ${projectDirName}\n${README}${MORE_INFO_MSG}`;
});
};

exports.getPlaceholderIcon = function getPlaceholderIcon() {
return fs.readFile(path.join(__dirname, "assets", "icon.png"));
};

exports.getProjectManifest = function getProjectManifest(projectDirName) {
return {
manifest_version: 2,
name: projectDirName,
version: "0.1",
description: `${projectDirName} description`,
content_scripts: [
{
matches: ["https://developer.mozilla.org/*"],
js: ["content.js"],
},
],
permissions: [],
icons: {
"64": "icon.png",
},
browser_action: {
default_title: `${projectDirName} (browserAction)`,
default_icon: {
"64": "icon.png",
},
},
background: {
scripts: ["background.js"],
},
};
};
12 changes: 12 additions & 0 deletions errors.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
const ES6Error = require("es6-error");

exports.onlyInstancesOf = function (errorType, handler) {
return (error) => {
if (error instanceof errorType) {
return handler(error);
}
throw error;
};
};

exports.UsageError = class UsageError extends ES6Error {};
91 changes: 23 additions & 68 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,8 @@ const path = require("path");
const chalk = require("chalk");
const fs = require("mz/fs");
const stripAnsi = require("strip-ansi");

const USAGE_MSG = `Usage: create-webextension project_dir_name`;

const README = `
This project contains a blank WebExtension addon, a "white canvas" for your new experiment of
extending and remixing the Web.
`;
const UsageError = require("./errors").UsageError;
const dependenciesMain = require("./dependencies-main");

const MORE_INFO_MSG = `

Expand All @@ -36,90 +31,50 @@ a WebExtension from the command line:
${chalk.bold.blue("web-ext run -s /path/to/extension")}
`;

function getProjectCreatedMessage(projectPath) {
return fs.readFile(path.join(__dirname, "assets", "webextension-logo.ascii"))
exports.getProjectCreatedMessage = function getProjectCreatedMessage(projectPath, dirname = __dirname) {
return fs.readFile(path.join(dirname, "assets", "webextension-logo.ascii"))
.then(asciiLogo => {
const PROJECT_CREATED_MSG = `\n
Congratulations!!! A new WebExtension has been created at:

${chalk.bold(chalk.green(projectPath))}`;

return `${asciiLogo} ${PROJECT_CREATED_MSG} ${MORE_INFO_MSG}`;
});
}

function getProjectReadme(projectDirName) {
return fs.readFile(path.join(__dirname, "assets", "webextension-logo.ascii"))
.then(() => {
return `# ${projectDirName}\n${README}${MORE_INFO_MSG}`;
});
}

function getPlaceholderIcon() {
return fs.readFile(path.join(__dirname, "assets", "icon.png"));
}

function getProjectManifest(projectDirName) {
return {
manifest_version: 2,
name: projectDirName,
version: "0.1",
description: `${projectDirName} description`,
content_scripts: [
{
matches: ["https://developer.mozilla.org/*"],
js: ["content.js"],
},
],
permissions: [],
icons: {
"64": "icon.png",
},
browser_action: {
default_title: `${projectDirName} (browserAction)`,
default_icon: {
"64": "icon.png",
},
},
background: {
scripts: ["background.js"],
},
};
}

exports.main = function main() {
if (!process.argv[2]) {
console.error(`${chalk.red("Missing project dir name.")}\n`);
console.log(USAGE_MSG);
process.exit(1);
};

exports.main = function main({
dirPath,
baseDir = process.cwd(),
dependencies = dependenciesMain,
}) {
if (!dirPath) {
throw new Error("Project directory name is a mandatory argument");
}

const projectPath = path.resolve(process.argv[2]);
const projectPath = path.resolve(baseDir, dirPath);
const projectDirName = path.basename(projectPath);

return fs.mkdir(projectPath).then(() => {
return Promise.all([
fs.writeFile(path.join(projectPath, "manifest.json"),
JSON.stringify(getProjectManifest(projectDirName), null, 2)),
JSON.stringify(dependencies.getProjectManifest(projectDirName), null, 2)),
fs.writeFile(path.join(projectPath, "background.js"),
`console.log("${projectDirName} - background page loaded");`),
fs.writeFile(path.join(projectPath, "content.js"),
`console.log("${projectDirName} - content script loaded");`),
]).then(() => getPlaceholderIcon())
]).then(() => dependencies.getPlaceholderIcon())
.then(iconData => fs.writeFile(path.join(projectPath, "icon.png"), iconData))
.then(() => getProjectReadme(projectDirName))
.then(() => dependencies.getProjectReadme(projectDirName, MORE_INFO_MSG))
.then(projectReadme => fs.writeFile(path.join(projectPath, "README.md"),
stripAnsi(projectReadme)))
.then(() => getProjectCreatedMessage(projectPath))
.then(console.log);
.then(async () => {
const projectCreatedMessage = await module.exports.getProjectCreatedMessage(projectPath);
return {projectPath, projectCreatedMessage};
});
}, error => {
if (error.code === "EEXIST") {
const msg = `Unable to create a new WebExtension: ${chalk.bold.underline(projectPath)} dir already exist.`;
console.error(`${chalk.red(msg)}\n`);
process.exit(1);
const msg = `Unable to create a new WebExtension: ${chalk.bold.underline(projectPath)} dir already exists.`;
throw new UsageError(msg);
}
}).catch((error) => {
console.error(error);
process.exit(1);
});
};
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
"homepage": "https://github.com/rpl/create-webextension#readme",
"dependencies": {
"chalk": "^1.1.3",
"es6-error": "^4.0.2",
"mz": "^2.6.0",
"strip-ansi": "^3.0.1"
},
Expand Down