GitNifty
    Preparing search index...

    Class Git

    A smart, user-friendly Git utility class for Node.js CLIs.

    Git provides a high-level interface for interacting with Git repositories using simple, intuitive commands. Designed for use in GitNifty, it wraps common Git operations like checking repository status, retrieving user info, detecting upstream branches, and more — all with clean automation and helpful defaults.

    This class is built to make version control effortless for developers who want precision and productivity, without dealing with complex Git shell commands directly.

    import { Git } from "./gitnifty";

    const git = new Git({ cwd: "/path/to/repo" });
    const username = await git.getUserName();
    const branch = await git.getCurrentBranchName();
    const isClean = await git.isWorkingDirClean();
    • Built for Node.js CLI tools like GitNifty.
    • Uses child_process.exec under the hood.
    • Handles common Git tasks with automation-friendly methods.
    • Falls back gracefully on errors, e.g., hasUpstreamBranch() or isWorkingDirClean() return false instead of throwing.
    Index

    Constructors

    • Creates an instance of the Git class.

      Parameters

      • options: GitOptions

        Configuration options for the Git instance.

      Returns Git

      const git = new Git({ cwd: "/path/to/repo" });
      

    Methods

    • Stages one or more files or directories for the next commit.

      This method wraps git add to prepare specified files or directories for commit. You can provide a single path or an array of paths. By default, it stages all changes.

      Parameters

      • path: string | string[] = "."

        The file(s) or directory path(s) to stage. Use "." to stage all changes. If an array is provided, all listed paths will be staged.

      Returns Promise<string>

      A promise that resolves with the command's stdout if successful.

      Throws an error with stderr if the command fails (e.g., invalid path).

      const git = new Git({ cwd: "/repo" });
      await git.add("README.md"); // stages a single file
      await git.add(["src/", "docs/"]); // stages multiple directories
      await git.add(); // stages everything (default ".")
    • Creates, deletes, renames, or lists branches.

      Parameters

      • Optionalname: string

        Optional branch name. Required for some flags.

      • flags: BranchFlag | BranchFlag[] = []

        Optional branch flags like -d, -m, --list, etc.

      Returns Promise<string>

      A promise that resolves with the result of the Git command.

      git.branch(); // git branch
      git.branch("feature-x"); // git branch feature-x
      git.branch("old-branch", ["-d"]); // git branch -d old-branch
      git.branch(undefined, "--show-current"); // git branch --show-current
    • Switches to the given branch or commit, optionally creating it.

      Parameters

      • target: string

        The branch, tag, or commit hash to checkout.

      • Optionalflags: CheckoutFlag | CheckoutFlag[]

        Optional checkout flags like -b, --orphan, etc.

      Returns Promise<Git>

      A promise that resolves with the result of the Git command.

      git.checkout("main"); // git checkout main
      git.checkout("new-branch", "-b"); // git checkout -b new-branch
    • Clones a Git repository into the current directory or specified folder.

      Parameters

      • url: string

        The Git repository URL to clone.

      • dir: string = ""

        Optional directory to clone into.

      Returns Promise<Git>

      A promise that resolves to the Git instance.

      await git.clone("https://github.com/user/repo.git", "my-folder");
      
    • Commits staged changes to the repository with a custom message and optional flags.

      This method wraps git commit -m "<message>" with support for additional commit flags. It safely escapes double quotes in the commit message to avoid shell issues.

      Parameters

      • message: string

        The commit message to use. Will be wrapped in quotes and escaped.

      • Optionalflags: CommitFlag | CommitFlag[]

        Optional list of commit flags to customize the commit behavior. Each flag must be a valid CommitFlag value.

      Returns Promise<Git>

      A promise that resolves with the command's stdout if the commit succeeds.

      Throws an error if the commit fails (e.g., nothing staged, invalid flags).

      const git = new Git({ cwd: "/repo" });
      await git.commit("feat: add login API");
      await git.commit("fix: typo", ["--amend", "--no-edit"]);
    • Runs git describe to generate a human-readable identifier for a commit.

      This wraps the git describe command and returns a string such as v1.2.3-2-gabcdef based on the most recent tag and commit information.

      Parameters

      • flags: DescribeFlag | DescribeFlag[]

        One or more optional git describe flags to customize the output. Can be a single flag or an array of flags.

      • Optionalref: string

        Optional Git reference to describe (e.g., a branch, tag, or commit hash). Defaults to HEAD if not provided.

      Returns Promise<string>

      A promise that resolves with the git describe output.

      await git.describe("--tags");
      await git.describe(["--tags", "--long"], "main");
      await git.describe(["--dirty=*", "--abbrev=10"], "HEAD~2");
    • Retrieves the name of the current branch.

      Returns Promise<string>

      A promise that resolves with the current branch name.

      Throws an error if the command fails (e.g., not a Git repository).

      const git = new Git({ cwd: "/path/to/repo" });
      const branch = await git.getCurrentBranchName();
      console.log(branch); // "main"
    • Retrieves the default branch name of the repository (e.g., main or master).

      Falls back to "main" if the default branch cannot be determined.

      Returns Promise<string>

      A promise that resolves with the default branch name.

      Throws an error if the command fails (e.g., not a Git repository).

      const git = new Git({ cwd: "/path/to/repo" });
      const defaultBranch = await git.getDefaultBranchName();
      console.log(defaultBranch); // "main" or "master"
    • Retrieves the latest reachable Git tag (e.g., v1.2.3) without commit metadata.

      This uses git describe --tags --abbrev=0 to return only the most recent tag name, ignoring additional suffixes like commit counts or hashes.

      Returns Promise<string>

      A promise that resolves with the latest tag as a string.

      await git.getLatestTag(); // "v1.2.3"
      
    • Retrieves the configured Git user email.

      Returns Promise<string>

      A promise that resolves with the user's email.

      Throws an error if the command fails (e.g., Git not installed or email not configured).

      const git = new Git({ cwd: "/path/to/repo" });
      const email = await git.getUserEmail();
      console.log(email); // "john.doe@example.com"
    • Retrieves the configured Git user name.

      Returns Promise<string>

      A promise that resolves with the user's name.

      Throws an error if the command fails (e.g., Git not installed or user not configured).

      const git = new Git({ cwd: "/path/to/repo" });
      const username = await git.getUserName();
      console.log(username); // "John Doe"
    • Checks if there are no staged but uncommitted changes.

      Returns Promise<boolean>

      A promise that resolves to true if there are no staged changes, otherwise false.

      const git = new Git({ cwd: "/repo" });
      const clean = await git.hasNoStagedChanges();
      console.log(clean); // true if nothing is staged for commit
    • Checks if there are no unstaged changes in the working directory.

      Returns Promise<boolean>

      A promise that resolves to true if there are no unstaged changes, otherwise false.

      const git = new Git({ cwd: "/repo" });
      const clean = await git.hasNoUnstagedChanges();
      console.log(clean); // true if working directory has no unstaged changes
    • Checks if the current branch has an upstream branch configured.

      Returns Promise<boolean>

      A promise that resolves to true if an upstream branch is set, false otherwise.

      const git = new Git({ cwd: "/path/to/repo" });
      const hasUpstream = await git.hasUpstreamBranch();
      console.log(hasUpstream); // true (if upstream is set), false (if not)
    • Initializes a new Git repository in the working directory.

      Returns Promise<Git>

      A promise that resolves to the Git instance.

      await git.init();
      await git.clone("https://github.com/repo.git");
    • Checks if the working directory is completely clean i.e., no staged or unstaged changes.

      Returns Promise<boolean>

      A promise that resolves to true if the working directory is fully clean, otherwise false.

      const git = new Git({ cwd: "/repo" });
      const isClean = await git.isWorkingDirClean();
      console.log(isClean); // true if no changes, false if dirty
    • Merges the specified branch into the current branch.

      Parameters

      • branchName: string

        The name of the branch to merge.

      • Optionalflags: MergeFlag | MergeFlag[]

        Optional merge flags like --no-ff, --squash, etc.

      Returns Promise<string>

      A promise that resolves with the result of the Git command.

      git.merge("feature-branch"); // git merge feature-branch
      git.merge("hotfix", ["--squash", "--no-commit"]); // git merge --squash --no-commit hotfix
    • Pushes changes to the specified remote and optionally to a specific branch.

      Parameters

      • remote: string | PushFlag[] = "origin"

        The remote name to push to. Defaults to "origin".

      • branch: string = ""

        The branch name to push. If not provided, pushes all matching branches.

      • flags: PushFlag | PushFlag[] = []

        Optional push flags to customize behavior. Can be a single flag or array.

      Returns Promise<Git>

      A promise that resolves with the result of the Git command.

      git.push(); // git push origin
      git.push("origin", "main", "--force"); // git push --force origin main
      git.push("origin", "dev", ["--tags", "--set-upstream"]); // git push --tags --set-upstream origin dev
    • Resets the current HEAD to the specified commit hash, with an optional behavior flag.

      This method wraps git reset <hash> <flag> and moves the current branch pointer to the given commit. It does not modify the working directory or the index unless additional flags (e.g., --hard, --soft) are added manually.

      Parameters

      • hashValue: string

        The target commit hash to reset to. This must be a valid Git commit SHA (full or abbreviated).

      • Optionalflag: ResetFlag

        One or more Git reset flags. Examples: "--soft", "--hard".

      Returns Promise<string>

      A promise that resolves with the command's stdout if the reset succeeds.

      Throws an error if the command fails (e.g., invalid hash or detached HEAD issues).

      const git = new Git({ cwd: "/repo" });
      await git.reset("abc1234"); // Moves HEAD to commit abc1234
      await git.reset("abc1234", "--hard"); // Hard reset to commit
    • Restores working tree files from the index or a specified source.

      This method wraps git restore to unstage files or restore their contents from the index (staged) or from a specific commit/branch.

      Parameters

      • target: string | string[] = "."

        One or more file paths to restore. Use "." to restore all tracked files. When using an array, all paths will be included.

      • Optionalflag: RestoreFlag

        An optional Git restore flag like --staged or --source=<commit>. Use this to restore from a specific source or unstage changes.

      Returns Promise<string>

      A promise that resolves with the command's output on success.

      Throws an error if the command fails (e.g., invalid path or ref).

      const git = new Git({ cwd: "/repo" });
      await git.restore("README.md"); // Restore file from index
      await git.restore(".", "--staged"); // Unstage all changes
      await git.restore(["src/", "docs/"], "--source=HEAD~1"); // Restore from previous commit
    • Sets the global Git user email.

      This command configures the user.email value in the global Git configuration. It wraps git config --global user.email "<email>".

      Parameters

      • email: string

        The Git user email address to set.

      Returns Promise<string>

      A promise that resolves when the email has been successfully set.

      await git.setUserEmail("john.doe@example.com");
      const email = await git.getUserEmail();
      console.log(email); // "john.doe@example.com"
    • Sets the global Git user name.

      This command configures the user.name value in the global Git configuration. It wraps git config --global user.name "<name>".

      Parameters

      • name: string

        The Git user name to set. If it includes spaces, it will be quoted automatically.

      Returns Promise<string>

      A promise that resolves when the name has been successfully set.

      await git.setUserName("John Doe");
      const name = await git.getUserName();
      console.log(name); // "John Doe"
    • Creates, deletes, or lists Git tags with optional flags.

      Parameters

      • value: string

        The tag name (or value depending on flags).

      • Optionalflags: TagFlag | TagFlag[]

        Optional tag flags like --annotate, --delete, etc.

      Returns Promise<string>

      A promise that resolves with the result of the Git command.

      git.tag("v1.0.0"); // git tag v1.0.0
      git.tag("v1.0.0", "--delete"); // git tag --delete v1.0.0
      git.tag("v1.0.0", ["--annotate", "--force"]); // git tag --annotate --force v1.0.0