Skip to content

Commit

Permalink
Merge pull request #49 from OperationSpark/fix-color
Browse files Browse the repository at this point in the history
Fix `cli-color` to invoke instance instead of using prototype
  • Loading branch information
ptbarnum4 authored Feb 4, 2022
2 parents 9589bb6 + 99f993d commit 8e3ef9c
Show file tree
Hide file tree
Showing 24 changed files with 865 additions and 627 deletions.
31 changes: 16 additions & 15 deletions .eslintrc.js
Original file line number Diff line number Diff line change
@@ -1,22 +1,23 @@
module.exports = {
"extends": "airbnb-base",
"plugins": ["import"],
"rules": {
extends: 'airbnb-base',
plugins: ['import'],
rules: {
// enable additional rules
"quotes": ["error", "single"],
"semi": ["error", "always"],
quotes: ['error', 'single'],
semi: ['error', 'always'],

// disable rules from base configurations
"no-underscore-dangle": "off",
"no-unused-expressions": "off",
"comma-dangle": "off",
"no-console": "off",
"no-use-before-define": "off",
"func-names": "off",
"consistent-return": "off",
"prefer-arrow-callback": "off",
'no-underscore-dangle': 'off',
'no-unused-expressions': 'off',
'comma-dangle': 'off',
'no-console': 'off',
'no-use-before-define': 'off',
'func-names': 'off',
'consistent-return': 'off',
'prefer-arrow-callback': 'off',
'arrow-parens': 'as-needed',
// Windows friendly -- does not show errors on every line of every file
"no-unused-vars": 1,
"linebreak-style": 0
'no-unused-vars': 1,
'linebreak-style': 0
}
};
38 changes: 21 additions & 17 deletions controller/github.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
require('cli-color');
const clc = require('cli-color');
const fs = require('fs');
const util = require('util');
const prompt = require('inquirer').prompt;
Expand Down Expand Up @@ -32,15 +32,15 @@ let _opspark;
// TODO : consider the "module level" vars, like _client in this implementation, are they necessary.

function getCredentials() {
console.log('Getting credentials. . .'.yellow);
console.log(clc.yellow('Getting credentials. . .'));
return new Promise(function (res, rej) {
if (userInfoExists()) {
const creds = {
login: grabLocalLogin(),
id: grabLocalUserID(),
token: grabLocalAuthToken()
};
console.log('Good to go!'.green);
console.log(clc.green('Good to go!'));
res(creds);
} else {
authorizeUser()
Expand Down Expand Up @@ -83,7 +83,7 @@ function promptForUserInfo() {
name: 'token',
type: 'token',
hidden: true,
conform: () => true,
conform: () => true
}
],
function (user) {
Expand All @@ -97,7 +97,7 @@ module.exports.promptForUserInfo = promptForUserInfo;

function writeAuth(auth) {
deleteAuth();
console.log('Writing auth. . .'.yellow);
console.log(clc.yellow('Writing auth. . .'));
return new Promise(function (res, rej) {
ensureApplicationDirectory();
fsJson.saveSync(authFilePath, { token: auth.token });
Expand All @@ -108,7 +108,7 @@ function writeAuth(auth) {
module.exports.writeAuth = writeAuth;

function obtainAndWriteAuth({ username, password }) {
console.log('Authorizing with GitHub. . .'.yellow);
console.log(clc.yellow('Authorizing with GitHub. . .'));
return new Promise(function (res, rej) {
const note = getNoteForHost();
const cmd = createGithubToken(username, password, note);
Expand All @@ -117,10 +117,9 @@ function obtainAndWriteAuth({ username, password }) {
if (_auth.message) {
rej(_auth);
} else {
console.log('GitHub login succeeded!'.green);
console.log(clc.green('GitHub login succeeded!'));
_auth.username = username;
writeAuth(_auth)
.then(() => res(_auth));
writeAuth(_auth).then(() => res(_auth));
}
});
});
Expand All @@ -130,7 +129,7 @@ module.exports.obtainAndWriteAuth = obtainAndWriteAuth;

function writeUser(auth) {
deleteUser();
console.log('Writing user. . .'.yellow);
console.log(clc.yellow('Writing user. . .'));
return new Promise(function (res, rej) {
const cmd = getGithubID(auth.token);
exec(cmd, function (err, stdout, stderr) {
Expand All @@ -157,7 +156,7 @@ function writeUser(auth) {
module.exports.writeUser = writeUser;

function obtainAndWriteUser(user) {
console.log('Grabbing user. . .'.yellow);
console.log(clc.yellow('Grabbing user. . .'));
return new Promise(function (res, rej) {
getOrCreateClient()
.then(function (client) {
Expand Down Expand Up @@ -197,8 +196,8 @@ function getOrObtainAuth() {
if (response.statusCode === 200) {
res(_auth);
} else {
console.log('Hmm, something\'s not right!'.green);
console.log('Let\'s try to login to GitHub again:'.green);
console.log(clc.green("Hmm, something's not right!"));
console.log(clc.green("Let's try to login to GitHub again:"));
deleteUserInfo();
authorizeUser();
}
Expand Down Expand Up @@ -297,7 +296,7 @@ function deauthorizeUser() {
// .then(deleteAuth)
.then(deleteUserInfo)
.then(() => {
console.log('Successfully logged out!'.blue);
console.log(clc.blue('Successfully logged out!'));
res(true);
})
.catch(err => rej(`${err}`.red));
Expand All @@ -307,9 +306,14 @@ function deauthorizeUser() {
module.exports.deauthorizeUser = deauthorizeUser;

function deleteToken({ username, password }) {
console.log('Deleting token. . .'.red);
console.log(clc.red('Deleting token. . .'));
return new Promise(function (res, rej) {
const cmd = deleteGithubToken(username, password, config.userAgent, grabLocalAuthID());
const cmd = deleteGithubToken(
username,
password,
config.userAgent,
grabLocalAuthID()
);
exec(cmd, function (err, stdout, stderr) {
if (stdout.indexOf('message') > -1) return rej(stdout);
res(stdout);
Expand All @@ -332,7 +336,7 @@ function deleteUser() {
module.exports.deleteUser = deleteUser;

function deleteUserInfo() {
console.log('Deleting files. . .'.red);
console.log(clc.red('Deleting files. . .'));
deleteAuth();
deleteUser();
}
Expand Down
37 changes: 18 additions & 19 deletions controller/greenlight.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
require('cli-color');
const clc = require('cli-color');
const rp = require('request-promise');

const github = require('./github');
Expand All @@ -11,27 +11,27 @@ const URI = GREENLIGHT;
module.exports.URI = URI;

function getSessions({ id }) {
console.log('Grabbing enrolled sessions. . .'.yellow);
console.log(clc.yellow('Grabbing enrolled sessions. . .'));
const options = {
method: 'GET',
uri: `${URI}/api/os/install`,
qs: {
id,
},
id
}
};
return rp(options);
}

module.exports.getSessions = getSessions;

function getGradable({ id }) {
console.log('Grabbing enrolled sessions. . .'.yellow);
console.log(clc.yellow('Grabbing enrolled sessions. . .'));
const options = {
method: 'GET',
uri: `${URI}/api/os/submit`,
qs: {
id,
},
id
}
};
return rp(options);
}
Expand All @@ -43,26 +43,25 @@ function sendGrade({ gist, project }) {
id: github.grabLocalUserID().toString(),
requirementId: project._id,
sessionId: project._session,
url: gist.files['grade.txt'].raw_url,
url: gist.files['grade.txt'].raw_url
};

const options = {
body,
method: 'POST',
uri: `${URI}/api/os/grade`,
json: true,
json: true
};

return rp(options)
.then((response) => {
if (response.status === 200) {
console.log(response.message.blue);
} else {
console.log(response.reason.red);
console.log(response.details.red);
}
return gist.url;
});
return rp(options).then(response => {
if (response.status === 200) {
console.log(response.message.blue);
} else {
console.log(response.reason.red);
console.log(response.details.red);
}
return gist.url;
});
}

module.exports.sendGrade = sendGrade;
20 changes: 10 additions & 10 deletions controller/handshake.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
require('cli-color');
const clc = require('cli-color');
const fs = require('fs');
const mkdirp = require('mkdirp');
const fsJson = require('fs-json')();
Expand All @@ -22,7 +22,7 @@ function readHandshake() {
// Checks if directory exists and creates if not
function checkForDirectory(path) {
if (!fs.existsSync(path)) {
console.log('Creating new directory'.yellow);
console.log(clc.yellow('Creating new directory'));
mkdirp.sync(path);
}
}
Expand All @@ -48,23 +48,23 @@ function storeCreds(body, hash) {
checkForDirectory(filePath);

if (fs.existsSync(path)) {
console.log('Hey, this file is already there!'.red);
console.log(clc.red('Hey, this file is already there!'));
view.inquireForInput('Overwrite file? (y/n)', (err, input) => {
console.log(input);
if (err) {
console.warn('Something went wrong! Run that code again.'.red);
console.warn(clc.red('Something went wrong! Run that code again.'));
} else if (input.toLowerCase()[0] === 'y') {
console.warn('Rewriting. . .'.yellow);
console.warn(clc.yellow('Rewriting. . .'));
fs.writeFileSync(path, JSON.stringify(userInfo));
console.warn('All done!'.green);
console.warn(clc.green('All done!'));
} else {
console.warn('Exiting without overwrite.'.green);
console.warn(clc.green('Exiting without overwrite.'));
}
});
} else {
console.warn('Writing file. . .');
fsJson.saveSync(path, JSON.stringify(userInfo));
console.warn('All done!'.green);
console.warn(clc.green('All done!'));
}
}

Expand All @@ -74,9 +74,9 @@ function greenlightRequest(hash) {
method: 'POST',
url: `${URI}/api/os/verify`,
body: {
authorization: hash,
authorization: hash
},
json: true,
json: true
};
rp(options)
.then(res => storeCreds(res, hash))
Expand Down
41 changes: 26 additions & 15 deletions controller/init.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
require('cli-color');
const clc = require('cli-color');
const fs = require('fs');
const url = require('url');
const cheerio = require('cheerio');
Expand All @@ -10,47 +10,58 @@ const configWebsite = require('../config.json').website;
const configPortfolio = require('../config.json').portfolio;
const { home, cloud9User, codenvyUser } = require('./env');

const jQueryCdnScript = ' <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js\"></script>\n';
const portfolioScript = " <script id=\"portfolioScript\">$(document).ready(function() {$.getJSON('projects/projects.json').then(function(data) { data.projects.forEach(function(project){ $('#portfolio').append('<li><a href=\"projects/' + project.name + '/\">' + project.title + ' : ' + project.description + '</a></li>'); }); }); });</script>\n </body>";
require('cli-color');
const jQueryCdnScript =
' <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>\n';
const portfolioScript =
" <script id=\"portfolioScript\">$(document).ready(function() {$.getJSON('projects/projects.json').then(function(data) { data.projects.forEach(function(project){ $('#portfolio').append('<li><a href=\"projects/' + project.name + '/\">' + project.title + ' : ' + project.description + '</a></li>'); }); }); });</script>\n </body>";

let rootDirectory = './';
let githubDir;

if (cloud9User) {
githubDir = fs.readdirSync(`${home()}/environment`)
githubDir = fs
.readdirSync(`${home()}/environment`)
.filter(dir => /[\w]+\.github\.io/.test(dir))[0];
rootDirectory = `${home()}/environment/${githubDir}`;
} else if (codenvyUser) {
rootDirectory = codenvyUser;
githubDir = fs.readdirSync(`${codenvyUser}/`).filter(dir => /[\w]+\.github\.io/.test(dir))[0];
githubDir = fs
.readdirSync(`${codenvyUser}/`)
.filter(dir => /[\w]+\.github\.io/.test(dir))[0];
rootDirectory = `${rootDirectory}/${githubDir}`;
}

module.exports.jQueryCdnScript = jQueryCdnScript;
module.exports.portfolioScript = portfolioScript;

function login() {
github.getCredentials()
.then(() => console.log('Have fun!'.blue))
.catch(err => console.error('Failure getting credentials\n'.red, err));
github
.getCredentials()
.then(() => console.log(clc.blue('Have fun!')))
.catch(err => console.error(clc.red('Failure getting credentials\n'), err));
}
module.exports.login = login;

function portfolio(filepath = configPortfolio.filepath) {
if (!fs.existsSync(filepath)) return console.log(configPortfolio.help.incomplete.red);
if (!fs.existsSync(filepath))
return console.log(configPortfolio.help.incomplete.red);
const html = fs.readFileSync(filepath, 'utf8');
const $ = cheerio.load(html);
const portfolioListTag = $('#portfolio')[0];
if (!portfolioListTag) return console.log(configPortfolio.help.noPortfolioList.red);
if (!portfolioListTag)
return console.log(configPortfolio.help.noPortfolioList.red);
const portfolioScriptTag = $('#portfolioScript')[0];
if (portfolioScriptTag) return console.log(configPortfolio.help.portfolioScriptTagExists.red);
if (portfolioScriptTag)
return console.log(configPortfolio.help.portfolioScriptTagExists.red);
const result = html.replace(/<\/body>/g, jQueryCdnScript + portfolioScript);
try {
fs.writeFileSync(filepath, result, 'utf8');
console.log('portfolio.html has been initialized!');
} catch (err) {
console.log('An error occurred while trying to write the portfolioScript to the portfolio.html file: ', err);
console.log(
'An error occurred while trying to write the portfolioScript to the portfolio.html file: ',
err
);
}
}
module.exports.portfolio = portfolio;
Expand All @@ -64,7 +75,7 @@ module.exports.portfolio = portfolio;
* or developers can get up to speed quickly.
*/
module.exports.website = function (next) {
console.log('Initializing website project, please wait...'.green);
console.log(clc.green('Initializing website project, please wait...'));
installWebsiteFiles(function (err) {
if (err) return console.log(err);
// check if rootDirectory is relative path
Expand All @@ -91,7 +102,7 @@ function installWebsiteFiles(next) {
message = filename + ' downloaded to ' + rootDirectory;
console.log(message.green);
if (++downloaded === numFiles) {
console.log('All website files downloaded.'.green);
console.log(clc.green('All website files downloaded.'));
next(null);
}
});
Expand Down
Loading

0 comments on commit 8e3ef9c

Please sign in to comment.