Skip to main content
This guide will walk you through the basics of useGit by creating a new Git repository, making commits, and exploring common operations.

Basic Usage

1

Import useGit

Start by importing the git instance from useGit:
import { git } from 'use-git';
The default git instance uses the current working directory. For working with different repositories, see Multiple Repositories.
2

Initialize a Repository

Create a new Git repository or reinitialize an existing one:
await git.init();
// Initializes with 'main' as the default branch
You can customize the initial branch name:
await git.init({ '--initial-branch': 'develop' });
3

Add Files

Stage files for commit:
// Add all files
await git.add('.');

// Add specific files
await git.add(['src/index.ts', 'package.json']);

// Add with options
await git.add('.', { flags: ['--verbose'] });
4

Create Commits

Commit your staged changes:
// Simple commit
await git.commit('feat: add new feature');

// Commit with description
await git.commit(
  'fix: handle empty input',
  'This fixes a bug where empty input caused a crash.'
);

// Commit with options
await git.commit('chore: release', { flags: ['--amend'] });

// Commit with signoff
await git.commit(
  'feat: improve API',
  'Adds better typing and docs.',
  { flags: ['--signoff'] }
);
5

Check Status

Inspect your repository status:
// Human-readable status
const status = await git.status();
console.log(status);

// Short format with branch info
const shortStatus = await git.status(undefined, {
  flags: ['--short', '--branch']
});

// Machine-readable output (for tooling)
const porcelain = await git.status(undefined, {
  flags: ['--porcelain']
});

// Check if there are uncommitted changes
const isDirty = await git.isDirty();
if (isDirty) {
  console.log('Working tree has uncommitted changes');
}

Working with Branches

Create and manage branches:
// Get current branch
const current = await git.currentBranch();
console.log('Current branch:', current); // main

// Create a new branch
await git.createBranch('feature/login');

// Check if a branch exists
const exists = await git.branchExists('feature/login');

// List all branches
const branches = await git.listBranches();

Working with Tags

Create and query tags:
// Create a lightweight tag
await git.createTag('v1.0.0');

// Create an annotated tag
await git.createAnnotatedTag('v1.0.0', 'Release version 1.0.0');

// Force create/update a tag
await git.createTag('v1.0.0', { force: true });

// Get all tags
const tags = await git.getTags();

// Get semantic version tags
const semverTags = await git.getSemverTags();

// Check if a tag exists
const hasTag = await git.hasTag('v1.0.0');

Viewing Diffs

Compare changes across commits:
// Show unstaged changes
const diff = await git.diff();

// Show staged changes
const stagedDiff = await git.diffStaged();

// Get diff statistics
const stats = await git.diffStats();

// Compare commits
const commitDiff = await git.diff(['HEAD~1', 'HEAD']);

// Diff specific files
const fileDiff = await git.diff(undefined, ['src/index.ts']);

// Check if there are staged changes
const hasStagedDiff = await git.hasStagedDiff();

Multiple Repositories

Work with multiple repositories by creating separate Git instances:
import { createGit } from 'use-git';

const projectA = createGit({ cwd: './project-a' });
const projectB = createGit({ cwd: './project-b' });

// Each instance operates independently
await projectA.add('.');
await projectA.commit('update project A');

await projectB.add('.');
await projectB.commit('update project B');

// Enable debug logging for an instance
const debugGit = createGit({ 
  cwd: './my-repo', 
  debug: true 
});

Complete Workflow Example

Here’s a complete example that demonstrates a typical Git workflow:
import { git } from 'use-git';

async function setupProject() {
  // Initialize repository
  await git.init();
  console.log('Repository initialized');

  // Create a new file (using fs)
  await fs.writeFile('README.md', '# My Project');

  // Stage and commit
  await git.add('.');
  await git.commit('docs: add README');
  console.log('Initial commit created');

  // Create a feature branch
  await git.createBranch('feature/awesome');
  console.log('Created feature branch');

  // Make changes and commit
  await fs.writeFile('feature.ts', 'export const feature = true;');
  await git.add('feature.ts');
  await git.commit('feat: add awesome feature');

  // Check status
  const status = await git.status();
  console.log('Status:', status);

  // Create a tag
  await git.createTag('v0.1.0');
  console.log('Tagged v0.1.0');

  // View the diff from main
  const current = await git.currentBranch();
  console.log('Current branch:', current);
}

setupProject().catch(console.error);

Error Handling

All useGit functions return promises that reject on errors:
try {
  await git.commit('feat: new feature');
} catch (error) {
  console.error('Commit failed:', error.message);
}

// Or with promise chains
git.commit('feat: new feature')
  .then(output => console.log('Success:', output))
  .catch(error => console.error('Failed:', error.message));

Next Steps

API Reference

Explore the complete API documentation

Examples

Browse more code examples and use cases
Most functions accept an options parameter where you can pass custom flags. Check the API reference for specific options available for each command.

Build docs developers (and LLMs) love