Created
September 18, 2019 00:01
-
-
Save gseok/58ebaa1465f0821b890f79dbc9e8dab5 to your computer and use it in GitHub Desktop.
Git Local Branch Clear When Remote Branch PR Merge and Deleted
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env node | |
const { spawn } = require('child_process') | |
const REMOTE_START_STR = 'remotes/origin/' | |
const runCommand = async (command, options) => { | |
return new Promise((resolve, reject) => { | |
const prc = spawn(command, [...options], { | |
cwd: process.cwd(), | |
}) | |
let result = '' | |
prc.stdout.on('data', data => { | |
result += data.toString() | |
}) | |
prc.stderr.on('data', reject) | |
prc.on('close', code => { | |
resolve(result) | |
}) | |
}) | |
} | |
const parseBranchInfo = rawInfo => { | |
const lines = rawInfo.split('\n') | |
const localBranch = [] | |
const remotesBranch = [] | |
lines.forEach(line => { | |
const br = line.trim().split(' ')[0] | |
if (!br || br === '*' || br === 'HEAD') return | |
br.startsWith(REMOTE_START_STR) ? remotesBranch.push(br.replace(REMOTE_START_STR, '')) : localBranch.push(br) | |
}) | |
return { | |
localBranch, | |
remotesBranch | |
} | |
} | |
const clearLocalBranch = ({ localBranch, remotesBranch }) => { | |
const localRemoveCandidate = localBranch.filter(branch => !remotesBranch.includes(branch)) | |
if (localRemoveCandidate && localRemoveCandidate.length > 0) { | |
return runCommand('git', ['branch', '-D', ...localRemoveCandidate]) | |
} | |
} | |
runCommand('git', ['branch', '-av']) | |
.then(parseBranchInfo) | |
.then(clearLocalBranch) | |
.then(() => console.log('Clear Success...')) | |
.catch(() => console.error('Clear Failed...')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment