-
Notifications
You must be signed in to change notification settings - Fork 10
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
[WIP] Implements show
commands
#117
Open
mukkachaitanya
wants to merge
7
commits into
AutolabJS:dev
Choose a base branch
from
mukkachaitanya:show-commands
base: dev
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
8140f7b
Adds show status command
mukkachaitanya 1ec202c
Implements show score command
mukkachaitanya 3b89a7c
Adds unit tests
mukkachaitanya a90d21e
Minor logic changes
mukkachaitanya 81d6368
Fixes buddy and npm-check issues
mukkachaitanya d9b9487
Adds integration tests for show commands
mukkachaitanya afde03d
Adds feature tests for show commands
mukkachaitanya File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,58 @@ | ||
const inquirer = require('inquirer'); | ||
const PromptGenerator = require('../../utils/PromptGenerator'); | ||
|
||
const getPromptGenerator = (name, type, message) => { | ||
const promptGenerator = new PromptGenerator(); | ||
promptGenerator.addProperty('name', name); | ||
promptGenerator.addProperty('type', type); | ||
promptGenerator.addProperty('message', message); | ||
return promptGenerator; | ||
}; | ||
|
||
const getScorePrompt = async () => { | ||
const prompts = [ | ||
getPromptGenerator('lab', 'input', 'Enter the lab whose score has to be shown:').getPrompt(), | ||
getPromptGenerator('id', 'input', 'Enter the student id: (optional)').getPrompt(), | ||
]; | ||
const scoreOptions = await inquirer.prompt(prompts); | ||
return { | ||
name: 'score', | ||
details: { | ||
lab: scoreOptions.lab, | ||
id: scoreOptions.id, | ||
}, | ||
}; | ||
}; | ||
|
||
const getScoreOptions = (options) => { | ||
const lab = options.l; | ||
const id = options.i; | ||
if (!lab) { | ||
return getScorePrompt(); | ||
} | ||
return { | ||
name: 'score', | ||
details: { | ||
lab, id, | ||
}, | ||
}; | ||
}; | ||
|
||
const getInput = async (args, options) => { | ||
switch (args.statistic) { | ||
case 'status': | ||
return { | ||
name: 'status', | ||
}; | ||
case 'score': | ||
return getScoreOptions(options); | ||
default: | ||
return { | ||
name: 'invalid_command', | ||
}; | ||
} | ||
}; | ||
|
||
module.exports = { | ||
getInput, | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,101 @@ | ||
const _ = require('lodash'); | ||
const chalk = require('chalk'); | ||
const childProcess = require('child_process'); | ||
const fs = require('fs-extra'); | ||
const Table = require('cli-table'); | ||
const { Spinner } = require('cli-spinner'); | ||
const util = require('util'); | ||
|
||
const spinner = new Spinner('Fetching request results, please wait...'); | ||
const startSpinner = () => { | ||
spinner.setSpinnerString(0); | ||
spinner.start(); | ||
}; | ||
|
||
const stopSpinner = () => { | ||
spinner.stop(); | ||
}; | ||
|
||
const showScoreLess = async (scoreboard) => { | ||
const file = '/tmp/autolabjs/scoreboard'; | ||
try { | ||
await fs.outputFile(file, scoreboard); | ||
childProcess.spawn('cat /tmp/autolabjs/scoreboard | less -r', { | ||
stdio: 'inherit', | ||
shell: true, | ||
}); | ||
console.log('\n'); | ||
} catch (err) { | ||
console.log(chalk.red('Can not display scores due to filesystem error. Try again.')); | ||
} | ||
}; | ||
|
||
const showScore = (details) => { | ||
const { scores } = details; | ||
const posColWidth = 10; | ||
const idColWidth = 15; | ||
const scoreColWidth = 10; | ||
const timeColWidth = 23; | ||
|
||
const threshold = 1; | ||
|
||
const table = new Table({ | ||
head: ['Position', 'ID Number', 'Score', 'Time'], | ||
colWidths: [posColWidth, idColWidth, scoreColWidth, timeColWidth], | ||
}); | ||
|
||
const scoreboard = _.zipWith(scores, _.range(1, scores.length + 1), (score, position) => { | ||
score.unshift(position); | ||
return _.map(score, val => val || ''); | ||
}); | ||
|
||
table.push(...scoreboard); | ||
if (scores.length <= threshold) { | ||
console.log(`\n${table.toString()}`); | ||
} else { | ||
showScoreLess(table.toString()); | ||
} | ||
}; | ||
|
||
const handleHttpFailure = (details) => { | ||
const httpError = 4; | ||
if (details.code === httpError) { | ||
console.log(chalk.red('\nPlease check your network connection')); | ||
} else { | ||
console.log(chalk.red('\nInvalid query')); | ||
} | ||
}; | ||
|
||
const sendOutput = async (event) => { | ||
const lineBreakLength = 80; | ||
switch (event.name) { | ||
case 'fetching_results': | ||
startSpinner(); | ||
break; | ||
case 'status': | ||
stopSpinner(); | ||
console.log(`\n${util.inspect(event.details.status, | ||
{ compact: true, breakLength: lineBreakLength, colors: true })}`); | ||
break; | ||
case 'score': | ||
stopSpinner(); | ||
await showScore(event.details); | ||
break; | ||
case 'invalid_lab': | ||
stopSpinner(); | ||
console.log(chalk.red('\nInvalid Lab')); | ||
break; | ||
case 'httpFailure': | ||
stopSpinner(); | ||
handleHttpFailure(event.details); | ||
break; | ||
default: | ||
stopSpinner(); | ||
console.log(chalk.red('\nInvalid Event')); | ||
break; | ||
} | ||
}; | ||
|
||
module.exports = { | ||
sendOutput, | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,36 @@ | ||
const showInput = require('../cli/input/show'); | ||
const showOutput = require('../cli/output/show'); | ||
const showModel = require('../model/show'); | ||
|
||
const showValidate = require('./validate/show'); | ||
|
||
const onShowResults = (showResult) => { | ||
showOutput.sendOutput(showResult); | ||
}; | ||
|
||
const onShow = async (args, options, logger) => { | ||
logger.moduleLog('info', 'Show', 'Show command invoked.'); | ||
|
||
const showOptions = await showInput.getInput(args, options); | ||
const validatedOptions = showValidate.validate(showOptions); | ||
|
||
logger.moduleLog('debug', 'Show', 'Show request for'); | ||
logger.moduleLog('debug', 'Show', validatedOptions); | ||
|
||
showOutput.sendOutput({ name: 'fetching_results' }); | ||
|
||
showModel.show(validatedOptions, onShowResults); | ||
}; | ||
|
||
const addTo = (program) => { | ||
program | ||
.command('show', 'Shows server status and lab scores') | ||
.argument('<statistic>', 'Argument for show command') | ||
.option('-l <lab>', 'Lab to show score') | ||
.option('-i <id>', 'Student ID to show the score') | ||
.action(onShow); | ||
}; | ||
|
||
module.exports = { | ||
addTo, | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
const validateScoreEvent = (event) => { | ||
if (!event.details.lab) { | ||
return { | ||
name: 'invalid_options', | ||
}; | ||
} | ||
return event; | ||
}; | ||
|
||
const validate = (showEvent) => { | ||
switch (showEvent.name) { | ||
case 'score': | ||
return validateScoreEvent(showEvent); | ||
default: | ||
return showEvent; | ||
} | ||
}; | ||
|
||
module.exports = { | ||
validate, | ||
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,106 @@ | ||
const requestPromise = require('request-promise'); | ||
const _ = require('lodash'); | ||
const preferenceManager = require('../utils/preference-manager'); | ||
const { logger } = require('../utils/logger'); | ||
|
||
const fetchQuery = async (host, port, query) => { | ||
const options = { | ||
method: 'GET', | ||
uri: `https://${host}:${port}${query}`, | ||
rejectUnauthorized: false, | ||
}; | ||
|
||
logger.moduleLog('debug', 'Show Model', `GET request to ${options.uri}`); | ||
|
||
return requestPromise(options).json(); | ||
}; | ||
|
||
const getErrorMessage = (e) => { | ||
const httpError = 4; | ||
logger.moduleLog('error', 'Init Model', `Error ; ${e || httpError}`); | ||
return { | ||
name: 'httpFailure', | ||
details: { | ||
code: e.statusCode || httpError, | ||
}, | ||
}; | ||
}; | ||
|
||
const getStatus = async (callback) => { | ||
let response; | ||
const { host, port } = preferenceManager.getPreference({ name: 'cliPrefs' }).main_server; | ||
try { | ||
const status = await fetchQuery(host, port, '/status'); | ||
logger.moduleLog('debug', 'Show Model', 'Fetched status..'); | ||
logger.moduleLog('debug', 'Show Model', status); | ||
response = { | ||
name: 'status', | ||
details: { | ||
status, | ||
}, | ||
}; | ||
} catch (e) { | ||
response = getErrorMessage(e); | ||
} | ||
|
||
callback(response); | ||
}; | ||
|
||
const getFormattedScores = (scores, id) => { | ||
if (scores === false) { | ||
logger.moduleLog('debug', 'Show Model', 'Invalid lab'); | ||
return { | ||
name: 'invalid_lab', | ||
}; | ||
} | ||
let filteredScores = scores; | ||
if (id) { | ||
filteredScores = _.find(scores, ['id_no', id]); | ||
return { | ||
name: 'score', | ||
details: { | ||
scores: [_.values(filteredScores)], | ||
}, | ||
}; | ||
} | ||
return { | ||
name: 'score', | ||
details: { | ||
scores: _.map(filteredScores, _.values), | ||
}, | ||
}; | ||
}; | ||
|
||
const getScore = async (options, callback) => { | ||
const { lab, id } = options; | ||
|
||
let response; | ||
const { host, port } = preferenceManager.getPreference({ name: 'cliPrefs' }).main_server; | ||
try { | ||
const scores = await fetchQuery(host, port, `/scoreboard/${lab}`); | ||
logger.moduleLog('debug', 'Show Model', `Fetched scores for ${lab}`); | ||
response = getFormattedScores(scores, id); | ||
} catch (e) { | ||
response = getErrorMessage(e); | ||
} | ||
|
||
callback(response); | ||
}; | ||
|
||
const show = (options, callback) => { | ||
switch (options.name) { | ||
case 'status': | ||
getStatus(callback); | ||
break; | ||
case 'score': | ||
getScore(options.details, callback); | ||
break; | ||
default: | ||
callback(options); | ||
break; | ||
} | ||
}; | ||
|
||
module.exports = { | ||
show, | ||
}; |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
There is no validation logic here. Are you planning to add more later?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yes, sir. The status command had not validation.