Last active
May 1, 2020 11:04
-
-
Save xanthalas/1fc615fe1139d2c62fbad1f311dca10a to your computer and use it in GitHub Desktop.
NodeJs script to copy matching GIT branch name to the clipboard
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
| var clipboard = require('copy-paste'); | |
| var fs = require('fs'); | |
| var exec = require('child_process').exec; | |
| var result = ''; | |
| var searchTerm = process.argv[2]; | |
| if (!searchTerm) { | |
| console.log("No search term specified. Usage: get-branch-name string-to-search-for"); | |
| return; | |
| } | |
| var child = exec('git branch'); | |
| child.stdout.on('data', function(data) { | |
| result += data; | |
| }); | |
| child.on('close', () => { | |
| extractBranchName(result, searchTerm); | |
| }); | |
| function extractBranchName(branchlist, search) { | |
| search = search.toLowerCase(); | |
| let branches = branchlist.split("\n"); | |
| let matchingBranches = branches.filter(b => b.toLowerCase().includes(search)); | |
| let selectedBranch = ""; | |
| let text = ""; | |
| switch (matchingBranches.length) { | |
| case 0: | |
| console.log(`Couldn't find a branch matching the search term ${search}`); | |
| break; | |
| case 1: | |
| selectedBranch = matchingBranches[0]; | |
| text = copyToClipboard(selectedBranch); | |
| console.log(`Branch "${text}" copied to clipboard`); | |
| break; | |
| default: | |
| selectedBranch = matchingBranches[0]; | |
| text = copyToClipboard(selectedBranch); | |
| console.log(`${matchingBranches.length} branches matched. First one copied to clipboard: ${text}\n`); | |
| for (let b of matchingBranches) { | |
| console.log(b); | |
| }; | |
| break; | |
| } | |
| console.log(""); | |
| } | |
| function copyToClipboard(text) { | |
| if (text) { | |
| if (text.startsWith("*")) { | |
| text = text.slice(1); | |
| } | |
| text = text.trim(); | |
| clipboard.copy(text); | |
| return text; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment