Skip to content

Instantly share code, notes, and snippets.

@tzellman
Created January 20, 2022 16:39
Show Gist options
  • Save tzellman/6a06a43610050cee8c7be06a1f31cd70 to your computer and use it in GitHub Desktop.
Save tzellman/6a06a43610050cee8c7be06a1f31cd70 to your computer and use it in GitHub Desktop.

This is an interactive file that can be run with the zx utility: https://github.com/google/zx

$.verbose = false
const DEFAULT_REF_BRANCH = 'develop';
const DEFAULT_BRANCH_FILTER = 'renovate';
const DEFAULT_REMOTE = 'origin';

if (argv.help || argv.h) {
    console.log(`
    --help | -h     display help information
    --ref           specify the reference branch (default=${DEFAULT_REF_BRANCH})
    --filter        specify the branch filter (default=${DEFAULT_BRANCH_FILTER})
    --remote        specify the remote (default=${DEFAULT_REMOTE})
`)
    process.exit(0)
}


const refBranch = argv.ref || DEFAULT_REF_BRANCH;
const branchFilter = argv.filter || DEFAULT_BRANCH_FILTER;
const remote = argv.remote || DEFAULT_REMOTE;

const mergeBranch = async (branch) => {
    const localBranch = new RegExp(`^${remote}\/(.*)`).exec(branch)[1];
    await nothrow( $`git branch -D ${localBranch}`)
    await $`git branch --track ${localBranch} ${branch}`
    await $`git checkout ${localBranch}`
    const results = (await $`git rebase ${refBranch}`).stdout
    console.log(results)
    await $`git checkout ${refBranch}`
    await $`git merge --ff-only ${localBranch}`
    console.log(`Merged branch ${chalk.blue(branch)} into ${chalk.blue(refBranch)}`)
}

await $`git checkout ${refBranch}`
await $`git fetch --all`
const filteredBranches = (await $`git branch -r --sort=-committerdate | grep -i ${remote} | grep -i ${branchFilter}`).stdout.split(/\n/).map(s => s.trim()).filter(s => s)

if (!filteredBranches.length) {
    console.log(`No potential branches to merge!`)
    process.exit(0)
}
while (filteredBranches.length) {
    console.log(`${filteredBranches.length} possible branches to merge: \n\n${chalk.yellow(filteredBranches.join('\n'))}\n`)
    const branch = await question(chalk.green('Choose a branch to merge: '), {
        choices: filteredBranches
    })
    console.log(`Attempting to merge branch: ${chalk.blue(branch)}`)
    // remove the choice for now
    filteredBranches.splice(filteredBranches.indexOf(branch), 1);
    await mergeBranch(branch);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment