Skip to main content
Branches allow you to develop features, fix bugs, or experiment in isolated environments. This guide covers comprehensive branch management with useGit.

Creating Branches

Create a New Branch

Use createBranch() to create a new branch:
import { createBranch } from 'usegit';

// Create a new branch
await createBranch('feature/user-authentication');
createBranch() will throw an error if the branch already exists. This prevents accidentally overwriting existing branches.

Create and Switch Options

The branch() function provides low-level control:
import { branch } from 'usegit';

// Create a new branch
await branch('feature/api-integration');

// Create a branch from a specific commit
await branch('hotfix/security-patch', {
  flags: ['--force']
});

Listing Branches

List Local Branches

Get all local branches in your repository:
import { listBranches } from 'usegit';

const branches = await listBranches();
console.log(branches);
// ['main', 'develop', 'feature/login']

List All Branches

Include both local and remote branches:
import { listAllBranches } from 'usegit';

const allBranches = await listAllBranches('json');
console.log(allBranches);
// {
//   local: ['main', 'develop'],
//   remote: ['origin/main', 'origin/develop']
// }

List Remote Branches

View only remote-tracking branches:
import { listRemoteBranches } from 'usegit';

const remoteBranches = await listRemoteBranches();
console.log(remoteBranches);
// ['origin/main', 'origin/feature/api']

Get Current Branch

Find out which branch you’re currently on:
import { currentBranch } from 'usegit';

const current = await currentBranch();
console.log(`Currently on: ${current}`);
// Currently on: main

Managing Branches

Rename a Branch

Change a branch name:
import { renameBranch } from 'usegit';

// Rename the current branch
await renameBranch('old-name', 'new-name');

// Force rename (overwrite if new name exists)
await renameBranch('feature/old', 'feature/new', {
  force: true
});

Copy a Branch

Create a copy of an existing branch:
import { copyBranch } from 'usegit';

// Copy a branch
await copyBranch('main', 'main-backup');

// Force copy (overwrite if target exists)
await copyBranch('develop', 'develop-backup', {
  force: true
});

Delete a Branch

Remove branches you no longer need:
import { deleteBranch } from 'usegit';

// Delete a merged branch
await deleteBranch('feature/completed-feature');

// Force delete an unmerged branch
await deleteBranch('feature/abandoned', {
  force: true
});
Use force: true when deleting a branch that hasn’t been merged. Be careful - this will permanently delete the branch and its commits if they’re not referenced elsewhere.

Branch Workflows

Feature Branch Workflow

A complete example of the feature branch workflow:
1

Create a feature branch

import { createBranch, currentBranch } from 'usegit';

await createBranch('feature/new-dashboard');
console.log('Created branch:', await currentBranch());
2

Work on your feature

import { add, commit } from 'usegit';

// Make changes to your files
await add('.');
await commit(
  'feat: add dashboard layout',
  'Implements the basic dashboard structure with navigation'
);
3

Continue development

// Make more changes
await add(['src/components/Dashboard.tsx']);
await commit('feat: add dashboard widgets');
4

Clean up after merge

import { deleteBranch } from 'usegit';

// After merging into main, delete the feature branch
await deleteBranch('feature/new-dashboard');

Checking Branch Status

Before switching or deleting branches, check their status:
import { 
  listBranches, 
  currentBranch, 
  branchExists,
  status 
} from 'usegit';

async function branchInfo() {
  // Get current branch
  const current = await currentBranch();
  console.log(`Current branch: ${current}`);

  // List all local branches
  const branches = await listBranches();
  console.log('Available branches:', branches);

  // Check if a branch exists
  const exists = await branchExists('feature/login');
  console.log('feature/login exists:', exists);

  // Check working tree status
  const statusResult = await status();
  console.log(statusResult);
}

branchInfo();

Advanced Branch Operations

Set Upstream Branch

Configure tracking relationship with remote branches:
import { setBranchUpstream } from 'usegit';

// Set upstream for the current branch
await setBranchUpstream('origin/main');

Reset Branch to HEAD

Reset a branch to point to HEAD:
import { resetBranchToHead } from 'usegit';

await resetBranchToHead('feature/experimental');

Get Default Branch

Retrieve the repository’s default branch name:
import { getDefaultBranch } from 'usegit';

const defaultBranch = await getDefaultBranch();
console.log(`Default branch: ${defaultBranch}`);
// Default branch: main

Real-World Example

Here’s a complete example managing branches in a development workflow:
import { 
  createBranch,
  currentBranch,
  listBranches,
  branchExists,
  deleteBranch,
  add,
  commit
} from 'usegit';

async function developFeature() {
  const featureName = 'feature/payment-integration';

  try {
    // Check if branch already exists
    if (await branchExists(featureName)) {
      console.log(`Branch ${featureName} already exists`);
      return;
    }

    // Create and switch to feature branch
    console.log(`Creating branch: ${featureName}`);
    await createBranch(featureName);

    // Verify we're on the new branch
    const current = await currentBranch();
    console.log(`Now on branch: ${current}`);

    // Develop the feature (simulated)
    // ... make file changes ...

    // Commit the changes
    await add('.');
    await commit(
      'feat: integrate Stripe payment API',
      'Adds payment processing with Stripe SDK including checkout and webhooks'
    );

    console.log('Feature development complete!');

    // List all branches
    const branches = await listBranches();
    console.log('Available branches:', branches);

  } catch (error) {
    console.error('Error during branch workflow:', error);
  }
}

async function cleanupOldBranches() {
  const branchesToDelete = [
    'feature/old-feature',
    'hotfix/temp-fix'
  ];

  for (const branch of branchesToDelete) {
    if (await branchExists(branch)) {
      console.log(`Deleting branch: ${branch}`);
      await deleteBranch(branch, { force: true });
    }
  }
}

// Run the workflow
developFeature();

Next Steps

Commit Operations

Learn advanced commit techniques

Diff and Status

Master status checking and diff viewing

Build docs developers (and LLMs) love