[Git Basics] Commonly used git commands (1)

1. Create a warehouse

1.1 Create warehouse

  1. Create a repository locally

It is very simple to create a Git warehouse locally. You only need to enter the directory to be used as a warehouse on the command line, and then execute the following command:

git init

In this way, an empty Git warehouse will be created in the current directory. At this time, there will be an additional .gitdirectory under the warehouse directory. .gitThere are many files about git management in the directory, and we don’t need to care about the things in it.

After you have a warehouse, you can use git add and git commit to add files to be tracked in the warehouse and submit the modified content.

  1. Create a repository on GitHub

GitHub is a very popular code hosting platform where you can create public or private repositories to manage your code. The steps to create a warehouse are as follows:

  • Log in to your GitHub account
  • Click the plus sign in the upper right corner and select "New repository"
  • Enter the warehouse name, description, visibility and other information
  • Click "Create repository"

After the creation is successful, the local code can be uploaded to the GitHub repository through the Git command.

  1. Create a warehouse on GitLab

GitLab is another popular code hosting platform where you can also create public or private repositories to manage your code. The steps to create a warehouse are as follows:

  • Log in to your GitLab account
  • Click "New project" in the left menu bar
  • Enter the warehouse name, description, visibility and other information
  • Click "Create project"

After the creation is successful, the local code can be uploaded to the GitLab repository through the Git command.

1.2 git add and git commit

① git add

It is used to add files and modifications in the working directory to the Git staging area, ready to be submitted to the Git repository. The role of the Git add command is to mark the modified code as "modified" for subsequent submission to the Git repository.

The Git add command can be used in the following ways:

  1. Add a single file
git add <file>

Where <file> is the name of the file to be added to the staging area. For example, to add the hello.txt file to the Git staging area, execute the following command:

git add hello.txt
  1. Add multiple files
git add <file1> <file2> ...

Multiple files can be added at the same time, for example:

git add hello.txt world.txt
  1. add all files
git add .

or

git add *

This command will add all files in the current directory to the Git staging area.

The difference between the two is:

  • git add .Only all files and folders in the current directory will be added to the staging area, excluding .hidden files starting with .
  • git add *will add all files and folders in the current directory to the staging area, including .hidden files starting with .

Therefore, when using the git add command, it is recommended git add .to avoid unnecessary files and folders being added to the staging area.

  1. Add all files in a directory
git add <directory>

You can add all files in a directory, for example:

git add src/

It should be noted that executing the git add command will only add the modified code to the Git temporary storage area, and you also need to execute the git commit command to submit the modified code to the Git warehouse. If you do not execute the git commit command, the changes in the temporary storage area will not be saved to the Git repository.

In short, the Git add command is a very important command in the Git version control system. It can help developers effectively manage code modification records and ensure code traceability and maintainability.

② git commit

It is used to commit the modification records in the local working directory to the local repository. When executing the git commit command, you need to specify the submitted information. This information usually includes the modified description and author information, and you can add some tags and comments.

The Git commit command is used as follows:

git commit -m "commit message"

Among them, the -m option is used to specify the submitted information, which can be any text, but a concise description is best. After executing this command, Git will submit all the modified records that have been temporarily stored to the local warehouse and generate a unique submission ID. This ID can be used to view commit records, rollback changes, etc.

In addition to the -m option, you can also use other options to specify the submitted content, author, time and other information, for example:

git commit -a -m "commit message"  # 提交所有已经跟踪的文件
git commit --amend -m "new commit message"  # 修改最近一次提交的信息

In short, Git commit is a very important command in the Git version control system. It can help developers effectively manage code modification records and ensure code traceability and maintainability.

③ Work area, temporary storage area and warehouse

In Git, there are three important concepts: workspace, staging area, and warehouse.

  • Workspace: refers to the directory we actually operate, which is what we often call the project directory, where we can add, modify, and delete files.
  • Temporary storage area: Also called index or cache area, it is a place to temporarily store our modified files. Git will store our modified files here, waiting for us to execute the git commit command to submit them to the warehouse.
  • Warehouse: also called version library, is the place where all versions of the Git project are stored. It contains all the files we submit to the temporary storage area, as well as relevant information for each submission (such as submitter, submission time, submission information, etc.) .

The Git workflow is like this: we add, modify, and delete files in the workspace, then use the git add command to add the modified files to the temporary storage area, and finally use the git commit command to submit the files in the temporary storage area to the warehouse . In this way, we can save our project version in the warehouse, and can easily perform version control and management.
insert image description here

2. Create a git server

2.1 Server:

Create a folder and use inside the folder:

git init --bare

insert image description here

In this way, we have created a bare warehouse on the server. Here is a brief introduction to the bare warehouse:

A bare warehouse is a warehouse without a workspace. It only contains version information in the Git database and has no actual file content, so it does not support file modification and submission operations. It is usually used to build remote servers for code sharing and management.

A bare repository differs from a normal Git repository in that it has no workspace and therefore does not contain the actual file content of the project, only the version information from the Git database. This makes the bare warehouse more lightweight, takes up less space, and is more suitable for multi-person collaborative development and code sharing.

When using git init --barethe command to create a bare warehouse, you need to specify a directory as the storage path of the warehouse. After executing this command, Git will create a bare warehouse under the specified path, and generate some necessary files and directories in it, such as HEAD, refs, objects, etc. At this point, the bare repository can already be cloned and pulled by other developers.

When using a bare warehouse, you usually need to do the following:

  • Clone warehouse: other developers can use the git clone command to clone the bare warehouse to the local for development and management
  • Pull code: other developers can use the git pull command to pull the latest code from the bare repository
  • Push code: Other developers can use the git push command to push local code to the bare warehouse for sharing and management.

The use of bare warehouse needs to be cautious, because it has no workspace, so it does not support file modification and submission operations. At the same time, all operations in the bare warehouse are operations against the Git database.

2.2 Local

First of all, we need to use the SSH protocol to operate, the steps are as follows:

  • Generate SSH key: Use the ssh-keygen command to generate an SSH key, the command format is:

    ssh-keygen -t rsa -C "[email protected]"
    

    Among them, the -t parameter indicates the key type, and RSA is used here; the -C parameter indicates a comment, which can be filled with a personal email address, or can be ignored.

  • Add the public key to the remote server: Add the generated public key (stored in the C:/Users/[username]/.ssh/id_rsa.pub file by default) to the remote server for authentication and store it in the server's ~/.ssh/authorized_keys.

  • Configure the SSH agent: use the ssh-agent command to start the SSH agent, and add the generated private key to the agent. The command format is:

    eval "$(ssh-agent -s)"
    ssh-add ~/.ssh/id_rsa
    

    This avoids having to enter a password every time you do a Git operation.

  • Use the SSH protocol in Git: When using the SSH protocol in Git to operate, you need to change the address of the remote server to the address of the SSH protocol, the format is:

    git ssh://<user_name>@<server_address>:<repository_path>
    

    Among them, server_address represents the address of the remote server, and repository_path represents the path of the warehouse.
    For example, clone the warehouse in the server:

    git clone ssh://root@<server_address>:/root/learn-git
    

When using the SSH protocol for operations, care must be taken to protect the private key to avoid disclosure. At the same time, if you cannot operate through the SSH protocol, you can try to use the HTTPS protocol to operate.

2.3 Modify configuration information

git config is a command for setting and reading configuration information in Git, which can be used to set global or local configuration of Git, read configuration information of Git, etc.

Commonly used git config commands include:

  • git config --global user.name "your_name": Set the global username for Git.
  • git config --global user.email "[email protected]": Set the global email address of Git.
  • git config --global core.editor "your_editor": Sets the global text editor for Git.
  • git config --global color.ui true: Enable Git's global color output.
  • git config --list: List all configuration information of Git.
  • git config --unset key: Delete the specified configuration information of Git.
  • git config --unset-all key: Delete all specified configuration information of Git.

Among them, the –global parameter indicates the global configuration, that is, the configuration applies to all Git repositories of the current user. If the --global parameter is not used, it means local configuration, which is only applicable to the current warehouse.

You can view Git configuration information with the following command:

git config --list

The output contains all Git configuration information, including username, email address, text editor, color output, etc. If you need to modify the configuration information, you can use the git config command to reset it.

The first two usernames and email addresses must be configured, and it will be displayed in each submission.

3. The basic principles of git

insert image description here

3.1 Four regions

  • Workspace: The workspace is where the project code is usually stored
  • Index/Stage: Temporary storage area, used to temporarily store changes, in fact it is just a file, saving the list information of the files to be submitted
  • Repository: The warehouse area or version library is the place where data is safely stored. There are all submitted versions of data in it, where HEAD points to the latest version put into the warehouse
  • Remote: The remote warehouse, the server hosting the code, can be simply considered as a computer in the project team for remote data exchange

3.2 Workflow

  1. Add and modify files in the working directory
  2. Add the files that need version management to the staging area
  3. Commit the files in the temporary storage area to the git warehouse
  4. Push the local modification to the remote warehouse, if it fails, go to step 5
  5. git pull pulls the modification of the remote warehouse to the local, if there is a conflict, you need to modify the conflict, go back to the third step

Therefore, the files managed by git have three states: modified (modified), staged (staged), and submitted (committed)

3.3 Four states of files

insert image description here

In Git, you can use git statusthe command to view the status of the current file, where red means that the file has been modified but not staged, green means that the file has been staged but not submitted, and no color means that the file has not been modified. Through these states, we can clearly understand the changes of the files, which is convenient for us to perform version control.

  • Untracked: Untracked, this file is in the folder, but it has not been added to the git library, does not participate in version control, and the status becomes Staged through git add
  • Unmodify: The file has been put into the repository and has not been modified, that is, the content of the file snapshot in the repository is exactly the same as that in the folder. There are two places for this type of file. If it is modified, it becomes Modified. If you use Move out of the git rmrepository , it becomes an Untracked file
  • Modified: The file has been modified, only modified, and no other operations have been performed. This file also has two destinations. It can enter the temporary staged state through git add, discard the modification when using it, and return git checkoutto the unmodified state. This git checkout is from the library Take out the file and overwrite the current modification
  • Staged: Temporary storage state, and the execution git commitwill synchronize the modification to the library. At this time, the files in the library and the local files become consistent again, and the files are in the Unmodify state

① git rm

git rmcommand can be used to remove files from a Git repository. It has two usages:

  1. git rm <file>: Delete the specified file from the Git repository, and add the delete operation to the temporary storage area.

  2. git rm --cached <file>: Delete the specified file from the Git warehouse, but do not delete the local file, only add the delete operation to the temporary storage area.

After using git rmthe command to delete the file, you need to git commitsubmit the modification in the temporary storage area through the command to completely delete the file from the Git repository.

It should be noted that if the deleted file has been modified by others and submitted to the warehouse, there git rmwill be a conflict when you delete the file locally using the command and then push the modification to the remote warehouse. At this point, conflicts need to be resolved through a merge operation.

② git checkout

git checkoutCommands can be used to switch branches, roll back code, and undo changes. It has several usages:

  1. Switch branch: git checkout <branch>, switch the current working directory to the specified branch.

  2. Rollback code: git checkout <commit> ., rolls back all files in the current working directory to the specified commit version.

  3. Undo modification: git checkout -- <file>, restore the specified file to the state of the last commit.

  4. Create new branch: git checkout -b <new_branch>, create a new branch and switch to it.

It should be noted that git checkoutwhen using commands to switch branches or roll back code, all uncommitted changes in the current working directory will be cleared. If you need to save the modification, you need to stage or submit the modification to the warehouse first.

4. Submit your changes gracefully

4.1 Detailed explanation of git commit command

  • git commit file1.name file2.name file3.name .. –m “commit messages”:commit refers to submitting the modification to the local warehouse, file*.namereferring to committhe file with –mthe following content refers to the submitted information, that is, remarks
  • git commit –a –m “commit messeages”: The added -aparameters will submit all the modifications (including delete operations) in the current temporary storage area, but those that have not been added to the temporary storage area will not be submitted. There are many blogs on the Internet that say that the parameters will submit the -aunadded The file was also submitted, this statement is wrong.
  • git commit: We may have forgotten to enter -mthe parameters due to shaking hands, and entered directly git commit, so the following interface appeared, that is, opened a vim editing interface, typed the "i" key to save, entered the message to be added, and typed "ESC" Press the key to exit the editing interface, and then type ":wqa" to save the message content and submit the modification. If you type ":q", the submission will be cancelled.
    insert image description here
  • git commit --amend: This is also a command we often use. It will append this commit to the previous commit content.

4.2 Format of git commit

The Angular team has developed a series of specifications to help developers better use Git for Angular project development. Here are some of the specifications:

  1. Branch naming convention
  • feature/xxx: Indicates the branch of the new feature, xxx is the feature name;
  • bugfix/xxx: Indicates the branch that fixes the bug, where xxx is the name of the bug;
  • hotfix/xxx: Indicates the emergency repair branch, xxx is the repair name;
  • release/xxx: Indicates the branch of the release version, where xxx is the version number;
  • refactor/xxx: indicates the branch of the refactored code, and xxx is the refactored name;
  • docs/xxx: Indicates the branch of the document modification, xxx is the document name;
  • test/xxx: Indicates the branch of the test case, and xxx is the test name.
  1. submit information specification

Every time you submit code, you need to follow the format below:

<type>(<scope>): <subject>
<BLANK LINE> 
<body> 
<BLANK LINE> 
<footer>

In addition to the blank line <BLANCK LINE>, the remaining three correspond to:

  • <type>(<scope>): <subject>Title line, required, describes the main modification type and content
  • <body>: The subject content, describing why it was modified, what kind of modification was made, and the development idea, etc.
  • <footer>: footer note, put Breaking Changes or Closed Issues

Among them, type indicates the submission type, which can be:

  • feat: new features
  • fix: modify the problem
  • refactor: code refactoring
  • docs: document modification
  • style: code format modification, note that it is not css modification
  • test: test case modification
  • chore: other modifications, such as build process, dependency management

scope indicates the scope of the commit's influence, that is, the affected modules or components, such as: route, component, utils, build...
subject indicates the overview of the commit, it is recommended to comply with 50/72 formatting
body indicates the specific modification content of the commit, which can be divided into multiple lines, it is recommended Comply with 50/72 formatting
footer to indicate some remarks, usually a link to BREAKING CHANGE or fixed bug, or feature and other information

  1. version number specification

The Angular team adopts the SemVer (semantic version number) specification, namely MAJOR.MINOR.PATCH, where:

  • MAJOR: major version number, indicating incompatible API changes;
  • MINOR: Minor version number, indicating new backward compatible features;
  • PATCH: Revision number, indicating a backward compatible bug fix.
  1. Merge Request Specification

Every time you submit a merge request, you need to follow this format:

[<type>(<scope>)]: <subject>

Among them, type, scope, and subject are the same as the submission information specification.

The above are some specifications formulated by the Angular team. Compliance with these specifications can improve team collaboration efficiency and reduce code maintenance costs.

You can also use the git cmmit template to standardize commits

  • ~/.gitconfigadd in the file

    [commit]
                  template=~/.gitmessage
    
  • Add ~/.gitmessage file. For example, a commit message might look like this:

    feat(login): add remember me feature
    
    Add a remember me checkbox on the login page to allow users to stay logged in between sessions.
    
    Fixes #123
    

    In this submission information <type>is feat, which means a new feature, <scope>is login, which means the scope of impact is the login module, <subject>and is add remember me feature, which means a brief description of the added remember me feature. <body>Describes the detailed modification content, and <footer>Fixes #123 in it indicates that issue #123 is associated.

4.3 git-commitizen

  1. Download the corresponding version of the nodejs package and install it
  2. Global installation using npm tool
  3. Then in the project directory, run the following command to make it support Angular's Commit message format
  4. If we want every project using git to follow this standard, we can use the following command to set it globally
  5. Create a .czrc file in your home directory and point the path to the commitizen adapter installed above
  6. Now we can use git cz to submit our commit message in each git project. Of course, we can also configure Commitlint to do automatic detection. If the inspection fails, the submission can be rejected.
  7. If all our commit information is filled in according to this format, we can use the following command to generate a changelog when releasing the version

4.4 Push to remote branch

The git push command is used to push the update of the local branch to the remote host. Its format is similar to the git pull command

git push <远程主机名> <本地分支名>:<远程分支名>

Note that the branch push order is written as <source>:<destination>, so git pull is <remote branch>:<local branch>, and git push is <local branch>:<remote branch>. For example:

git push origin master:refs/for/master

If the remote branch name is omitted, it means that the local branch will be pushed to the remote branch that has a "tracking relationship" with it (usually the two have the same name). If the remote branch does not exist, it will be newly created:

git push origin master

The above command means to push the local master branch to the master branch of the origin host. If the latter does not exist, it will be created.
insert image description here

If the local branch name is omitted, it means to delete the specified remote branch, because this is equivalent to pushing an empty local branch to the remote branch:

git push origin :master # 等同于 git push origin --delete master

The above command means to delete the master branch of the origin host.

If there is a tracking relationship between the current branch and the remote branch, both the local branch and the remote branch can be omitted:

git push origin

The above command means to push the current branch to the corresponding branch of the origin host.

If the current branch has only one tracking branch, the hostname can be omitted:

git push

In addition to the above basic usage, the Git push command has some other options, such as:

  • --force: Forcibly push the local branch, that is, overwrite the remote branch;
  • --tags: Push the local tag to the remote code base;
  • --all: Push all local branches to the remote code base.

It should be noted that git pushthe command will push the local submission to the remote code base, so it is recommended to submit the changes in the local code base to the local warehouse before pushing.

4.5 git push conflict resolution

Conflicts usually occur because the codes of the local branch and the remote branch are inconsistent, making it impossible to merge directly. Details are as follows:

  1. Both the local branch and the remote branch modified the same part of the same file at the same time.
  2. Both the local branch and the remote branch have modified the same file, but the modified parts are different. At this time, Git can automatically merge.
  3. Both the local branch and the remote branch have deleted the same file, and Git cannot automatically merge it at this time.
  4. Both the local branch and the remote branch have created the same file, and Git can automatically merge it at this time.

insert image description here

When a conflict occurs, Git will prompt the user to manually resolve the conflict. The user needs to resolve the conflict according to the prompt, and then submit the code again. If multiple people modify the same part of the same file at the same time, there needs to be an agreement about who resolves the conflict, or everyone resolves the conflict on their own local branch before merging into the master branch.


The steps for git to resolve conflicts are as follows:

  1. First call git pullto pull the branch down:
    insert image description here

  2. Then the content of the conflict will be recorded in the conflicting file, head represents the content of the current branch, and the hash value represents the content in the current remote warehouse:
    insert image description here

  3. To resolve conflicts manually:
    insert image description here

  4. save the modified file

  5. Execute git addthe command to add the modified file to the temporary storage area

  6. Execute git committhe command and submit the modification

  7. Execute git pushand submit to the remote warehouse

If git commita prompt similar to the following appears when executing the command:

Automatic merge failed; fix conflicts and then commit the result.

It means that there are still unresolved conflicts, and you need to continue to resolve the conflicts. Repeat the above steps until all conflicts are resolved.

If you don't want to resolve conflicts, you can use git merge --abortthe command to unmerge.

Pull to view in other branches:
insert image description here

Visual display:
insert image description here

5. Supplement: the difference between git push and git pull

5.1 git push

Basic format:

git push [远程仓库名称] [本地分支名称]:[远程分支名称]

Things to note:

  • Remote warehouse name: usually origin, indicating the alias of the remote warehouse
  • Local branch name: the local branch that needs to be pushed
  • Remote branch name: the branch pushed to the remote repository

In most cases, a simplified format can be used:

git push

This command will push the currently active branch to the remote branch it is associated with.

5.2 git pull

Basic format:

git pull [远程仓库名称] [远程分支名称]:[本地分支名称]

Things to note:

  • Remote warehouse name: usually origin, indicating the alias of the remote warehouse
  • Remote branch name: the branch that needs to be pulled from the remote warehouse
  • Local branch name: Merge the fetched remote branch into the local branch.

In most cases, a simplified format can be used:

git pull

This command will pull and merge the remote branch associated with the current active branch into the local branch.

5.3 Notes

  • Make sure you have configured a remote warehouse, usually using git remote add [远程仓库名称] [远程仓库地址]Add Remote Warehouse.
  • Before pushing, make sure you have associated your local branch with the remote branch, you can use git branch --set-upstream-to=[远程仓库名称]/[远程分支名称] [本地分支名称]associated branches.
  • Before pulling, make sure your local workspace and staging area are clean to avoid merge conflicts. If you have uncommitted changes, you can use git stashSave Changes first, and then use Revert Changes after the pull is complete git stash apply.
  • If you encounter a merge conflict, go through it and resolve the conflict before committing your changes.

5.4 Explanation of terms and viewing branches

Remote repository name: The remote repository name is a short name used to represent the remote Git repository. By default, when you clone a project from a remote repository, the name of the remote repository is set to origin. You can view the remote warehouse name with the following command:

git remote -v

This will list all remote repositories and their corresponding URLs. If you want to add a new remote, you can use the following command:

git remote add [远程仓库名称] [远程仓库地址]

Remote branch name: The remote branch name is the name of a branch in the remote repository. In general, the format followed by remote branch names [远程仓库名称]/[分支名称]. For example, origin/masterto represent a branch originin the remote repository named master. You can view all remote branches with the following command:

git branch -r

Local branch name: The local branch name is the name of a branch in the local Git repository. You can view all local branches with the following command:

git branch

This will list all local branches, marked with an asterisk (*) in front of the currently active branch.

To view the relationship between the local branch and the remote branch, you can use the following command:

git branch -vv

This will show each local branch and its associated remote branch (if any).

Guess you like

Origin blog.csdn.net/weixin_52665939/article/details/130083898