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

Add npm run quality script, Update Readme #97

Merged
merged 4 commits into from
Oct 31, 2018
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .buddyrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"detectObjects": false,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

please clarify the use of next two lines.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

According to the documentation :

detectObjects    -    detect object expressions and properties
enforceConst     -    require literals to be defined using const

I think we can switch both to true.

"enforceConst": false,
"ignore": [0, 1, 2, 3],
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

please remove this ignore statement.

"reporter": "detailed"
}
5 changes: 3 additions & 2 deletions .eslintignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
/node_modules
/coverage
node_modules/*
coverage/*
test/feature/*
17 changes: 17 additions & 0 deletions .eslintrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
{
"extends": "airbnb-base",
"env" : {
"node": true,
"mocha": true
},
"rules": {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

please clarify the reason for using the rule.

"max-lines-per-function" : ["error", 30],
"no-plusplus" : ["error", { "allowForLoopAfterthoughts": true }],
"no-unused-vars": [
"error",
{
"varsIgnorePattern": "should|expect|Before|After|Given"
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

avoid this rule using a plug-in?

}
]
}
}
6 changes: 0 additions & 6 deletions .eslintrc.json

This file was deleted.

9 changes: 9 additions & 0 deletions .jsinspectrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"threshold": 30,
"identifiers": true,
"literals": true,
"color": true,
"ignore": "coverage",
"minInstances": 2,
"truncate": 100
}
1 change: 1 addition & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,4 @@ script:
- npm run post-unit
- npm run integration
- npm run post-integration
- npm run quality
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,11 @@ A client command line interface for submissions to [AutolabJS](https://github.co
* `autolabjs exit` - Logout off AutolabJS
* `autolabjs prefs changeserver [ --type ms --host <host> --port <port>]` - To change the host for main server.
* `autolabjs prefs changeserver [ --type gitlab --host <host>]` - To change the host for gitlab server.
* `autolabjs prefs logger [--maxsize <size> --blacklist <keyword>]` - To change logger file's maxsize and add keyword to log blacklist
* `autolabjs prefs show` - Show the saved preferences
* `autolabjs eval [-l <lab_name> --lang <language>]` - To submit your code for evaluation
* `autolabjs help` - Print help manual
* `autolabjs <command> [options] -v` - To print debug/error log messages to log file (Default location `~/.autolabjs/cli.log`)

## License ##
GNU General Public License
8 changes: 5 additions & 3 deletions lib/cli/input/eval.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
const inquirer = require('inquirer');
const path = require('path');
const fs = require('fs');
const PromptGenerator = require('../../utils/PromptGenerator');
const preferenceManager = require('../../utils/preference-manager');

const defaultPrefPath = path.join(__dirname, '../../../default-prefs.json');
const defaultPrefs = JSON.parse(require('fs').readFileSync(defaultPrefPath, 'utf8'));
const defaultPrefs = JSON.parse(fs.readFileSync(defaultPrefPath, 'utf8'));

const { supportedLanguages } = defaultPrefs;
const { logger } = require('../../utils/logger');
Expand Down Expand Up @@ -50,15 +51,16 @@ const getSubmitInfo = () => {

const getIdNo = (options) => {
logger.moduleLog('debug', 'Eval Input', 'Fetching id to submit.');
const username = preferenceManager.getPreference({ name: 'gitLabPrefs' }).username;
const { username } = preferenceManager.getPreference({ name: 'gitLabPrefs' });
if (username === 'root') {
logger.moduleLog('debug', 'Eval Input', `Root user detected, passing up the ID provided : ${options.i}.`);
return options.i || '';
}
return username;
};

const isValidOptions = options => options.l && options.lang && supportedLanguages.indexOf(options.lang) !== -1;
const isValidOptions = options => options.l && options.lang
&& supportedLanguages.indexOf(options.lang) !== -1;

const getInput = async (args, options) => {
let evalOptions = {};
Expand Down
1 change: 0 additions & 1 deletion lib/cli/input/init.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
const inquirer = require('inquirer');
const PromptGenerator = require('../../utils/PromptGenerator');
const { logger } = require('../../utils/logger');

const getLengthValidator = invalidMessage => (value) => {
if (value.length) {
Expand Down
18 changes: 13 additions & 5 deletions lib/cli/input/prefs.js
Original file line number Diff line number Diff line change
Expand Up @@ -87,16 +87,20 @@ const changeGitlab = (host) => {
};

const changeServer = async (options) => {
let { host, port, type } = options;
const { host, port } = options;
let { type } = options;
if (!type) {
const typePrompt = prefPrompts.getServerTypePrompt();
type = (await inquirer.prompt(typePrompt)).type;
({ type } = (await inquirer.prompt(typePrompt)));
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why brackets?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We have discussed this, sir, but for having everything in a single thread; the MDN documentation says:

The parentheses ( ... ) around the assignment statement are required when using object literal destructuring assignment without a declaration.

{a, b} = {a: 1, b: 2} is not valid stand-alone syntax, as the {a, b} on the left-hand side is considered a block and not an object literal.

However, ({a, b} = {a: 1, b: 2}) is valid, as is var {a, b} = {a: 1, b: 2}

NOTE: Your ( ... ) expression needs to be preceded by a semicolon or it may be used to execute a function on the previous line.

}
if (type === 'ms') {
return changeMainServer(host, port);
} if (type === 'gitlab') {
return changeGitlab(host);
}
return {
name: 'invalid_server',
};
};

const changeLogger = async (options) => {
Expand Down Expand Up @@ -124,15 +128,19 @@ const changeLogger = async (options) => {
const getInput = async (args, options) => {
switch (args.preference) {
case 'changelang':
return await changeLang(options);
return changeLang(options);
case 'changeserver':
return await changeServer(options);
return changeServer(options);
case 'show':
return {
name: 'show_prefs',
};
case 'logger':
return await changeLogger(options);
return changeLogger(options);
default:
return {
name: 'invalid_command',
};
}
};

Expand Down
8 changes: 6 additions & 2 deletions lib/cli/input/prefsprompt.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
const inquirer = require('inquirer');
const path = require('path');
const fs = require('fs');

const validator = require('validator');
const PromptGenerator = require('../../utils/PromptGenerator');
const preferenceManager = require('../../utils/preference-manager');

const defaultPrefPath = path.join(__dirname, '../../../default-prefs.json');
const defaultPrefs = JSON.parse(require('fs').readFileSync(defaultPrefPath, 'utf8'));
const defaultPrefs = JSON.parse(fs.readFileSync(defaultPrefPath, 'utf8'));

const { supportedLanguages } = defaultPrefs;

Expand Down Expand Up @@ -145,12 +146,15 @@ const changeBlacklist = async () => {

const changeLoggerPrompt = async () => {
const loggerPrompt = getLoggerPreferncePrompt();
const type = (await inquirer.prompt(loggerPrompt)).type;
const { type } = (await inquirer.prompt(loggerPrompt));
if (type === 'maxsize') {
return changeMaxSize();
} if (type === 'blacklist') {
return changeBlacklist();
}
return {
name: 'invalid_logger_pref',
};
};

module.exports = {
Expand Down
14 changes: 10 additions & 4 deletions lib/cli/output/eval.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,12 +23,16 @@ const onSubmissionPending = () => {
};

const printTableAndGetScore = (data) => {
const testCaseColWidth = 15;
const statusColWidth = 25;
const scoreColWidth = 15;

const table = new Table({
head: [chalk.cyan('Test Case #'), chalk.cyan('Status'), chalk.cyan('Score')],
colWidths: [15, 25, 15],
colWidths: [testCaseColWidth, statusColWidth, scoreColWidth],
});
let totalScore = 0;
for (i = 0; i < data.marks.length; i++) {
for (let i = 0; i < data.marks.length; ++i) {
totalScore += +data.marks[i];
table.push([(i + 1), data.comment[i], data.marks[i]]);
}
Expand All @@ -37,9 +41,9 @@ const printTableAndGetScore = (data) => {
};

const printStatusAndLog = (data, totalScore) => {
logger.moduleLog('debug', 'Eval Output', `Evaluation logs: ${new Buffer(data.log, 'base64').toString()}.`);
logger.moduleLog('debug', 'Eval Output', `Evaluation logs: ${Buffer.from(data.log, 'base64').toString()}.`);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The Buffer constructor is different depending on the type of its argument, and not validating such arguments might lead to memory disclosure and denial of service. So eslint enforces the use of Buffer.from() or Buffer.alloc() instead.

ref


console.log(`\n${chalk.yellow('Log :\n')}${new Buffer(data.log, 'base64').toString()}`);
console.log(`\n${chalk.yellow('Log :\n')}${Buffer.from(data.log, 'base64').toString()}`);
if (data.status !== 0) {
console.log(chalk.red('Penalty : ') + data.penalty);
} else if (data.status === 0) {
Expand Down Expand Up @@ -71,6 +75,8 @@ const sendOutput = (event) => {
stopSpinner();
onScores(event.details);
break;
default:
console.log(chalk.red('\nInvalid Event'));
}
};

Expand Down
2 changes: 2 additions & 0 deletions lib/cli/output/exit.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ const sendOutput = (event) => {
case 'logout_success':
sendLogoutMessage();
break;
default:
console.log(chalk.red('\nInvalid Event'));
}
};

Expand Down
6 changes: 4 additions & 2 deletions lib/cli/output/init.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,7 @@ const sendSuccessWelcome = (user) => {
};

const sendError = (error) => {
error = chalk.red(error);
console.log(error);
console.log(chalk.red(error));
};

const handleResponse = (status) => {
Expand All @@ -54,6 +53,9 @@ const sendOutput = (event) => {
stopSpinner();
handleResponse(event.details);
break;

default:
console.log(chalk.red('\nInvalid Event'));
}
};

Expand Down
21 changes: 15 additions & 6 deletions lib/cli/output/prefs.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,11 @@ const chalk = require('chalk');
const Table = require('cli-table');

const showPrefs = (prefs) => {
const prefsColWidth = 25;
const valuesColWidth = 27;
const table = new Table({
head: [chalk.cyan('Preferences'), chalk.cyan('Values')],
colWidths: [25, 27],
colWidths: [prefsColWidth, valuesColWidth],
});
table.push(
['Gitlab host', prefs.gitlab_host],
Expand All @@ -18,17 +20,21 @@ const showPrefs = (prefs) => {
console.log(table.toString());
};

const showServerChange = (event) => {
if (event.details.type === 'ms') {
console.log(chalk.green(`Your main server has been changed to ${event.details.host} at port ${event.details.port}`));
} else if (event.details.type === 'gitlab') {
console.log(chalk.green(`Your gitlab server has been changed to ${event.details.host}`));
}
};

const sendOutput = (event) => {
switch (event.name) {
case 'lang_changed':
console.log(chalk.green(`Your submission language has been changed to ${event.details.lang}`));
break;
case 'server_changed':
if (event.details.type === 'ms') {
console.log(chalk.green(`Your main server has been changed to ${event.details.host} at port ${event.details.port}`));
} else if (event.details.type === 'gitlab') {
console.log(chalk.green(`Your gitlab server has been changed to ${event.details.host}`));
}
showServerChange(event);
break;
case 'show_prefs':
showPrefs(event.details);
Expand All @@ -47,6 +53,9 @@ const sendOutput = (event) => {
break;
case 'invalid_logger_prefs':
console.log(chalk.red('Keyword already exixts, please provide valid blacklist keyword'));
break;
default:
console.log(chalk.red('\nInvalid Event'));
}
};

Expand Down
4 changes: 2 additions & 2 deletions lib/controller/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ const { logger } = require('../utils/logger');
const init = require('./init');
const exit = require('./exit');
const prefs = require('./prefs');
const eval = require('./eval');
const evaluate = require('./eval');


const start = async () => {
Expand All @@ -20,7 +20,7 @@ const start = async () => {
init.addTo(program);
exit.addTo(program);
prefs.addTo(program);
eval.addTo(program);
evaluate.addTo(program);

await program.parse(process.argv);
};
Expand Down
13 changes: 10 additions & 3 deletions lib/model/eval.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ const { logger } = require('../utils/logger');

const connectToSocket = () => {
const cliPrefs = preferenceManager.getPreference({ name: 'cliPrefs' });
const host = cliPrefs.main_server.host;
const port = cliPrefs.main_server.port;
const { host } = cliPrefs.main_server;
const { port } = cliPrefs.main_server;

logger.moduleLog('debug', 'Eval Model', `Opening a socket connection to http://${host}:${port}`);

Expand All @@ -21,7 +21,7 @@ const getRequestArray = (evalOptions) => {
return [idNo, lab, commitHash, lang];
};

const socketEventHandler = (event, socket, data, callback) => {
const socketEventHandler = (event, socket, data, callback) => {
let response;
switch (event) {
case 'invalid':
Expand All @@ -45,6 +45,13 @@ const socketEventHandler = (event, socket, data, callback) => {
},
};
break;
default:
response = {
name: event,
details: {
...data,
},
};
}

logger.moduleLog('error', 'Eval Model', data);
Expand Down
9 changes: 6 additions & 3 deletions lib/model/prefs.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ const preferenceManager = require('../utils/preference-manager');

const eventForShowPref = (changePrefEvent) => {
const cliPrefs = preferenceManager.getPreference({ name: 'cliPrefs' });
changePrefEvent.details = {
const details = {
gitlab_host: cliPrefs.gitlab.host,
mainserver_host: cliPrefs.main_server.host,
mainserver_port: cliPrefs.main_server.port,
Expand All @@ -11,7 +11,10 @@ const eventForShowPref = (changePrefEvent) => {
logger_location: cliPrefs.logger.logLocation,
logger_blacklist: cliPrefs.logger.blacklist,
};
return changePrefEvent;
return {
...changePrefEvent,
details,
};
};

const getPrefsObjectToStore = (prefsName, values) => ({
Expand Down Expand Up @@ -77,7 +80,7 @@ const storePrefs = (changePrefEvent) => {
} else if (changePrefEvent.name === 'server_changed') {
storeServer(changePrefEvent.details);
} else if (changePrefEvent.name === 'show_prefs') {
changePrefEvent = eventForShowPref(changePrefEvent);
return eventForShowPref(changePrefEvent);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The function storePrefs was modifying the input argument changePrefEvent storing and then returning it. Instead, the above modification returns the new value directly.

} else if (changePrefEvent.name === 'logger_pref_changed') {
storeLoggerPref(changePrefEvent.details);
}
Expand Down
Loading