Skip to content

Instantly share code, notes, and snippets.

@JamesGelok
Last active December 8, 2023 14:55
Show Gist options
  • Save JamesGelok/dc4ee1fed963330c61262686a0c57a8f to your computer and use it in GitHub Desktop.
Save JamesGelok/dc4ee1fed963330c61262686a0c57a8f to your computer and use it in GitHub Desktop.
Git shortcut command `git prev-branch [steps]`

Git Previous Branch Command in Node.js

This script provides a custom Git command git prev-branch [steps], allowing you to check out a previously used Git branch by specifying how many steps back in the branch history you wish to go.

Installation

  1. Save git-prev-branch.js to a directory in your PATH (e.g. ~/git-prev-branch.js).
  2. Make the script executable: chmod +x git-prev-branch.js
  3. Rename the script to remove the .js extension: mv git-prev-branch.js git-prev-branch

Usage

To use the command, type git prev-branch [steps], where [steps] is the number of steps back in your branch history. For example, git prev-branch 1 will check out the branch that was used just before the current one.






Windows Setup

To use this script on Windows, you'll need to have Node.js installed and be able to run Node.js scripts from the command line. Additionally, you will need a way to execute the script as a Git command. Here's how to set it up:

  1. Install Node.js: If not already installed, download and install Node.js from nodejs.org.

  2. Save the Script: Save the git-prev-branch.js file to a directory.

  3. Add to PATH:

    • Right-click on 'This PC' or 'My Computer' on your desktop or in File Explorer.
    • Click 'Properties'.
    • Click 'Advanced system settings'.
    • In the System Properties window, click the 'Environment Variables' button.
    • In the Environment Variables window, select the 'Path' variable in the 'System variables' section, and click 'Edit'.
    • Add the path to the directory where you saved git-prev-branch.js.
    • Click OK in all dialogs to close them.
  4. Create a Batch File for Git Command:

    • In the same directory, create a new file named git-prev-branch.bat.
    • Edit the file and add the following line:
      @node "%~dp0git-prev-branch.js" %*
      
    • This batch file allows Git to use the Node.js script as a command.
  5. Usage:

    • Open Git Bash or your preferred shell.
    • Use the command as described previously: git prev-branch [step].
    • The [step] parameter works the same as in the Linux/Mac instructions.

This setup allows Windows users to run the script as a Git command. Ensure that the directory containing both git-prev-branch.js and git-prev-branch.bat is in your PATH.

#!/usr/bin/env node
const { execSync } = require('child_process');
function main() {
// Check if an argument is provided
if (process.argv.length < 3) {
console.error("Please provide a branch step as an argument.");
process.exit(1);
}
// Get the step count and remove minus signs
const step = parseInt(process.argv[2].replace('-', ''), 10);
// Extract branch names from the git reflog
let branches;
try {
branches = execSync("git reflog | grep -o 'checkout: moving from [^ ]* to [^ ]*' | awk '{print $6}' | uniq")
.toString()
.trim()
.split('\n');
} catch (error) {
console.error("Error extracting branches:", error.message);
process.exit(1);
}
// Get the branch name at the specified step
const branchName = branches[step - 1];
if (!branchName) {
console.error("No such branch found.");
process.exit(1);
}
// Checkout the branch
try {
execSync(`git checkout ${branchName}`, { stdio: 'inherit' });
} catch (error) {
console.error("Error checking out branch:", error.message);
process.exit(1);
}
}
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment