Git 上获取部分文件

背景

最近在开发的时候,遇到这么一种情况,公司的设计同事将 UI 设计稿放到了 git 上,但是这个 git 库已经 5+ G了。我为了看某一个版本的 UI 设计稿,要把所有的设计稿都拽下来,之前自己的本本硬盘比较足,还是不在乎的,最近换了个 256 的Mini,我卡,不行,不能拽一些没用的下来,so … 我需要一种技能 —— git pull 的时候,每次只拉去 Git 仓库中的某个文件夹。

一言蔽之

从远程 Git 仓库获取某个目录下的内容。

操作

创建本地Git仓库目录

1
2
3
4
5
6
7
$mkdir myGit_folder
$cd myGit_folder
#/myGit_folder 目录下
$git init
Initialized empty Git repository in /your computer path/myGit_folder/.git/
$ls -a
. .. .git

如上所示,如果在你当前目录下看到了隐藏 .git 目录就证明OK了。

添加远程 Git 仓库地址

1
2
3
4
5
6
7
8
9
10
11
12
13
14
$git remote add -f origin < your git url,like: http://youaresogreat:3000/lawyer/ui.git >

##这个时候在.git目录下的config文件是这个样子
[core]
repositoryformatversion = 0
filemode = true
bare = false
logallrefupdates = true
ignorecase = true
precomposeunicode = true
sparseCheckout = true
[remote "origin"]
url = http://youaresogreat:3000/lawyer/ui.git
fetch = +refs/heads/*:refs/remotes/origin/*

如果 url = http://youaresogreat:3000/lawyer/ui.git 这一行添加到了 .git/config 文件中,就证明OK了。

开启 Git 仓库 Sparse Checkout 模式

1
$git config core.sparsecheckout true

命令执行前:

1
2
3
4
5
6
7
8
9
10
11
#.git/config
[core]
repositoryformatversion = 0
filemode = true
bare = false
logallrefupdates = true
ignorecase = true
precomposeunicode = true
[remote "origin"]
url = http://youaresogreat:3000/lawyer/ui.git
fetch = +refs/heads/*:refs/remotes/origin/*

命令执行后:

1
2
3
4
5
6
7
8
9
10
11
12
#.git/config
[core]
repositoryformatversion = 0
filemode = true
bare = false
logallrefupdates = true
ignorecase = true
precomposeunicode = true
sparseCheckout = true
[remote "origin"]
url = http://youaresogreat:3000/lawyer/ui.git
fetch = +refs/heads/*:refs/remotes/origin/*

如果 sparseCheckout = true 这一行添加到了 .git/config目录下,就说明OK了。

进入到 .git/info/ 配置要获取的文件夹路径

1
2
3
4
5
$cd .git/info
$ vim sparse-checkout
/ui/HTML/2.4.0
:wq
$cd ...

这里是在 sparse-checkout 文件中设置你要获取的文件夹目录 - /ui/HTML/2.4.0

拉取远程目录内容

1
git pull origin master

快速操作步骤:

这是对上面罗里吧嗦的步骤的总汇

1
2
3
4
5
6
7
8
9
10
11
12
$md myGit
$cd myGit
$(myGit/) git init
$(myGit/) git remote add -f origin (your git url)
$(myGit/) git config core.sparsecheckout true
$(myGit/) cd .git/info
$(myGit/.git/info) vim sparse-checkout
/one/two/three/mywantFileDir/
:wq
$(myGit/.git/info) cd ...
$(myGit/) git pull origin master
...

后记:本质就是开启git的 sparse checkout 模式,在 .git/config/sparse-checkout 文件中配置要拉取的文件夹路径。

思考:

通过写一个脚本让操作更加简单 … …

-------------本文结束谢谢欣赏-------------
Alice wechat