Browse Source

Major refactor into cli.js / lib.js

* Removed index.js
* Added cli.js
* Added lib.js
* All functions now throw or return value on success
pull/10/head
Muthu Kumar 7 years ago
parent
commit
007ee80b35
  1. 1
      .eslintrc.json
  2. 9
      actions/createProxyServer.js
  3. 14
      actions/createStaticServer.js
  4. 16
      actions/killALL.js
  5. 7
      actions/listServers.js
  6. 51
      cli.js
  7. 135
      index.js
  8. 35
      lib.js
  9. 6
      package.json
  10. 28
      utils/listFile.js
  11. 19
      utils/nginxReload.js
  12. 3
      utils/requirements.js
  13. 37
      utils/validate.js

1
.eslintrc.json

@ -3,6 +3,7 @@
"node": true,
"es6": true
},
"parserOptions": { "ecmaVersion": 2017 },
"extends": "eslint:recommended",
"rules": {
"no-console": "off",

9
actions/createProxyServer.js

@ -12,9 +12,11 @@ const { EOL } = require('os'); // \n if used on Linux, \r\n if used on Windows.
function createProxyServer(domain, inPort, outPort) {
outPort = outPort || 80;
shell.mkdir('-p', npath.confD());
shell.mkdir('-p', npath.enabledSites());
// Creates directories if doesn't exist
fs.outputFileSync((conf(npath.confD(), domain, outPort)),
fs.outputFileSync((conf(npath.enabledSites(), domain, outPort)),
"server {" + EOL +
" listen " + outPort + ";" + EOL +
" listen [::]:" + outPort + ";" + EOL +
@ -34,9 +36,6 @@ function createProxyServer(domain, inPort, outPort) {
shell.mkdir('-p', npath.enabledSites());
// Creates directories if doesn't exist
shell.ln('-sf', conf(npath.confD(), domain, outPort),
conf(npath.enabledSites(), domain, outPort));
// Symlink the conf file from sites-available to sites-enabled
appendToList(domain, outPort, inPort);
nginxReload();

14
actions/createStaticServer.js

@ -14,9 +14,11 @@ const { EOL } = require('os'); // \n if used on Linux, \r\n if used on Windows.
function createStaticServer(domain, outPort) {
outPort = outPort || 80;
shell.mkdir('-p', npath.confD());
shell.mkdir('-p', npath.enabledSites());
// Creates directories if doesn't exist
fs.outputFileSync((conf(npath.confD(), domain, outPort)),
fs.outputFileSync((conf(npath.enabledSites(), domain, outPort)),
// Gets nginx's paths from nginxPath.js
"server {" + EOL +
" listen " + outPort + ";" + EOL +
@ -30,13 +32,7 @@ function createStaticServer(domain, outPort) {
" }" + EOL +
"}"
);
shell.mkdir('-p', npath.enabledSites());
// Creates directories if doesn't exist
shell.rm('-rf', conf(npath.enabledSites(), domain, outPort));
// Removes domain from sites-enabled if exists
shell.ln('-sf', conf(npath.confD(), domain, outPort),
conf(npath.enabledSites(), domain, outPort));
// Symlink the conf file from confD to sites-enabled
shell.rm('-rf', npath.webRootDomain(domain, outPort));
// Removes domain from webroot if exists
shell.mkdir('-p', npath.webRoot());

16
actions/killALL.js

@ -2,6 +2,7 @@
const shell = require('shelljs');
const path = require('path');
const fs = require('fs');
const { EOL } = require('os');
@ -13,26 +14,23 @@ function killALL () {
shell.rm('-Rf', npath.serversBakUp);
shell.mv(npath.serversUp(), npath.serversBakUp());
shell.rm('-Rf', npath() + "sites-available");
shell.rm('-Rf', npath.confD());
shell.rm('-Rf', npath.enabledSites());
shell.rm('-Rf', npath.webRoot());
shell.mkdir('-p', npath.confD());
shell.mkdir('-p', npath.enabledSites());
shell.mkdir('-p', npath.webRoot());
shell.cp((path.join(__dirname, '/../build/defaultNginx.conf')),
conf(npath.enabledSites()));
// Create the default.conf file
console.log("All servers were killed and reverted to default.");
console.log(EOL + [
"A backup of your old servers.up is " +
"saved in /etc/up-serve/servers.bak.up.",
"Check this if you need to."
].join(EOL) + EOL);
nginxReload();
console.log(EOL + "All servers were killed and reverted to default." +
EOL + "A backup of your old servers.up is " +
"saved in /etc/up-serve/servers.bak.up." +
"Check this if you need to." + EOL
);
}
function noKill () {
console.log(EOL + "kill-all was interrupted by user.");
return(EOL + "kill-all was interrupted by user.");
}
module.exports.kill = killALL;

7
actions/listServers.js

@ -7,10 +7,9 @@ const { EOL } = require('os');
function listServers() {
const serversList = readServers();
if(serversList) console.log(EOL + prettyjson.render(serversList) + EOL);
else console.log(EOL +
"No servers were found! Create some using `up`!" +
EOL);
if(serversList) return(EOL + prettyjson.render(serversList));
else return(EOL +
"No servers were found! Create some using `up`!");
}
module.exports = listServers;

51
cli.js

@ -9,49 +9,76 @@ const program = require('commander');
const chalk = require('chalk');
// Require API
const up = require('./api');
const up = require('./lib');
const killAllConfirm = require('./actions/killAllConfirm');
// Requiring utils
const requirements = require('./utils/requirements');
// Check for requirements such as OS version and nginx install.
// Throw and exit if requirements not found.
// #Roadmap: Add ability to satisfy any possible requirements.
requirements(); // Comment in development and uncomment this line in production.
// This should check whether the OS is compatible with this version of `up`
let cmdValue;
requirements();
// Comment in development and uncomment this line in production.
const tryCatch = ((test, name) => {
try {
const msg = test();
if(msg) console.log(msg);
} catch (err) {
err.message = EOL + `[${name}]: ` + err.message;
console.log (err.message);
process.exit(1);
}
});
let cmdValue = '';
program
.version('0.2.1')
.version('0.2.5')
.arguments('<cmd>')
.action((cmd) => cmdValue = cmd);
program
.command('static <domain> [outPort]')
.description('Create a static server at this folder.')
.action((domain, outPort) => up.server(domain, outPort));
.action((domain, outPort) =>
tryCatch(
() => up.server(domain, outPort),
'new-server'
));
program
.command('proxy <domain> <inPort> [outPort]')
.description('Create a proxy server, listening at port number.')
.action((domain, inPort, outPort) => up.proxy(domain, inPort, outPort));
.action((domain, inPort, outPort) =>
tryCatch(
() => up.proxy(domain, inPort, outPort),
'new-proxy'
));
program
.command('list')
.description('List all available servers.')
.action(() => up.list());
.action(() =>
tryCatch(
() => up.list(),
'list'
));
program
.command('kill <domain> [ourPort]')
.description('Kill a server.')
.action((domain, outPort) => up.kill(domain, outPort));
.action((domain, outPort) =>
tryCatch (
() => up.kill(domain, outPort),
'kill-server'
));
program
.command('kill-all')
.description('Warning! Will completely kill all servers and reset nginx')
.action(() => up.reset());
.action(() => killAllConfirm());
program

135
index.js

@ -1,135 +0,0 @@
#!/usr/bin/env node
'use strict';
const { EOL } = require('os');
// Requiring npm modules
const program = require('commander');
const chalk = require('chalk');
// Requiring Actions
const createProxyServer = require('./actions/createProxyServer');
const createStaticServer = require('./actions/createStaticServer');
const killServer = require('./actions/killServer');
const listServers = require('./actions/listServers');
const killAllConfirm = require('./actions/killAllConfirm');
// Requiring utils
const validate = require('./utils/validate');
const requirements = require('./utils/requirements');
// Check for requirements such as OS version and nginx install.
// Throw and exit if requirements not found.
// #Roadmap: Add ability to satisfy any possible requirements.
requirements(); // Comment in development and uncomment this line in production.
// This should check whether the OS is compatible with this version of `up`
let cmdValue;
program
.version('0.2.1')
.arguments('<cmd>')
.action(function (cmd) {
cmdValue = cmd;
});
program
.command('static <domain> [outPort]')
.description('Create a static server at this folder.')
.action(function (domain, outPort) {
// If outport is not given, 80 is set as default.
// Later, change this default to reflect nginx's settings.
outPort = outPort || "80";
// This is a string because regex needs to validate it.
if (!validate(domain, outPort)) return;
// Validates domain and outport, and if invalid, throws and returns.
createStaticServer(domain, outPort);
if (outPort != "80" || "443") domain = domain + ":" + outPort;
console.log(EOL + [
"Done! Your static server has been set up!",
"Point your domain to this server and check " +
chalk.cyan(domain) +
" to verify!"
].join(EOL));
});
program
.command('proxy <domain> <inPort> [outPort]')
.description('Create a proxy server, listening at port number.')
.action(function (domain, inPort, outPort) {
// Inbound port is necessary, but outbound is set to 80 by default.
// Again, will change this to reflect nginx's settings.
outPort = outPort || "80";
// This is a string because regex needs to validate it.
if (!validate(domain, inPort, outPort)) return;
createProxyServer(domain, inPort, outPort);
if (outPort != "80" || "443") domain = domain + ":" + outPort;
console.log(EOL + [
"Done! Your reverse proxy server has been set up!",
"Point your domain to this server and check " +
chalk.cyan(domain) +
" to verify!"].join(EOL));
});
program
.command('list')
.description('List all available servers.')
.action(function () {
listServers();
});
program
.command('kill <domain> [ourPort]')
.description('Kill a server.')
.action(function (domain, outPort) {
outPort = outPort || "80";
// This is a string because regex needs to validate it.
killServer(domain, outPort);
console.log(EOL + "Done! Your server has been killed!"+ EOL);
});
program
.command('kill-all')
.description('Warning! Will completely kill all servers and reset nginx')
.action(function() {
killAllConfirm();
});
program
.command('*') // This should pick invalid commands, but it doesn't, yet.
.action(function () {
console.log(EOL + "Invalid command. Type " +
chalk.cyan('up --help') + " for help." + EOL);
});
// Adds custom help text to the automatically generated help.
program.on('--help', function () {
console.log(EOL
+ ' Usage:'
+ EOL
+ EOL
+ ' ' + chalk.yellow('$ up ')
+ chalk.cyan('static')
+ chalk.blue('[domain-name]')
+ EOL
+ ' Set up a static server at domain-name'
+ EOL
+ EOL
+ ' ' + chalk.yellow('$ up ')
+ chalk.cyan('proxy')
+ chalk.blue('[domain-name] <port-number>')
+ EOL
+ ' Set up a proxy server listening at port-number'
+ EOL);
});
// Parses commands passed to `up` and chooses one of the above commands.
program.parse(process.argv);
if (typeof cmdValue === 'undefined') {
console.log(EOL + "No command was given. `up --help` for help info.");
process.exit(1);
}

35
api.js → lib.js

@ -10,21 +10,18 @@ const createProxyServer = require('./actions/createProxyServer');
const createStaticServer = require('./actions/createStaticServer');
const killServer = require('./actions/killServer');
const listServers = require('./actions/listServers');
const killAllConfirm = require('./actions/killAllConfirm');
// Requiring utils
const validate = require('./utils/validate');
function server (domain, outPort) {
function server (domain, outPort = "80") {
// If outport is not given, 80 is set as default.
// Later, change this default to reflect nginx's settings.
outPort = String(outPort) || "80";
// This is a string because regex needs to validate it.
if (!validate(domain, outPort)) return;
outPort = String(outPort);
validate(domain, outPort);
// Validates domain and outport, and if invalid, throws and returns.
createStaticServer(domain, outPort);
if (outPort != "80" || "443") domain = domain + ":" + outPort;
console.log(EOL + [
return (EOL + [
"Done! Your static server has been set up!",
"Point your domain to this server and check " +
chalk.cyan(domain) +
@ -32,16 +29,15 @@ function server (domain, outPort) {
].join(EOL));
}
function proxy (domain, inPort, outPort) {
function proxy (domain, inPort, outPort = "80") {
// Inbound port is necessary, but outbound is set to 80 by default.
// Again, will change this to reflect nginx's settings.
outPort = String(outPort) || "80";
outPort = String(outPort);
inPort = String(inPort);
// This is a string because regex needs to validate it.
if (!validate(domain, inPort, outPort)) return;
validate(domain, inPort, outPort);
createProxyServer(domain, inPort, outPort);
if (outPort != "80" || "443") domain = domain + ":" + outPort;
console.log(EOL + [
return (EOL + [
"Done! Your reverse proxy server has been set up!",
"Point your domain to this server and check " +
chalk.cyan(domain) +
@ -49,24 +45,19 @@ function proxy (domain, inPort, outPort) {
}
function list () {
listServers();
return listServers();
}
function kill (domain, outPort) {
outPort = String(outPort) || "80";
function kill (domain, outPort = "80") {
outPort = String(outPort);
// This is a string because regex needs to validate it.
killServer(domain, outPort);
console.log(EOL + "Done! Your server has been killed!"+ EOL);
}
function reset () {
killAllConfirm();
return (EOL + "Done! Your server has been killed!");
}
module.exports = {
server,
proxy,
list,
kill,
reset
kill
};

6
package.json

@ -2,7 +2,7 @@
"name": "up-serve",
"version": "0.2.1",
"description": "A cli tool to quickly create and manage nginx server blocks.",
"main": "index.js",
"main": "lib.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "node ./build/fetchTLDS"
@ -28,8 +28,8 @@
},
"homepage": "https://github.com/codefeathers/up-serve#readme",
"dependencies": {
"chalk": "^2.3.0",
"commander": "^2.11.0",
"chalk": "2.3.0",
"commander": "2.11.0",
"fs-extra": "^4.0.2",
"prettyjson": "^1.2.1",
"readline-sync": "^1.4.7",

28
utils/listFile.js

@ -1,7 +1,5 @@
'use strict';
const { EOL } = require('os');
const fs = require('fs-extra');
const removeFromArray = require('./removeFromArray');
@ -35,23 +33,33 @@ function appendToList(domain, outPort, inPort) {
function removeFromList (domain, outPort) {
if (fs.existsSync(listFilePath())) {
let jsonFile = { "domains": [] };
const jsonBuffer = JSON.parse(fs.readFileSync(listFilePath()));
jsonFile.domains = removeFromArray(jsonBuffer.domains, domain, outPort);
jsonFile = JSON.stringify(jsonBuffer, null, '\t');
fs.writeFileSync(listFilePath(), jsonFile);
const jsonContent = fs.readFileSync(listFilePath(), "utf-8");
const jsonBuffer = JSON.parse(jsonContent);
for (let i = 0; i < (jsonBuffer.domains).length; i ++) {
if(jsonBuffer.domains[i].domain == domain){
jsonFile.domains =
removeFromArray(jsonBuffer.domains, domain, outPort);
jsonFile = JSON.stringify(jsonFile, null, '\t');
fs.writeFileSync(listFilePath(), jsonFile);
return;
}
}
throw new Error("This domain does not exist in servers.up");
}
else console.log(EOL + "No servers were created using `up` yet." + EOL);
else throw new Error("No servers were created using `up` yet.");
}
function readServers () {
let serversList;
if (fs.existsSync(listFilePath())) {
serversList = JSON.parse(fs.readFileSync(listFilePath()));
if(!serversList.domains[0]) return undefined;
if(!serversList.domains[0]) {
throw new Error("No domains exist in servers.up");
}
}
else {
return "Servers were not created";
return "No servers were created using `up` yet.";
}
return serversList;
}

19
utils/nginxReload.js

@ -3,14 +3,17 @@
const { execSync } = require('child_process');
function nginxReload() {
execSync('service nginx reload', function (error, stdout, stderr) {
if (error) {
console.error("exec error: " + error);
console.log("stdout: " + stdout);
console.log("stderr: " + stderr);
process.exit(1);
}
});
/*try {
execSync('service nginx reload', {
stdio: 'ignore'
});
execSync('service nginx start', {
stdio: 'ignore'
});
} catch (err) {
throw new Error('nginx failed to load');
}
return;*/
}
module.exports = nginxReload;

3
utils/requirements.js

@ -25,7 +25,8 @@ function requirements() {
// Check if sudo
if (process.getuid() != 0) {
console.log("`up` requires root privileges to work. Please use `sudo up <command>`");
shell.echo("`up` requires root privileges to work."
+ "Please use `sudo up <command>`");
shell.exit(1);
}

37
utils/validate.js

@ -1,7 +1,5 @@
'use strict';
const { EOL } = require('os');
const parseToInt = require('./parseToInt');
const isIP = require('./isIP');
@ -15,12 +13,12 @@ function validate(domain, inPort, outPort) {
// Error messages
const domainInvalidMsg = [
EOL + "Please use a domain name instead of an IP address.",
EOL + "Domain is not valid. Please use a valid domain name."
"Please use a domain name instead of an IP address.",
"Domain is not valid. Please use a valid domain name."
];
const portInvalidMsg = [
EOL + "Port should be a number.",
EOL + "Port should be a number from 1 and 65535."
"Port should be a number.",
"Port should be a number from 1 and 65535."
];
// ARGV returns a string as input.
@ -30,35 +28,25 @@ function validate(domain, inPort, outPort) {
const validInPort = parseToInt(inPort);
const validOutPort = parseToInt(outPort);
// The value of isInvalid will be returned back.
// If none of the `if`s are true, the default
// value `true` is returned `domain`, `inPort` and `outPort` are considered
// validated.
let isValid = true;
// Throw if IP is given instead of domain name.
if (isIP(domain)) {
console.log(domainInvalidMsg[0]);
return isValid = false;
throw new Error(domainInvalidMsg[0]);
}
// Throw if input is not a Fully Qualified Domain Name (FQDN)
if (!isDomain(domain)) {
console.log(domainInvalidMsg[1]);
return isValid = false;
throw new Error(domainInvalidMsg[1]);
}
// Enter if `inPort` is not defined.
// This happens for `up static` where no inbound ports are required.
if (typeof inPort == undefined) {
if (!validOutPort) {
console.log(portInvalidMsg[0]); // `outPort` is not an integer.
return isValid = false;
throw new Error(portInvalidMsg[0]);// `outPort` is not an integer.
}
if (!(validOutPort > 0 && validOutPort <= 65535)) {
console.log(portInvalidMsg[1]);
throw new Error(portInvalidMsg[1]);
// `outPort` is not within port range.
return isValid = false;
}
}
@ -66,23 +54,18 @@ function validate(domain, inPort, outPort) {
// inbound port is required.
if (typeof inPort !== undefined) {
if (!validInPort || !validOutPort) {
console.log(portInvalidMsg[0]);
throw new Error(portInvalidMsg[0]);
// Either `inPort` or `outPort` is not an integer.
return isValid = false;
}
if (typeof outPort !== undefined) {
if (!(
(validInPort > 0 && validInPort <= 65535) &&
(validOutPort > 0 && validOutPort <= 65535)
)) {
console.log(portInvalidMsg[1]);
throw new Error(portInvalidMsg[1]);
// Either `inPort` or `outPort` are not within port range.
return isValid = false;
}
}
return isValid;
// If any of the `if`s were true, `isInvalid = false`.
// If not, `isInvalid = true`.
}
}

Loading…
Cancel
Save