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

promisifying-refactor #53

Merged
merged 4 commits into from
Apr 18, 2022
Merged
Show file tree
Hide file tree
Changes from all 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
148 changes: 45 additions & 103 deletions cli.js
Original file line number Diff line number Diff line change
@@ -1,52 +1,53 @@
#!/usr/bin/env node

const fs = require('fs');
const fs = require('fs/promises');
const path = require('path');
const chalk = require('chalk');
const Table = require('cli-table');
const _async = require('async');
const updateNotifier = require('update-notifier');

const theGit = require('git-state');
const { Spinner } = require('cli-spinner');
const argv = require('minimist')(process.argv.slice(2));

const pkg = require('./package');
const C = require('./src/constants');
const { printHelp } = require('./src/functions');
const {
printHelp,
prettyPath,
colorForStatus,
processDirectory,
} = require('./src/functions');

const NOOP = () => {};

const printLine = console.log;
const showGitOnly = argv.gitonly || argv.g;
const dirs = argv._.length ? argv._ : [process.cwd()];
const debug = Boolean(argv.debug) ? console.log : NOOP;
const debug = Boolean(argv.debug) ? printLine : NOOP;

let spinner = null;
let table = null;
let cwd = null;
let fileIndex = 0;
let statuses = [];
let compact = false;

const linePrinter = console.log;

updateNotifier({
pkg: pkg,
updateCheckInterval: C.updateInterval * C.daysMultiplier,
}).notify();

process.on('uncaughtException', (err) => {
linePrinter(`Caught exception: ${err}`);
printLine(`Caught exception: ${err}`);
process.exit();
});

if (argv.version || argv.v) {
linePrinter(pkg.version);
printLine(pkg.version);
process.exit();
}

if (argv.help || argv.h) {
printHelp(linePrinter);
printHelp(printLine);
process.exit();
}

Expand All @@ -66,12 +67,13 @@ function getTableHeader(type, color) {
if (!color) {
color = 'cyan';
}
return C.columnsOrder.map((key) => chalk[color](C.headers[key][type]));
const colorizer = chalk[color];
return C.columnsOrder.map((key) => colorizer(C.headers[key][type]));
}

function init() {
function init(directories) {
//either passed from CLI or take the current directory
cwd = dirs[0];
cwd = directories[0];

//Spinners
spinner = new Spinner('%s');
Expand All @@ -98,54 +100,12 @@ function init() {
return new Table(tableOpts);
}

function prettyPath(pathString) {
let p = pathString.split(path.sep);
return p[p.length - 1];
}

function processDirectory(stat, callback) {
fileIndex++;
let pathString = path.join(cwd, stat.file);
if (stat.stat.isDirectory()) {
debug(fileIndex, stat.file);
theGit.isGit(pathString, function (isGit) {
if (isGit) {
theGit.check(pathString, function (e, gitStatus) {
if (e) return callback(e);
gitStatus.git = true;
debug(stat.file, gitStatus);
insert(pathString, gitStatus);
return callback(null, true);
});
} else {
const gitStatus = C.emptyGitStatus;
debug(stat.file, gitStatus);
if (!showGitOnly) {
insert(pathString, gitStatus);
}
return callback(null, false);
}
});
} else {
debug(stat.file, false);
return callback(null, false);
}
}

function insert(pathString, status) {
let directoryName = prettyPath(pathString);
status.directory = directoryName;
statuses.push(status);

// TODO: refactor
let methodName =
status.dirty === 0
? status.ahead === 0
? status.untracked === 0
? 'grey'
: 'yellow'
: 'green'
: 'red';
let methodName = colorForStatus(status);

if (!((argv.attention || argv.a) && methodName === 'grey')) {
table.push(
Expand All @@ -168,13 +128,11 @@ function simpleStatus(status) {
for (let i = 0; i < C.simple.length; i++) {
str.push(status[C.simple[i]]);
}
console.log(str.join(','));
printLine(str.join(','));
}

function simple() {
for (let i = 0; i < statuses.length; i++) {
simpleStatus(statuses[i]);
}
function simple(_statuses) {
_statuses.forEach((status) => simpleStatus(status));
}

function finish() {
Expand All @@ -183,25 +141,17 @@ function finish() {
process.stdout.cursorTo(0); // move cursor to beginning of line

if (argv.sort) {
table.sort((a, b) => {
if (a[0] < b[0]) {
return -1;
}
if (a[0] > b[0]) {
return 1;
}
return 0;
});
table.sort((a, b) => a[0] - b[0]);
}

if (argv.simple || argv.s) {
simple();
simple(statuses);
} else {
if (!chalk.supportsColor) {
console.log(chalk.stripColor(table.toString()));
} else {
console.log(table.toString());
}
printLine(
chalk.supportsColor
? table.toString()
: chalk.stripColor(table.toString())
);
}
if (compact) {
let str = [];
Expand All @@ -210,39 +160,31 @@ function finish() {
str.push(chalk.cyan(header.short) + ': ' + header.long);
});
if (!hasAskedForVeryCompact()) {
console.log(str.join(', ') + '\n');
printLine(str.join(', ') + '\n');
}
}
}

const listRepos = () => {
table = init(dirs);
linePrinter(chalk.green(cwd));

fs.readdir(cwd, function (err, files) {
if (err) {
printLine(chalk.green(cwd));

fs.readdir(cwd)
.then((files) => files.map((file) => path.resolve(cwd, file)))
.then((files) =>
Promise.all(
files.map((file) =>
fs.stat(file).then((stat) => ({ file, stat }), printLine)
)
)
)
.then((statuses) =>
processDirectory(statuses, { debug, insert, C, showGitOnly })
)
.then((statuses) => finish(statuses))
.catch((err) => {
throw err;
}
_async.map(
files,
function (file, statCallback) {
fs.stat(path.join(cwd, file), function (err, stat) {
if (err) return statCallback(err);
statCallback(null, {
file: file,
stat: stat,
});
});
},
function (err, statuses) {
if (err) throw new Error(err);
debug(statuses.length);
_async.filter(statuses, processDirectory, function () {
finish();
});
}
);
});
});
};

listRepos();
1 change: 0 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@
},
"homepage": "https://github.com/pankajpatel/list-repos#readme",
"dependencies": {
"async": "^3.1.0",
"chalk": "~4.1.2",
"cli-spinner": "^0.2.5",
"cli-table": "^0.3.4",
Expand Down
18 changes: 18 additions & 0 deletions src/functions/colorForStatus.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
const COLORS = {
RED: 'red',
GREEN: 'green',
YELLOW: 'yellow',
GREY: 'grey',
};

const colorForStatus = (state) => {
if (state.dirty) return COLORS.RED;
if (state.ahead) return COLORS.GREEN;
if (state.untracked) return COLORS.YELLOW;
return COLORS.GREY;
};

module.exports = {
colorForStatus: colorForStatus,
COLORS: COLORS,
};
8 changes: 8 additions & 0 deletions src/functions/colorForStatus.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
const { colorForStatus, COLORS } = require('./colorForStatus');

describe('colorForStatus()', () => {
it('should return default color', () => {
const color = colorForStatus({});
expect(color).toBe(COLORS.GREY);
});
});
15 changes: 15 additions & 0 deletions src/functions/gitCheck.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
const theGit = require('git-state');

const gitCheck = (p) =>
new Promise((resolve, reject) => {
theGit.check(p, function (e, result) {
if (e) {
reject(e);
}
resolve(result);
});
});

module.exports = {
gitCheck,
};
12 changes: 11 additions & 1 deletion src/functions/index.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,15 @@
const printHelp = require('./printHelp');
const { printHelp } = require('./printHelp');
const { colorForStatus } = require('./colorForStatus');
const { isGit } = require('./isGit');
const { gitCheck } = require('./gitCheck');
const { prettyPath } = require('./prettyPath');
const { processDirectory } = require('./processDirectory');

module.exports = {
printHelp: printHelp,
colorForStatus: colorForStatus,
isGit: isGit,
gitCheck: gitCheck,
prettyPath: prettyPath,
processDirectory: processDirectory,
};
12 changes: 12 additions & 0 deletions src/functions/isGit.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
const theGit = require('git-state');

const isGit = (p) =>
new Promise((resolve) => {
theGit.isGit(p, function (result) {
resolve(result);
});
});

module.exports = {
isGit,
};
10 changes: 10 additions & 0 deletions src/functions/prettyPath.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
const path = require('path');

const prettyPath = (pathString) => {
const p = pathString.split(path.sep);
return p[p.length - 1];
};

module.exports = {
prettyPath,
};
4 changes: 3 additions & 1 deletion src/functions/printHelp.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,6 @@ function printHelp(linePrinter = console.log) {
linePrinter(lines.join('\n'));
}

module.exports = printHelp;
module.exports = {
printHelp: printHelp,
};
2 changes: 1 addition & 1 deletion src/functions/printHelp.spec.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
const printHelp = require('./printHelp');
const { printHelp } = require('./printHelp');

describe('printHelp()', () => {
it('should run the passed printer function', () => {
Expand Down
45 changes: 45 additions & 0 deletions src/functions/processDirectory.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
const { isGit } = require('./isGit');
const { gitCheck } = require('./gitCheck');

const processDirectory = (stat, options) => {
if (!stat || !stat.file) {
return Promise.resolve(false);
}
let pathString = stat.file;

if (!stat.stat.isDirectory()) {
options.debug(stat.file, false);
return Promise.resolve(false);
}

options.debug(stat.file);

return Promise.resolve()
.catch((e) => Promise.resolve(false))
.then(() => isGit(pathString))
.then((isDirGit) => {
return !isDirGit
? new Promise((resolve) => {
const gitStatus = options.C.emptyGitStatus;
options.debug(stat.file, gitStatus);
if (!options.showGitOnly) {
options.insert(pathString, gitStatus);
return resolve(true);
}
return resolve(false);
})
: gitCheck(pathString).then((gitStatus) => {
gitStatus.git = true;
options.debug(stat.file, gitStatus);
options.insert(pathString, gitStatus);
return Promise.resolve(true);
});
});
};

const processDirectories = (stats, opts) =>
Promise.all(stats.map((status) => processDirectory(status, opts)));

module.exports = {
processDirectory: processDirectories,
};
Loading