LinuxCommandLibrary

git-graft

Manually define parent commits for initial history

TLDR

Merge all commits not present on the target branch from the source branch to target branch, and delete the source branch

$ git graft [source_branch] [target_branch]
copy

SYNOPSIS

git graft [<commit>...]

PARAMETERS

<commit>...
    A list of commits to be added as parents of the HEAD. These commits are treated as though they were the immediate parents of the current commit. If no commits are specified, git graft reads the commit hashes from the standard input.

DESCRIPTION

The git graft command is a plumbing command in Git primarily used for forging a history of a project by adding a commit as a parent to the current HEAD commit. This is useful when importing a repository from another version control system or when combining two separate Git repositories that need to share a common history.

The command modifies the .git/info/grafts file to record the fake parentage. It doesn't actually rewrite the Git history like git rebase or git filter-branch. It simulates the specified commits as immediate ancestors in the view of the current HEAD.

This simulated history is only visible to your local repository, unless you perform a more permanent history modification and push the result. Using `git replace` command, which is a higher-level approach, is generally preferred.

CAVEATS

Using git graft creates a temporary, local history modification. It doesn't change the actual commit history unless followed by a history rewriting command (like git filter-branch). This is not recommended for shared repositories. Use with caution, as it can complicate collaboration.

USAGE

After running git graft, you typically need to perform a history rewrite operation, such as git filter-branch, to make the grafted history permanent. Otherwise, the grafted history only exists locally and will not be visible to others. Alternatively, the newer git replace is favored, and the index needs to be updated after that, so that the changes are reflected. You can update it by using git update-index --again

INFO/GRAFTS FILE

git graft modifies the .git/info/grafts file. Each line in this file consists of a commit ID followed by one or more commit IDs, separated by spaces. The first commit ID is the commit to which the grafts apply, and the following commit IDs are the commits that should be treated as its parents.

SEE ALSO

git replace(1), git filter-branch(1), git rebase(1)

Copied to clipboard