HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptgitMinor

List all the git branches

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
thebranchesallgitlist

Problem

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();

Solution

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();

Code Snippets

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();

Context

StackExchange Code Review Q#161554, answer score: 2

Revisions (0)

No revisions yet.