The working directory (cwd) determines where Git commands are executed. useGit manages this through a stateful system that tracks the current working directory for each Git instance.
useGit provides a setCwd() function to update the working directory after instance creation:
import { createGit, setCwd } from "use-git"const git = createGit({ cwd: "./repo-1" })await git.status() // operates in ./repo-1// Change working directorysetCwd("./repo-2")await git.status() // operates in ./repo-2
setCwd() changes the working directory globally for all instances that share the same state. For independent repositories, create separate instances instead.
Create separate instances when working with multiple repositories:
import { createGit } from "use-git"const frontend = createGit({ cwd: "./apps/frontend" })const backend = createGit({ cwd: "./apps/backend" })// Each operates in its own directoryawait frontend.status() // runs in ./apps/frontendawait backend.status() // runs in ./apps/backend
If you need to work with repositories sequentially, use setCwd():
import { createGit, setCwd } from "use-git"const git = createGit()// Work with first repositorysetCwd("./repo-1")await git.add()await git.commit("Update repo 1")// Switch to second repositorysetCwd("./repo-2")await git.add()await git.commit("Update repo 2")
The working directory is managed through a state module:
// Simplified internal implementationexport let cwd = "."export function setCwd(next: string) { cwd = next}
When Git commands execute, they use Node.js’s child_process.spawn() with the cwd option:
const child = spawn("git", ["status"], { cwd: cwd, // Current working directory from state})
This stateful approach means the working directory is shared across all operations using the same instance. Create separate instances to isolate working directories.