Git Lecture 12 Git Branch Management

Git branch management

In Git, branch management is a core concept that allows team members to develop multiple tasks, features, or fix different bugs in parallel without interfering with each other. Branch management can help you better organize and manage the code of your project. The following will introduce some commonly used branch management operations.

5.1 Create and switch branches

Git branches are independent copies of a project's code that can be modified on different development paths. The operation of creating and switching branches is very simple, just execute the following commands:

# 创建新分支
$ git branch <branch-name>

# 切换到新分支
$ git checkout <branch-name>
或者
git switch  <branch-name>

For example, if you want to create a feature-loginnew feature branch called and switch to that branch, you can execute the following command:

$ git branch feature-login
$ git checkout feature-login

5.2 Merging branches

After a branch has finished developing, you may wish to merge it into master or another branch. Git provides a variety of ways to merge branches, the most commonly used is to use git mergecommands.

# 切换到目标分支
$ git checkout <target-branch>

# 合并源分支到目标分支
$ git merge <source-branch>

For example, if you want to feature-loginmerge the branch into the master branch, you can execute the following command:

$ git checkout main
$ git merge feature-login

5.3 Resolving Conflicts

When merging branches, if two branches modify the same line of code, Git cannot automatically resolve the conflict and needs to be resolved manually. The steps to resolve conflicts are as follows:

  1. Git will use special markers to identify conflicting code segments in conflicting files. You need to open the file and manually edit the conflicting parts.

  2. After resolving conflicts, save the file, and execute the following command to remove the conflict markers from the file:

    $ git add <conflicted-file>
    
  3. Finally, do a merge commit:

    $ git commit
    

Conflict resolution is a common task in collaborative development that requires consultation and cooperation with team members.

5.4 Delete branch

When work on a branch is complete, you can choose to delete it to keep the codebase clean. Deleting a branch does not delete the commits on the branch, they are still accessible through other branches or refs.

# 删除本地分支
$ git branch -d <branch-name>

# 强制删除分支(丢失未合并的更改)
$ git branch -D <branch-name>

For example, to

To delete feature-loginthe local branch named, you can execute the following command:

$ git branch -d feature-login

5.5 Create a new branch based on a remote/local branch

git checkout -b main origin/master
git checkout -b feature/local-feature origin/feature/remote-feature

Guess you like

Origin blog.csdn.net/huanglu0314/article/details/131157462