3
\$\begingroup\$

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:

  1. List only local branches.
  2. List only remote branches.
  3. 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();
200_success
145k22 gold badges190 silver badges478 bronze badges
asked Apr 22, 2017 at 23:41
\$\endgroup\$
2
  • \$\begingroup\$ for start I would to use git one of those git libraries for node, this one looks fine. \$\endgroup\$ Commented 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\$ Commented Apr 23, 2017 at 16:51

1 Answer 1

2
\$\begingroup\$

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();
answered Apr 23, 2017 at 18:37
\$\endgroup\$
1
  • \$\begingroup\$ What about extending features? \$\endgroup\$ Commented Apr 24, 2017 at 6:26

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.