0%

Git

Git笔记

Git结构

  1. 工作目录 work directory
  2. 暂存区 stage
  3. 本地仓库 repository
    • 每台电脑都有一个
  4. 远程仓库 remote
    • 多台电脑共用一个,位于服务器

注意:

  • 文件提交时,必须1->2->3->4逐步提交
  • 文件可以依次检出,也可以直接从remote检出到work directory
  • 内置小的linux系统,支持linux命令

基本命令

config

1
2
3
git config --global -l
git config --global user.name "My name"
git config --global unset user.name

init, add

位于任意文件夹,创建本地仓库.git

外面即为work directory, 所创建文件默认处于未追踪 untracked 状态,需要add,进入暂存区stage

1
2
3
4
5
6
7
8
9
10
11
12
13
git init

git status

git add hello.txt

git add . #一次性添加目录下所有文件

git commit -m "message" #提交至本地仓库repository

git log #查看提交记录
git log --oneline
git log --oneline --graph --all

每次文件修改后,都需要再次add和comit

1
2
3
4
5
6
7
git add hello.txt
git commit

git commit -a -m "Modify" #只适用于修改

git show
git show 5121

.gitignore

直接写入文件名

支持正则匹配

1
2
3
4
5
6
7
8
9
10
# 匹配所有txt文件
*.txt
# 除了这个txt
!666.txt
# 排除某个文件夹
test/
# 目录中所有以txt结尾的文件,但不包括子目录
xxx/*.txt
# 目录中所有以txt结尾的文件,包括子目录
xxx/**/*.txt

rollback

将work directory恢复到指定的提交状态

1
2
3
git reset --hard commitID

git reflog #显示所有commitID

branch

不同分支下文件内容相互隔离

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
git branch

git branch test
git branch yyds

git log --all --graph --online

git branch -d yyds #删除

git chechout test #切换/签出
git commit -a -m "Modify on test"


#合并分支
git chechout master
git merge test
git diff
#解决冲突后再次提交
git commit -a -m "Merge on conflict"
1
2
3
4
5
# 首先切换到staging
git checkout staging

# 根据staging分支创建新分支
git branch ivn/newModification

注意:

  • merge并不改变另一个分支,只是把另一分支的修改合到当前分支上(提交的合并,非分支的合并)

rebase

变基

1
2
git chechout test
git rebase master

cherry-pick

优选,灵活选取其他branch的某些更新

1
git cherry-pick commitID	#单独合并一个提交

远程仓库GitHub

本地推远程

1
2
3
git remote add origin https://github.com/.../...
git push origin master
git push 远程仓库名称 本地分支名称[:远程分支名称]

远程克隆本地

1
git clone https://github.com/.../...

解决不同步

1
2
3
4
5
6
7
8
9
10
git fetch origin
git log --all --graph --oneline
git merge origin/master

#pull = fetch + merge
git pull origin

#解决冲突后,再次提交
git commit -a -m "Modify by B finally"
git push origin

实战

远程本地均多分支

1
2
3
4
5
6
7
8
9
#根据远程拉本地: 先建新分支,
git branch ivn/newBranch
git pull origin staging

#检查本地分支和远程分支是否同步
git status

#强制本地和远程一样
git reset --hard origin/staging

原理:

  • github看似是同步file,其实是基于node,同步node
  • 因此需要确保要同步的branch不能有divergence,即dev branch必须修改于staging branch的最新状态,而不是之前的旧状态
  • 为此,需要在每次commit前先pull,保证同步