Browse Source

Merge complete ES6 update from trgwii/develop

ESLint fixes: const, newlines, destructuring, max width
pull/7/head
Muthu Kumar 7 years ago
committed by GitHub
parent
commit
e0f63aa2cc
No known key found for this signature in database GPG Key ID: 4AEE18F83AFDEB23
  1. 7
      .eslintrc.json
  2. 23
      actions/createProxyServer.js
  3. 42
      actions/createStaticServer.js
  4. 15
      actions/killALL.js
  5. 12
      actions/killAllConfirm.js
  6. 12
      actions/killServer.js
  7. 14
      actions/listServers.js
  8. 13
      build/fetchTLDS.js
  9. 82
      index.js
  10. 12
      utils/isFQDN.js
  11. 8
      utils/isIP.js
  12. 24
      utils/listFile.js
  13. 5
      utils/nginxConf.js
  14. 17
      utils/nginxPath.js
  15. 4
      utils/nginxReload.js
  16. 7
      utils/parseToInt.js
  17. 8
      utils/removeFromArray.js
  18. 24
      utils/requirements.js
  19. 60
      utils/validate.js

7
.eslintrc.json

@ -18,6 +18,11 @@
"error", "error",
"always" "always"
], ],
"prefer-const": "error" "prefer-const": "error",
"prefer-destructuring": "error",
"no-var": "error",
"strict": "error",
"eol-last": "error",
"max-len": "error"
} }
} }

23
actions/createProxyServer.js

@ -1,12 +1,14 @@
var fs = require('fs-extra'); 'use strict';
var shell = require('shelljs');
var npath = require('../utils/nginxPath'); const fs = require('fs-extra');
var conf = require('../utils/nginxConf'); const shell = require('shelljs');
var nginxReload = require('../utils/nginxReload');
var appendToList = require('../utils/listFile').appendToList;
var EOL = require('os').EOL; // \n if used on Linux, \r\n if used on Windows. const npath = require('../utils/nginxPath');
const conf = require('../utils/nginxConf');
const nginxReload = require('../utils/nginxReload');
const { appendToList } = require('../utils/listFile');
const { EOL } = require('os'); // \n if used on Linux, \r\n if used on Windows.
function createProxyServer(domain, inPort, outPort) { function createProxyServer(domain, inPort, outPort) {
outPort = outPort || 80; outPort = outPort || 80;
@ -30,8 +32,11 @@ function createProxyServer(domain, inPort, outPort) {
"}" "}"
); );
shell.mkdir('-p', npath.confD()); shell.mkdir('-p', npath.confD());
shell.mkdir('-p', npath.enabledSites()); // Creates directories if doesn't exist shell.mkdir('-p', npath.enabledSites());
shell.ln('-sf', conf(npath.confD(), domain, outPort), conf(npath.enabledSites(), domain, outPort)); // Symlink the conf file from sites-available to sites-enabled // 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); appendToList(domain, outPort, inPort);
nginxReload(); nginxReload();

42
actions/createStaticServer.js

@ -1,20 +1,23 @@
var fs = require('fs-extra'); 'use strict';
var shell = require('shelljs');
var path = require('path');
var npath = require('../utils/nginxPath'); const fs = require('fs-extra');
var conf = require('../utils/nginxConf'); const shell = require('shelljs');
var nginxReload = require('../utils/nginxReload'); const path = require('path');
var appendToList = require('../utils/listFile').appendToList;
var currentPath = path.normalize(process.cwd()); const npath = require('../utils/nginxPath');
var EOL = require('os').EOL; // \n if used on Linux, \r\n if used on Windows. const conf = require('../utils/nginxConf');
const nginxReload = require('../utils/nginxReload');
const { appendToList } = require('../utils/listFile');
const currentPath = path.normalize(process.cwd());
const { EOL } = require('os'); // \n if used on Linux, \r\n if used on Windows.
function createStaticServer(domain, outPort) { function createStaticServer(domain, outPort) {
outPort = outPort || 80; outPort = outPort || 80;
shell.mkdir('-p', npath.confD()); shell.mkdir('-p', npath.confD());
fs.outputFileSync((conf(npath.confD(), domain, outPort)), // Gets nginx's paths from nginxPath.js fs.outputFileSync((conf(npath.confD(), domain, outPort)),
// Gets nginx's paths from nginxPath.js
"server {" + EOL + "server {" + EOL +
" listen " + outPort + ";" + EOL + " listen " + outPort + ";" + EOL +
" listen [::]:" + outPort + ";" + EOL + " listen [::]:" + outPort + ";" + EOL +
@ -27,12 +30,19 @@ function createStaticServer(domain, outPort) {
" }" + EOL + " }" + EOL +
"}" "}"
); );
shell.mkdir('-p', npath.enabledSites()); // Creates directories if doesn't exist shell.mkdir('-p', npath.enabledSites());
shell.rm('-rf', conf(npath.enabledSites(), domain, outPort)); // Removes domain from sites-enabled if exists // Creates directories if doesn't exist
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', conf(npath.enabledSites(), domain, outPort));
shell.rm('-rf', npath.webRootDomain(domain, outPort)); // Removes domain from webroot if exists // Removes domain from sites-enabled if exists
shell.mkdir('-p', npath.webRoot()); // Creating the nginx www path if it doesn't exist so symlink doesn't fail shell.ln('-sf', conf(npath.confD(), domain, outPort),
shell.ln('-sf', currentPath, npath.webRootDomain(domain, outPort)); // Symlink current directory to nginx's web root 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());
// Creating the nginx www path if it doesn't exist so symlink doesn't fail
shell.ln('-sf', currentPath, npath.webRootDomain(domain, outPort));
// Symlink current directory to nginx's web root
appendToList(domain, outPort); appendToList(domain, outPort);
nginxReload(); nginxReload();

15
actions/killALL.js

@ -1,7 +1,9 @@
var shell = require('shelljs'); 'use strict';
var npath = require('../utils/nginxPath'); const shell = require('shelljs');
var conf = require('../utils/nginxConf');
const npath = require('../utils/nginxPath');
const conf = require('../utils/nginxConf');
function killALL () { function killALL () {
shell.rm('-Rf', npath.serversBakUp); shell.rm('-Rf', npath.serversBakUp);
@ -13,8 +15,11 @@ function killALL () {
shell.mkdir('-p', npath.confD()); shell.mkdir('-p', npath.confD());
shell.mkdir('-p', npath.enabledSites()); shell.mkdir('-p', npath.enabledSites());
shell.mkdir('-p', npath.webRoot()); shell.mkdir('-p', npath.webRoot());
shell.cp('./build/defaultNginx.conf', conf(npath.confD())); // Create the default.conf file shell.cp('./build/defaultNginx.conf', conf(npath.confD()));
shell.ln('-sf', npath.confD() + "default.conf", npath.enabledSites() + "default.conf"); // Symlink the default.conf file from confD to sites-enabled // Create the default.conf file
shell.ln('-sf', npath.confD() + "default.conf",
npath.enabledSites() + "default.conf");
// Symlink the default.conf file from confD to sites-enabled
} }
module.exports = killALL; module.exports = killALL;

12
actions/killAllConfirm.js

@ -1,3 +1,7 @@
'use strict';
const { EOL } = require('os');
const prompt = require('prompt'); const prompt = require('prompt');
const shell = require('shelljs'); const shell = require('shelljs');
@ -8,9 +12,10 @@ function killAllConfirm () {
prompt.start(); prompt.start();
var property = { const property = {
name: 'yesno', name: 'yesno',
message: 'This will completely destroy all configs and reset nginx. Are you sure?', message: 'This will completely destroy all configs and reset nginx. ' +
'Are you sure?',
validator: /y[es]*|n[o]?/, validator: /y[es]*|n[o]?/,
warning: 'Must respond yes or no', warning: 'Must respond yes or no',
default: 'no' default: 'no'
@ -24,7 +29,8 @@ function killAllConfirm () {
else { else {
console.log("Deleting all servers..."); console.log("Deleting all servers...");
killAll(); killAll();
console.log("\nDone. All configs have been destroyed. Hope you're happy."); console.log(EOL +
"Done. All configs have been destroyed. Hope you're happy.");
} }
}); });
} }

12
actions/killServer.js

@ -1,9 +1,11 @@
var shell = require('shelljs'); 'use strict';
var npath = require('../utils/nginxPath'); const shell = require('shelljs');
var conf = require('../utils/nginxConf');
var nginxReload = require('../utils/nginxReload'); const npath = require('../utils/nginxPath');
var removeFromList = require('../utils/listFile').removeFromList; const conf = require('../utils/nginxConf');
const nginxReload = require('../utils/nginxReload');
const { removeFromList } = require('../utils/listFile');
function killServer(domain, outPort) { function killServer(domain, outPort) {
shell.rm('-rf', conf(npath.enabledSites(), domain, outPort)); shell.rm('-rf', conf(npath.enabledSites(), domain, outPort));

14
actions/listServers.js

@ -1,12 +1,16 @@
var readServers = require('../utils/listFile').readServers; 'use strict';
var prettyjson = require('prettyjson');
var EOL = require('os').EOL; const { readServers } = require('../utils/listFile');
const prettyjson = require('prettyjson');
const { EOL } = require('os');
function listServers() { function listServers() {
var serversList = readServers(); const serversList = readServers();
if(serversList) console.log(EOL + prettyjson.render(serversList) + EOL); if(serversList) console.log(EOL + prettyjson.render(serversList) + EOL);
else console.log("\nNo servers were found! Create some using `up`!\n"); else console.log(EOL +
"No servers were found! Create some using `up`!" +
EOL);
} }
module.exports = listServers; module.exports = listServers;

13
build/fetchTLDS.js

@ -1,7 +1,8 @@
var https = require('https'); 'use strict';
var fs = require('fs-extra');
var file = fs.createWriteStream("./assets/tlds.txt"); const https = require('https');
https.get("https://data.iana.org/TLD/tlds-alpha-by-domain.txt", function(response) { const fs = require('fs-extra');
response.pipe(file);
}); const file = fs.createWriteStream("./assets/tlds.txt");
https.get("https://data.iana.org/TLD/tlds-alpha-by-domain.txt",response =>
response.pipe(file));

82
index.js

@ -2,26 +2,30 @@
'use strict'; 'use strict';
const { EOL } = require('os');
// Requiring npm modules // Requiring npm modules
var program = require('commander'); const program = require('commander');
var chalk = require('chalk'); const chalk = require('chalk');
//var fs = require('fs-extra'); //var fs = require('fs-extra');
// Requiring Actions // Requiring Actions
var createProxyServer = require('./actions/createProxyServer'); const createProxyServer = require('./actions/createProxyServer');
var createStaticServer = require('./actions/createStaticServer'); const createStaticServer = require('./actions/createStaticServer');
var killServer = require('./actions/killServer'); const killServer = require('./actions/killServer');
var listServers = require('./actions/listServers'); const listServers = require('./actions/listServers');
var killAllConfirm = require('./actions/killAllConfirm'); const killAllConfirm = require('./actions/killAllConfirm');
// Requiring utils // Requiring utils
var validate = require('./utils/validate'); const validate = require('./utils/validate');
var requirements = require('./utils/requirements'); const requirements = require('./utils/requirements');
// Check for requirements such as OS version and nginx install. Throw and exit if requirements not found. // 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. // #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` requirements(); // Comment in development and uncomment this line in production.
// This should check whether the OS is compatible with this version of `up`
program program
.version('0.1.5'); .version('0.1.5');
@ -29,23 +33,40 @@ program
program program
.command('static <domain> [outPort]') .command('static <domain> [outPort]')
.description('Create a static server at this folder.') .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. .action(function (domain, outPort) {
outPort = outPort || "80"; // This is a string because regex needs to validate it. // If outport is not given, 80 is set as default.
if (!validate(domain, outPort)) return; //Validates domain and outport, and if invalid, throws and returns. // 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); createStaticServer(domain, outPort);
if (outPort != "80" || "443") domain = domain + ":" + outPort; if (outPort != "80" || "443") domain = domain + ":" + outPort;
console.log("\nDone! Your static server has been set up!\nPoint your domain to this server and check " + chalk.cyan(domain) + " to verify!"); 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 program
.command('proxy <domain> <inPort> [outPort]') .command('proxy <domain> <inPort> [outPort]')
.description('Create a proxy server, listening at port number.') .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. .action(function (domain, inPort, outPort) {
outPort = outPort || "80"; // This is a string because regex needs to validate it. // 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; if (!validate(domain, inPort, outPort)) return;
createProxyServer(domain, inPort, outPort); createProxyServer(domain, inPort, outPort);
if (outPort != "80" || "443") domain = domain + ":" + outPort; if (outPort != "80" || "443") domain = domain + ":" + outPort;
console.log("\nDone! Your reverse proxy server has been set up!\nPoint your domain to this server and check " + chalk.cyan(domain) + " to verify!"); 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 program
@ -59,9 +80,10 @@ program
.command('kill <domain> [ourPort]') .command('kill <domain> [ourPort]')
.description('Kill a server.') .description('Kill a server.')
.action(function (domain, outPort) { .action(function (domain, outPort) {
outPort = outPort || "80"; // This is a string because regex needs to validate it. outPort = outPort || "80";
// This is a string because regex needs to validate it.
killServer(domain, outPort); killServer(domain, outPort);
console.log("\nDone! Your server has been killed!\n"); console.log(EOL + "Done! Your server has been killed!"+ EOL);
}); });
program program
@ -69,14 +91,18 @@ program
.description('Warning! Will completely kill all servers and reset nginx') .description('Warning! Will completely kill all servers and reset nginx')
.action(function() { .action(function() {
killAllConfirm(); killAllConfirm();
console.log("\nA backup of your old servers.up is saved in /etc/up-serve/servers.bak.up.\n" + console.log(EOL + [
"Check this if you need to.\n"); "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);
}); });
program program
.command('*') // This should pick invalid commands, but it doesn't, yet. .command('*') // This should pick invalid commands, but it doesn't, yet.
.action(function () { .action(function () {
console.log("\nInvalid command. Type " + chalk.cyan('up --help') + " for help.\n"); console.log(EOL + "Invalid command. Type " +
chalk.cyan('up --help') + " for help." + EOL);
}); });
// Adds custom help text to the automatically generated help. // Adds custom help text to the automatically generated help.
@ -84,10 +110,16 @@ program.on('--help', function () {
console.log(''); console.log('');
console.log(' Usage:'); console.log(' Usage:');
console.log(''); console.log('');
console.log(' ', chalk.yellow('$ up'), chalk.cyan('static'), chalk.blue('domain-name')); console.log(' ',
chalk.yellow('$ up'),
chalk.cyan('static'),
chalk.blue('domain-name'));
console.log(' Set up a static server at domain-name'); console.log(' Set up a static server at domain-name');
console.log(''); console.log('');
console.log(' ', chalk.yellow('$ up'), chalk.cyan('proxy'), chalk.blue('domain-name port-number')); console.log(' ',
chalk.yellow('$ up'),
chalk.cyan('proxy'),
chalk.blue('domain-name port-number'));
console.log(' Set up a proxy server listening at port-number'); console.log(' Set up a proxy server listening at port-number');
console.log(''); console.log('');
}); });

12
utils/isFQDN.js

@ -3,7 +3,7 @@
'use strict'; 'use strict';
var fs = require('fs-extra'); const fs = require('fs-extra');
// Official list of TLDs should be fetched from: // Official list of TLDs should be fetched from:
// https://data.iana.org/TLD/tlds-alpha-by-domain.txt // https://data.iana.org/TLD/tlds-alpha-by-domain.txt
@ -14,7 +14,7 @@ var fs = require('fs-extra');
function isFQDN(domain) { function isFQDN(domain) {
// Importing and parsing `tlds.txt` file // Importing and parsing `tlds.txt` file
var tlds = fs.readFileSync('./assets/tlds.txt', 'utf8') const tlds = fs.readFileSync('./assets/tlds.txt', 'utf8')
.split(/[\r\n]+/) .split(/[\r\n]+/)
.filter(x => !x.startsWith('#')); .filter(x => !x.startsWith('#'));
@ -22,19 +22,19 @@ function isFQDN(domain) {
return false; return false;
} }
var labels = domain.split('.').reverse(); const labels = domain.split('.').reverse();
if (labels.length < 2) { if (labels.length < 2) {
return false; return false;
} }
var tld = labels[0]; const [ tld ] = labels;
if (!tlds.includes(tld.toUpperCase())) { if (!tlds.includes(tld.toUpperCase())) {
return false; return false;
} }
for (var label of labels) { for (const label of labels) {
const len = label.length; const len = label.length;
@ -56,6 +56,6 @@ function isFQDN(domain) {
} }
} }
return true; return true;
}; }
module.exports = isFQDN; module.exports = isFQDN;

8
utils/isIP.js

@ -1,14 +1,16 @@
'use strict';
// Parses a string, and returns true if it is an IP Address. // Parses a string, and returns true if it is an IP Address.
function isIP(str) { function isIP(str) {
var segments = str const segments = str
.split(".") .split(".")
.map(Number); .map(Number);
if (!segments.length === 4) { if (!segments.length === 4) {
return false; return false;
} }
for(var i = 0; i < segments.length; i++) { for(let i = 0; i < segments.length; i++) {
var segment = segments[i]; const segment = segments[i];
if (Number.isNaN(segment)) { if (Number.isNaN(segment)) {
return false; return false;
} }

24
utils/listFile.js

@ -1,13 +1,17 @@
var fs = require('fs-extra'); 'use strict';
var removeFromArray = require('./removeFromArray'); const { EOL } = require('os');
var listFilePath = require('./nginxPath').serversUp;
const fs = require('fs-extra');
const removeFromArray = require('./removeFromArray');
const listFilePath = require('./nginxPath').serversUp;
function appendToList(domain, outPort, inPort) { function appendToList(domain, outPort, inPort) {
inPort = inPort || undefined; inPort = inPort || undefined;
var jsonFile = { "domains": [] }; let jsonFile = { "domains": [] };
var domBlock = { const domBlock = {
"domain": domain, "domain": domain,
"outPort": outPort "outPort": outPort
}; };
@ -20,7 +24,7 @@ function appendToList(domain, outPort, inPort) {
} }
if (fs.existsSync(listFilePath())) { if (fs.existsSync(listFilePath())) {
var jsonBuffer = JSON.parse(fs.readFileSync(listFilePath())); const jsonBuffer = JSON.parse(fs.readFileSync(listFilePath()));
jsonFile.domains = removeFromArray(jsonBuffer.domains, domain, outPort); jsonFile.domains = removeFromArray(jsonBuffer.domains, domain, outPort);
} }
jsonFile.domains.push(domBlock); jsonFile.domains.push(domBlock);
@ -30,18 +34,18 @@ function appendToList(domain, outPort, inPort) {
function removeFromList (domain, outPort) { function removeFromList (domain, outPort) {
if (fs.existsSync(listFilePath())) { if (fs.existsSync(listFilePath())) {
var jsonFile = { "domains": [] }; let jsonFile = { "domains": [] };
var jsonBuffer = JSON.parse(fs.readFileSync(listFilePath())); const jsonBuffer = JSON.parse(fs.readFileSync(listFilePath()));
jsonFile.domains = removeFromArray(jsonBuffer.domains, domain, outPort); jsonFile.domains = removeFromArray(jsonBuffer.domains, domain, outPort);
jsonFile = JSON.stringify(jsonBuffer, null, '\t'); jsonFile = JSON.stringify(jsonBuffer, null, '\t');
fs.writeFileSync(listFilePath(), jsonFile); fs.writeFileSync(listFilePath(), jsonFile);
} }
else console.log("\nNo servers were created using `up` yet.\n"); else console.log(EOL + "No servers were created using `up` yet." + EOL);
} }
function readServers () { function readServers () {
var serversList = JSON.parse(fs.readFileSync(listFilePath())); const serversList = JSON.parse(fs.readFileSync(listFilePath()));
if(!serversList.domains[0]) return undefined; if(!serversList.domains[0]) return undefined;
return serversList; return serversList;

5
utils/nginxConf.js

@ -1,4 +1,7 @@
// Simple function that takes a path and domain name, concatenates them with ".conf" and returns it. 'use strict';
// Simple function that takes a path and domain name,
// concatenates them with ".conf" and returns it.
function conf(path, domain, outPort) { function conf(path, domain, outPort) {
return (path + domain + "." + outPort + ".conf"); return (path + domain + "." + outPort + ".conf");

17
utils/nginxPath.js

@ -1,13 +1,14 @@
'use strict'; 'use strict';
// These functions just return paths. Later, these should be modified to poll from nginx's config. // These functions just return paths.
// Later, these should be modified to poll from nginx's config.
var npath = "/etc/nginx/";
var enabled = npath + "sites-enabled/"; const npath = "/etc/nginx/";
var confDpath = npath + "conf.d/"; const enabled = npath + "sites-enabled/";
var upPath = "/etc/up-serve/"; const confDpath = npath + "conf.d/";
var wwwRoot = upPath + "static/"; const upPath = "/etc/up-serve/";
var serverListPath = upPath + "servers"; const wwwRoot = upPath + "static/";
const serverListPath = upPath + "servers";
function nginxPath() { function nginxPath() {
return npath; return npath;

4
utils/nginxReload.js

@ -1,4 +1,6 @@
var execSync = require('child_process').execSync; 'use strict';
const { execSync } = require('child_process');
function nginxReload() { function nginxReload() {
execSync('service nginx reload', function (error, stdout, stderr) { execSync('service nginx reload', function (error, stdout, stderr) {

7
utils/parseToInt.js

@ -1,7 +1,10 @@
// Parse an input string and return a number if it is an integer. If it's a float, string, or array, return undefined. 'use strict';
// Parse an input string and return a number if it is an integer.
// If it's a float, string, or array, return undefined.
function parseToInt(inputString) { function parseToInt(inputString) {
var parsing = /^\d+$/.exec(inputString); const parsing = /^\d+$/.exec(inputString);
return (parsing || [])[0]; return (parsing || [])[0];
} }

8
utils/removeFromArray.js

@ -1,7 +1,11 @@
'use strict';
function removeFromArray (arr, dom, port) { function removeFromArray (arr, dom, port) {
var shouldDelete = []; let shouldDelete = [];
for(var i = 0; i < arr.length; i++) if((arr[i].domain == dom) && (arr[i].outPort == port)) shouldDelete = [true, i]; for(let i = 0; i < arr.length; i++)
if((arr[i].domain == dom) && (arr[i].outPort == port))
shouldDelete = [true, i];
if (shouldDelete[0]) { if (shouldDelete[0]) {
arr.splice(shouldDelete[1], 1); arr.splice(shouldDelete[1], 1);

24
utils/requirements.js

@ -1,20 +1,32 @@
var shell = require('shelljs'); 'use strict';
var chalk = require('chalk');
const { EOL } = require('os');
const shell = require('shelljs');
const chalk = require('chalk');
function requirements() { function requirements() {
// Detect Linux or BSD // Detect Linux or BSD
var isLin = /^linux|^bsd/.test(process.platform); const isLin = /^linux|^bsd/.test(process.platform);
// Throw if OS is not Linux or BSD. This should be changed to throw if not Debian based distro. Eventually, we can add more exceptions as `up` handles more cases. // Throw if OS is not Linux or BSD.
// This should be changed to throw if not Debian based distro.
// Eventually, we can add more exceptions as `up` handles more cases.
if(!isLin) { if(!isLin) {
shell.echo("\nThis is not a Linux or freeBSD distribution. This tool not written for this distro. Please raise an issue at " + chalk.cyan("https://github.com/codefeathers/up-serve") + " if you want `up` to be ported for your distro"); shell.echo(EOL +
"This is not a Linux or freeBSD distribution. " +
"This tool not written for this distro. " +
"Please raise an issue at " +
chalk.cyan("https://github.com/codefeathers/up-serve") +
" if you want `up` to be ported for your distro");
shell.exit(1); shell.exit(1);
} }
// Throw if Nginx is not found // Throw if Nginx is not found
if (!shell.which('nginx')) { if (!shell.which('nginx')) {
shell.echo('I need nginx to work. Install nginx first. https://nginx.org/'); shell.echo(
'I need nginx to work. Install nginx first. https://nginx.org/');
shell.exit(1); shell.exit(1);
} }

60
utils/validate.js

@ -1,8 +1,12 @@
var parseToInt = require('./parseToInt'); 'use strict';
var isIP = require('./isIP');
const { EOL } = require('os');
const parseToInt = require('./parseToInt');
const isIP = require('./isIP');
// Using Validator // Using Validator
var isDomain = require('./isFQDN'); const isDomain = require('./isFQDN');
function validate(domain, inPort, outPort) { function validate(domain, inPort, outPort) {
// //
@ -10,15 +14,27 @@ function validate(domain, inPort, outPort) {
outPort = outPort || 80; outPort = outPort || 80;
// Error messages // Error messages
var domainInvalidMsg = ["\nPlease use a domain name instead of an IP address.", "\nDomain is not valid. Please use a valid domain name."]; const domainInvalidMsg = [
var portInvalidMsg = ["\nPort should be a number.", "\nPort should be a number from 1 and 65535."]; EOL + "Please use a domain name instead of an IP address.",
EOL + "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."
];
// ARGV returns a string as input. Port numbers should be parsed to int to validate them. If validation fails, these will return undefined and will fail the subsequent test. // ARGV returns a string as input.
var validInPort = parseToInt(inPort); // Port numbers should be parsed to int to validate them.
var validOutPort = parseToInt(outPort); // If validation fails, these will return undefined and
// will fail the subsequent test.
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. // The value of isInvalid will be returned back.
var isValid = true; // 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. // Throw if IP is given instead of domain name.
if (isIP(domain)) { if (isIP(domain)) {
@ -32,31 +48,41 @@ function validate(domain, inPort, outPort) {
return isValid = false; return isValid = false;
} }
// Enter if `inPort` is not defined. This happens for `up static` where no inbound ports are required. // Enter if `inPort` is not defined.
// This happens for `up static` where no inbound ports are required.
if (typeof inPort == undefined) { if (typeof inPort == undefined) {
if (!validOutPort) { if (!validOutPort) {
console.log(portInvalidMsg[0]); // `outPort` is not an integer. console.log(portInvalidMsg[0]); // `outPort` is not an integer.
return isValid = false; return isValid = false;
} }
if (!(validOutPort > 0 && validOutPort <= 65535)) { if (!(validOutPort > 0 && validOutPort <= 65535)) {
console.log(portInvalidMsg[1]); // `outPort` is not within port range. console.log(portInvalidMsg[1]);
// `outPort` is not within port range.
return isValid = false; return isValid = false;
} }
} }
// Enter if `inPort` is defined. This happens for `up proxy` where inbound port is required. // Enter if `inPort` is defined. This happens for `up proxy` where
// inbound port is required.
if (typeof inPort !== undefined) { if (typeof inPort !== undefined) {
if (!validInPort || !validOutPort) { if (!validInPort || !validOutPort) {
console.log(portInvalidMsg[0]); // Either `inPort` or `outPort` is not an integer. console.log(portInvalidMsg[0]);
// Either `inPort` or `outPort` is not an integer.
return isValid = false; return isValid = false;
} }
if (typeof outPort !== undefined) { if (typeof outPort !== undefined) {
if (!((validInPort > 0 && validInPort <= 65535) && (validOutPort > 0 && validOutPort <= 65535))) { if (!(
console.log(portInvalidMsg[1]); // Either `inPort` or `outPort` are not within port range. (validInPort > 0 && validInPort <= 65535) &&
(validOutPort > 0 && validOutPort <= 65535)
)) {
console.log(portInvalidMsg[1]);
// Either `inPort` or `outPort` are not within port range.
return isValid = false; return isValid = false;
} }
} }
return isValid; // If any of the `if`s were true, `isInvalid = false`. If not, `isInvalid = true`. return isValid;
// If any of the `if`s were true, `isInvalid = false`.
// If not, `isInvalid = true`.
} }
} }

Loading…
Cancel
Save