この投稿では、Gitでの以前のコミットからブランチを作成する方法について説明します。

1.git-branch

以前のコミットからブランチを作成するには、 git-branch 指図。

git branch <branchname> [<commit-id>]

これにより、新しいブランチが作成されます。 branchname その頭が指定されたものを指している commit-id。たとえば、次の例では、指定されたコミットハッシュから開発ブランチを作成します。

git branch develop 04c900c9d9c325720ed5c807b46272a500c22a97

完全なSHA-1ハッシュを使用するか、部分的なハッシュを提供することで、コミットを参照できます。部分ハッシュには、40文字のSHA-1ハッシュの最初の数文字が含まれ、少なくとも4文字の長さで明確である必要があります。

git branch develop 04c900c

コミットがその祖先を介して参照することもできます。

git branch develop HEAD~4

The GITマニュアル コミットを参照するすべての方法を指定します。

 
新しいブランチを作成したら、新しいブランチをリモートリポジトリにプッシュする必要があります。これは、を使用して行うことができます git push:

# Create a new branch from the previous commit's hash
git branch develop 04c900c
 
# Push the new branch to the remote repository
git push --set-upstream origin develop
 
# Check out the new branch
git checkout develop

これを示す実例を次に示します。

create a new branch with git branch

2.git-checkout

ここでのアイデアは、特定のコミットをチェックアウトしてから、そのコミットからブランチを作成することです。

# Check out specified commit
git checkout <commit-id>
 
# Create a new branch
git checkout -b <branchname>

これを1つのステップに簡略化できます。

# Create a new branch from the specified commit
git checkout -b <branchname> [<commit-id>]

新しいブランチを作成したら、それをリモートリポジトリにプッシュできます。

# Push the new branch to the remote repository
git push --set-upstream origin <branchname>

create a new branch with git checkout

3.git-reset

または、現在のブランチのヘッドから新しいブランチを作成し、特定のコミットにハードリセットすることもできます。これは、gitresetによって簡単に実行できます。

# Create a new branch from HEAD
git checkout -b <branchname>
 
# Remove the commits made after <commit-id>
git reset --hard <commit-id>
 
# Push the new branch to the remote repository
git push --set-upstream origin <branchname>

これを示す実例を次に示します。

create a new branch with git reset

4. GitHub

最後に、GitHubは、特定のコミットから新しいブランチを作成する簡単な方法を提供します。手順は次のとおりです。

1. GitHubのリポジトリに移動し、[xcommits]タブで特定のコミットを見つけます。

2.その特定のコミットについて、[履歴のこの時点でリポジトリを参照する]リンクをクリックします。

Select commit id in Github

3.'ツリーをクリックします。 sha-1ハッシュ'ドロップダウンで、'ブランチの検索または作成'入力ボックスにブランチ名を入力し、ブランチの作成オプションをクリックします。

create branch from commit id in Github

4.以上です。ブランチが作成されます。 git fetchを実行して、ローカルにプルします。

これで、Gitでの以前のコミットからブランチを作成できます。