How can I get parent branch name using simpleGit ?
nvuillam opened this issue · 2 comments
nvuillam commented
I'm trying to implement a way to get the name of the branch that has been used to create the current branch
Solutions exists, but I don't succeed to implement them with simpleGit
Would someone have some tip to reproduce the following solution with simpleGit ? https://stackoverflow.com/a/17843908/7113625
steveukx commented
Based on the answer to the stackoverflow you linked to, you would use:
const outputFromGit = (await simpleGit({ trimmed: true }).raw('show-branch', '-a')).split('\n');
const rev = await simpleGit({ trimmed: true }).raw('rev-parse', '--abbrev-ref', 'HEAD');
To give you an array of each line of output from git
, which is the first step in the piped chain. From there, you would:
outputFromGit
.map(line => line.replace(/\].*/, '')) // remove branch commit message
.filter(line => line.includes('*')) // only lines with a star in them
.filter(line => !line.includes(rev)) // only lines not including the specified revision
.filter((line, index, all) => index < all.length - 1) // not the last line
.map(line => line.replace(/^.*\[/, '')) // remove all but the branch name
Or thereabouts.
nvuillam commented
@steveukx thanks for your reply :)
It did not work exactly as expected (cf screenshot) , but I built some ugly code that seems to work :)
export async function getGitParentBranch() {
try {
const outputFromGit = (
await simpleGit({ trimmed: true }).raw("show-branch", "-a")
).split("\n");
const rev = await simpleGit({ trimmed: true }).raw(
"rev-parse",
"--abbrev-ref",
"HEAD"
);
const allLinesNormalized = outputFromGit.map((line) =>
line.trim().replace(/\].*/, "")
);
const indexOfCurrentBranch = allLinesNormalized.indexOf(`* [${rev}`);
if (indexOfCurrentBranch > -1) {
const parentBranch = allLinesNormalized[indexOfCurrentBranch + 1].replace(
/^.*\[/,
""
);
return parentBranch;
}
} catch (e) {
return null;
}
return null;
}