Basic commands and usage of git and github

Basic commands and usage of git and github

git and GitHub basics

version control

  1. Version control software is alog file changes, in order to refer to the system of specific version revisions in the future, so it is sometimes called "version control system".
  2. Easy to operate, easy to compare, easy to trace back, not easy to lose, and easy to collaborate.

Classification of Version Control Systems

  1. Local version control system: One-click run to toolize the operation of maintaining file versions.

Features:
Use software to record different versions of files, which improves work efficiency and reduces the error rate of manual version maintenance. Disadvantages:

Stand-alone operation, does not support multi-person collaborative development
② After the version database fails, all historical update records will be lost

  1. Centralized version control system (for example: svn): networked operation, supports multi-person collaborative operation, poor performance and poor user experience

Features:
based onserver, client① The
server keeps all update records of the file
② The client only keeps the latest file version
Advantages: Network operation, support multi-person collaborative development
Disadvantages:
① Does not support offline submission of version updates
② After the central server crashes, everyone cannot work normally
③ After the version database fails, all historical update records will be lost

  1. Distributed version control system (eg: git): network operation, support multi-person collaboration, excellent performance, good user experience

Features:
Based on server and client operating mode⚫The
server saves all updated versions of files⚫The
client is a complete backup of the server, not just the latest version of the file.
Advantages:
①Network operation, support multi-person collaborative development
②Client disconnected from the network Afterwards, it supports offline local submission of version updates
③ After the server fails or is damaged, any client backup can be used for recovery

git

Git basic concepts

Git is an open source distributed version control system, which is currently the most advanced and popular version control system in the world. Versioning of very small to very large projects can be handled quickly and efficiently.

Features of Git The
reason why Git is fast and efficient mainly depends on its following two features:
① Directly record snapshots instead of difference comparison
② Almost all operations are performed locally

SVN diff comparison

Traditional version control systems (such as SVN) are difference-based version control. They store a set of basic files and the differences of each file gradually accumulated over time.
Benefits: Save disk space
Disadvantages: Time-consuming and inefficient
Every time you switch versions, you need to apply each difference on the basis of the basic files to generate the files corresponding to the target version

Git record snapshot

Git snapshot is to regenerate a new file based on the original file version, similar to backup. For efficiency, if the file has not been modified, Git does not re-store the file, but only keeps a link pointing to the previously stored file.
Disadvantage: takes up a lot of disk space.
Advantage: version switching is very fast, because each version is a complete file snapshot, and the snapshot of the target version can be directly restored when switching versions.
Features: space for time

Most operations in Git only require access to local files and resources, and generally do not require information from other computers on the network.
Features:
① You can still manage the version of the project locally after disconnecting from the
network ② After connecting to the Internet, you can synchronize the locally modified records to the cloud server

Three regions in git

The project managed by Git has three areas, namely the work area, the staging area, and the Git warehouse.
work area: the area where the work is processed
storage cache: Temporary storage area for completed work, waiting to be submitted
Git repository: final storage area

Three states in Git

Modified modified: Indicates that the file has been modified, but the modified result has not been placed in the temporary storage area
staged: Indicates that the current version of the modified file is marked to be included in the list of the next submission
Committed: Indicates that the file has been safely saved in the local Git warehouse.
Note:
⚫ The file in the workspace has been modified, but it has not been placed in the temporary storage area, which is the modified state.
⚫ If the file has been modified and put into the staging area, it belongs to the staged state.
⚫ If a specific version of the file is saved in the Git repository, it belongs to the committed state.

Basic Git workflow

[External link image transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the image and upload it directly (img-L5dIUDrR-1648949129726)(./images/gitBasicworkflow.png)] The basic Git workflow is as follows: ①
At
work Modify the file in the
temporary storage area ② Temporarily store the changes you want to submit next time
③ Submit the update, find the file in the temporary storage area, and permanently store the snapshot in the Git warehouse

Install and configure Git

Choose to download the corresponding Git installation package: https://git-scm.com/downloads

Configure user information

$ git config --global user.name "zsn"
$ git config --global user.email "[email protected]"

git global configuration file

The user name and email address configured by git config --global user.name and git config --global user.email will be written to the C:/Users/username folder/.gitconfig file. This file is Git's global configuration file, which can take effect permanently after being configured once.
If the --global option is used, the command only needs to be run once to take effect permanently.

Check configuration information

Use the terminal command to quickly view the global configuration information of Git:

# 查看所有的全局配置项
git config --list --global
# 查看指定的全局配置项
git config user.name
git config user.email

get help information

# 打开git config 命令的帮助信息
git help config
# 获取git config 命令的快速参考
git config -h

Basic operations of Git

1. Two ways to get Git repository

① 将尚未进行版本控制的本地目录转换为 Git 仓库
② 从其它服务器克隆一个已存在的 Git 仓库

2. Initialize the repository in an existing directory

If you have a project directory that has not been under version control and want to use Git to control it, you need to perform the following two steps:

① 在项目目录中,通过鼠标右键打开“Git Bash”
② 执行 git init 命令将当前的目录转化为 Git 仓库

The git init command will create a hidden directory named .git. This .git directory is the Git repository of the current project, which contains the initial necessary files, which are a necessary part of the Git repository.

3. 4 states of files in the workspace

Each file in the workspace may have 4 states, which are divided into two categories
Untracked (Untracked)

  1. Not managed by Git: Files not managed by Git
  2. Managed by Git:
    • The content of the file in the unmodified (Unmodified) workspace is consistent with the content of the file in the Git repository
    • The content of the file in the modified (Modified) workspace is inconsistent with the content of the file in the Git repository
    • The modified files in the Staged workspace have been placed in the temporary storage area, and the modified files are ready to be saved to the Git repository

The ultimate result of Git operations: keep the files in the workspace in an "unmodified" state.

4. Check the status of the file

The git status command to see what state the file is in.
git status -s or –short displays the file status in a streamlined manner

Newly created files appear under Untracked files (untracked files).
An untracked file means that Git didn't have those files in a previous snapshot (commit); Git doesn't automatically track them unless you explicitly tell it "I need to use Git tracking to manage this file".

Untracked files are preceded by a red ?? mark
Newly added files to the staging area are marked with a green A in front of them

5. Track new files

Start tracking a file with the command git add

git add filename

Run the git status command, and you will see that the file is under the line Changes to be committed, indicating that it has been tracked and is in a temporary state

6. Submit an update

There are files in the temporary storage area waiting to be submitted to the Git repository for storage. You can execute the git commit command to submit, where the -m option is followed by this submission message, which is used to further describe the content of the submission

git commit -m "新建了index.html文件"

7. Make changes to submitted files

The file has been tracked by Git, and the content of the file in the workspace is consistent with that in the Git warehouse. After modifying the file content, run the git status and git status -s commands again. The file appears under the line Changes not staged for commit, indicating that it has been tracked The content of the file has changed, but it has not been put to the staging area.

Modified files that have not been placed in the temporary storage area are marked with a red M in front of them

8. Staging modified files

The files in the workspace have been modified. If you want to temporarily store this modification, you need to run the git add command again

The git add command has three functions:
① You can use it to start tracking new files
② Put tracked and modified files into the temporary storage area
③ Mark conflicting files as resolved

9. Submit the staged file

git commit -m "commit message" command, you can submit the snapshot of index.html recorded in the temporary storage area to the Git warehouse for storage

git commit -m "修改了index.html文件"

10. Undo changes to the file

Undoing the modification of the file refers to: put thework areaThe modification of the corresponding file in , restores to the version saved in the Git repository.
Result of the operation: all modifications will be lost and cannot be recovered! The risk is relatively high, please operate with caution!

git checkout -- index.html

The essence of the undo operation: Overwrite the specified file in the workspace with the file saved in the Git repository.

11. Add multiple files to the temporary storage area at one time

git add .
warning: LF will be replaced by CRLF in CSS/reset.css.
The file will have its original line endings in your working directory
在文本处理中,CR(CarriageReturn),LF(LineFeed),CR/LF是不同操作系统上使用的换行符

1.git 的 Windows 客户端基本都会默认设置 core.autocrlf=true,设置core.autocrlf=true, 只要保持工作区都是纯 CRLF 文件,编辑器用 CRLF 换行,就不会出现警告了;
2.Linux 最好不要设置 core.autocrlf,因为这个配置算是为 Windows 平台定制;
3.Windows 上设置 core.autocrlf=false,仓库里也没有配置 .gitattributes,很容易引入 CRLF 或者混合换行符(Mixed Line Endings,一个文件里既有 LF 又有CRLF)到版本库,这样就可能产生各种奇怪的问题。

12. Unstaged files

To remove the corresponding file from the staging area

git reset HEAD filename

13. Skip using the staging area

The standard workflow of Git is workspace → temporary storage area → Git warehouse, but sometimes it is a bit cumbersome to do so. At this time, you can skip the temporary storage area and directly submit the changes in the workspace to the Git warehouse. At this time, Git works The process is simplified to workspace → Git repository.

git commit -a -m "描述信息"

14. Remove files

There are two ways to remove files from a Git repository:

① 从 Git 仓库和工作区中同时移除对应的文件
git rm -f filename
② 只从 Git 仓库中移除指定的文件,但保留工作区中对应的文件
git rm --cached filename

15. Ignore files

Generally, we always have some files that don't need to be managed by Git, and we don't want them to always appear in the list of untracked files. In this case, we can create a configuration file called .gitignore that lists matching patterns for files to ignore.

The format specification of the file .gitignore is as follows:
① Comments start with #
② Directories end with /
③ Prevent recursion at the beginning of / ④ Negation
starts with !
⑤ You can use glob pattern to match files and folders (glob refers simplified regex)

16. glob pattern

The so-called glob pattern refers to a simplified regular expression:
① Asterisk * matches zero or more arbitrary characters
② [abc] matches any character listed in square brackets (this case matches an a or matches a b or Match a c)
③ A question mark? Only match one arbitrary character
④ Use a dash to separate two characters in square brackets, indicating that all within the range of these two characters can be matched (such as [0-9] means matching all 0 to 9)
⑤ two asterisks means to match any intermediate directory (for example, a//z can match a/z, a/b/z or a/b/c/z, etc.)

.gitignore文件的例子

# 忽略所有的.a文件
*.a

# 跟踪所有的lib.a,即便在前面忽略了.a文件
!lib.a

# 只忽略当前目录下的TODO文件,而不忽略其他文件夹的TODO
/TODO

# 忽略任何目录下名为build的文件
build/

# 忽略doc/notes.txt,但不忽略doc/server/arch.txt
doc/*.txt

# 忽略doc/目录及其所有子目录下的.pdf文件
doc//*.pdf

17. View commit history

# 按时间先后顺序列出所有的提交历史,最近的提交排在最上面
git log

# 只展示最新的两条提交历史,数字可以按需修改
git log -2

# 在一行上显示最近的俩条提交历史
git log -2 --pretty=oneline

# 在一行上展示最近的两条提交历史,并自定义输出的格式
#%h提交的简写哈希值 %an作者名字 %ar作者修订日期,按多久以前的方式显示 %s提交说明
git log -2 --pretty=format:"%h | %an | %ar | %s"

18. Roll back to the specified version

# 在一行上显示所有的提交历史
git log -2 --pretty=oneline

# 使用git reset --hard命令,根据指定的提交ID回退到指定的版本
git reset --hard <CommitID>

# 在旧版本中使用git reflog --pretty=oneline 命令,查看命令操作的历史
git reflog --pretty=oneline

# 再次根据最新的提交ID,跳转到最新的版本
git reset --hard<CommitID>

GitHub

Open source is open source code (Open source code). Open source does not mean that there is no limit at all. In order to limit the scope of use of users and protect the rights of authors, every open source project should abide by the open source license agreement (Open Source License).

5 Common Open Source License Agreements

① BSD(Berkeley Software Distribution)
② Apache Licence 2.0
GPL(GNU General Public License)
⚫ An infectious open source agreement that does not allow modified and derived codes to be released and sold as closed-source commercial software
⚫ The most famous software project using GPL is: Linux
④ LGPL (GNU Lesser General Public License)
MIT(Massachusetts Institute of Technology, MIT)
⚫ It is currently the least restrictive agreement, the only condition: in the modified code or distribution package, the original author's license information must be included
⚫ Software projects using MIT include: jquery, Node.js

Reference blog https://www.runoob.com/w3cnote/open-source-license.html

Open source project hosting platform

A website dedicated to storing the source code of open source projects for free is called an open source project hosting platform. At present, there are three well-known open source project hosting platforms in the world:
⚫ Github (the best open source project hosting platform in the world, none of them)
⚫ Gitlab (good support for code privacy, so there are more enterprise users)
⚫ Gitee (also known as code cloud, is a domestic open source project hosting platform. Fast access, pure Chinese interface, friendly to use)

Note: The above three open source project hosting platforms can only host project source code managed by Git, so their names all start with Git.

What is Github

Github is the world's largest open source project hosting platform. Because it only supports Git as the only version control tool, it is named GitHub. In Github, you can:
① Follow your favorite open source projects, like and call them
② Contribute to your favorite open source projects (Pull Request)
③ Discuss bugs and raise requirements with the authors of open source projects (Issues)
④ Put Copy a copy of your favorite project and modify it as your own project (Fork)
⑤ Create your own open source project
⑥ etc...

Use of remote warehouses

1. Create a new blank remote warehouse
[Failed to transfer the external link image, the source site may have an anti-leeching mechanism, it is recommended to save the image and upload it directly (img-1aZnj2qC-1648949129728)(./images/github1.png)]

2. Successfully create a blank remote warehouse
[External link image transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the image and upload it directly (img-IWZAwBT3-1648949129728)(./images/github2.png)]

Two access methods for remote warehouses

The remote warehouse on Github has two access methods, HTTPS and SSH. Their differences are:
①HTTPS: Zero configuration; but every time you access the warehouse, you need to repeatedly enter the Github account and password to access successfully
②SSH: Additional configuration is required; but after the configuration is successful, you do not need to repeat it every time you access the warehouse Enter your Github account and password

Note: In actual development, it is recommended to use SSH to access the remote warehouse.

Upload the local warehouse to Github based on HTTPS

[External link picture transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the picture and upload it directly (img-Eau6nxwH-1648949129729)(./images/github3.png)]

本地没有git仓库
# 创建README.md文档,并写入初始内容# test
echo "# test" >> README.md

# 初始化并提交到本地git仓库
git init
git add README.md
git commit -m "first commit"
git branch -M main

本地仓库和GitHub仓库关联并推送
git remote add origin https://github.com/cat-6/test.git
git push -u origin main

本地有git仓库
git remote add origin https://github.com/cat-6/test.git
git branch -M main
git push -u origin main
Upload the local warehouse to Github based on SSH

[External link image transfer failed, the source site may have an anti-leeching mechanism, it is recommended to save the image and upload it directly (img-B7FbFeMN-1648949129731)(./images/github4.png)]

SSH key

The role of SSH key: to realize the encrypted data transmission between the local warehouse and Github without login.
The benefits of SSH key: login-free identity authentication, encrypted data transmission. The SSH key consists of two parts, namely:
①id_rsa (private key file, which can be stored in the client computer)
②id_rsa.pub (public key file, which needs to be configured in Github)

Generate SSH key

①Open Git Bash
②Paste the following command, and replace [email protected] with the email address you filled in when you registered your Github account:

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

③Continuously press Enter 3 times to generate two files id_rsa and id_rsa.pub in the C:\Users\username folder.ssh directory

Configure SSH keys

①Use Notepad to open the id_rsa.pub file and copy the text content inside
②Log in to Github in the browser, click on the avatar -> Settings-> SSH and GPG Keys -> New SSH key
③Paste the content in the id_rsa.pub file Go to the text box corresponding to the Key
④ Fill in any name in the Title text box to identify where the Key comes from

Detect whether Github's SSH key is configured successfully
ssh -T [email protected]

Clone the remote warehouse to the local

git clone 远程仓库地址

git branch

During multi-person collaborative development, in order to prevent mutual interference and improve the experience of collaborative development, it is recommended that each developer develop project functions based on branches

local branch operation

master main branch

When initializing the local Git warehouse, Git has created a branch named master for us by default. Usually we call this master branch the main branch.
In actual work, the role of the master main branch is to save and record the completed function code of the entire project. Therefore, programmers are not allowed to modify the code directly on the master branch, because the risk of doing so is too high, and it is easy to cause the entire project to crash.

feature branch

A function branch refers to a branch specially used to develop new functions. It is temporarily forked from the master main branch. When the new function is developed and tested, it needs to be merged into the master main branch.

view branch list

git branch

The * sign in front of the branch name indicates the current branch.

create new branch

#基于当前分支,创建一个新的分支
git branch 分支名

switch branch

git checkout 分支名

Quick creation and switching of branches

# -b 表示创建一个新分支
git checkout -b 分支名

merge branch

After the code development and testing of the function branch is completed, the following command can be used to merge the completed code into the master main branch

git checkout master
git merge login

Points to note when merging branches: Suppose you want to merge the code of the C branch into the A branch, you must first switch to the A branch, and then run the git merge command to merge the C branch!

delete branch

After merging the code of the function branch into the master main branch, you can use the following command to delete the corresponding function branch:

git branch -d 分支名

Merging branches when encountering conflicts

If different changes are made to the same file in two different branches, Git cannot merge them cleanly. At this point, we need to open these conflicting files and manually resolve the conflicts.

remote branch operation

Push the local branch to the remote repository

If it is the first time to push the local branch to the remote warehouse, you need to run the following command

# -u 表示把本地分支和远程分支进行关联,只在第一次推送时需要带-u参数
git push -u 远程仓库的别名 本地分支的名称:远程分支的名称

#如果远程分支的名称和本地分支的名称,可以简化
git push -u 远程仓库的别名 分支的名称

Note: The -u parameter is required to push the branch for the first time, and then you can directly use git push to push the code to the remote branch.

View a list of all branches in the remote repository

git remote show 远程仓库名称

track branch

Tracking branch refers to: from the remote warehouse, download the remote branch to the local warehouse

# 从远程仓库中,把对应的远程分支下载到本地仓库,保持本地分支和远程分支名称相同
git checkout 远程分支名称

# 从远程仓库中,把对应的远程分支下载到本地仓库,并把下载的本地分支进行重命名
git checkout -b 本地分支名称 远程仓库名称/远程分支名称

Pull the latest code from the remote branch

git pull

delete remote branch

git push 远程仓库名称 --delete 远程分支名称
本地分支和远程分支进行关联,只在第一次推送时需要带-u参数
git push -u 远程仓库的别名 本地分支的名称:远程分支的名称

#如果远程分支的名称和本地分支的名称,可以简化
git push -u 远程仓库的别名 分支的名称

Note: The -u parameter is required to push the branch for the first time, and then you can directly use git push to push the code to the remote branch.

View a list of all branches in the remote repository

git remote show 远程仓库名称

track branch

Tracking branch refers to: from the remote warehouse, download the remote branch to the local warehouse

# 从远程仓库中,把对应的远程分支下载到本地仓库,保持本地分支和远程分支名称相同
git checkout 远程分支名称

# 从远程仓库中,把对应的远程分支下载到本地仓库,并把下载的本地分支进行重命名
git checkout -b 本地分支名称 远程仓库名称/远程分支名称

Pull the latest code from the remote branch

git pull

delete remote branch

git push 远程仓库名称 --delete 远程分支名称

Reference source: dark horse programmer ppt

Guess you like

Origin blog.csdn.net/m0_68672731/article/details/123932794