I have written a toy script to list all the git branches in cwd
. I am interested in knowing how can I make this code more modular and flexible.
For example I would like to have features like:
- List only local branches.
- List only remote branches.
- Etc.
const os = require('os');
const cp = require('child_process');
const REGEX_STAR = /^\*\s*/g;
const promiseExec = (cmd) =>
new Promise((resolve, reject) => {
cp.exec(cmd, (err, stdout, stderr) => {
if (err) {
return reject(err);
}
resolve(lines(`${stdout}`));
});
});
const lines = (str) =>
str.trim().split(os.EOL).map((line) =>
line.trim().replace(REGEX_STAR, '')
);
const branches = () =>
promiseExec('git branch -a')
.then((res) => {
console.log(res);
});
branches();
-
\$\begingroup\$ for start I would to use git one of those git libraries for node, this one looks fine. \$\endgroup\$zb'– zb'2017年04月23日 16:49:26 +00:00Commented Apr 23, 2017 at 16:49
-
\$\begingroup\$ next, I would to create a Class for your purposes, instead of own promiseExec I would to use promisify libraries, in short - better to use common libraries than to write own. \$\endgroup\$zb'– zb'2017年04月23日 16:51:37 +00:00Commented Apr 23, 2017 at 16:51
1 Answer 1
Just return the data and leave it to the consumer what to do with it. That way, branches
becomes a generic data grabber. If you want to have printer functions, keep them separate from the raw command.
Your Promise wrapper appears to expect the output of the branches
command. Move the use of lines
to the branches
function instead.
Also, arrow functions with single arguments can omit the parens.
const promiseExec = (cmd) => new Promise((resolve, reject) => {
cp.exec(cmd, (err, stdout, stderr) => {
if (err) reject(err);
else resolve(stdout);
});
});
const branchLines = (str) => str.trim().split(os.EOL).map(line => line.trim().replace(REGEX_STAR, ''));
const branches = () => promiseExec('git branch -a').then(res => branchLines(res));
const printBranches = () => branches().then(res => console.log(res));
// Print manually
branches().then(res => console.log(res));
// or have a printer function do it
printbranches();
-
\$\begingroup\$ What about extending features? \$\endgroup\$CodeYogi– CodeYogi2017年04月24日 06:26:58 +00:00Commented Apr 24, 2017 at 6:26