-
Notifications
You must be signed in to change notification settings - Fork 1
/
gitcd.plugin.zsh
55 lines (46 loc) · 1.5 KB
/
gitcd.plugin.zsh
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
gitcd() {
basedir="$HOME/Code"
# 如果存在全局的 GITCD_HOME,就用它
[[ -n $GITCD_HOME ]] && {
basedir=$GITCD_HOME
}
# 用户传入的参数
url=$1
# 忘记输入参数,就跳出
[[ $url == "" ]] && {
# 显示红色加粗
print -P "%B%F{red}[gitcd] Please input your repo url."
return
}
# 通过 git url 计算出路径来
dir=$(_giturl2dir $url)
target=$basedir/$dir
# 如果文件夹已经存在,那直接 cd 过去就好了
[[ -d $target ]] && {
# 显示绿色加粗
print -P "%B[gitcd] $target %F{green}already exists."
cd $target
return
}
git clone $url $target && cd $target
# 显示绿色加粗
print -P "%B%F{green}[gitcd] Done. Have a great day!"
}
_giturl2dir() {
# 规则参考了 https://github.com/repo-utils/giturl/blob/master/lib/giturl.js
url=$1
# 删掉 @ 和之前的内容,即 `git@`` || `https://jpillora@` => ""
url=${url#*@} # 删除左端匹配到的内容,最小匹配
# 删掉协议头,即 `git://` || `git+https://` => ""
url=${url#*://}
# 删掉末尾的 .git,即 .git => ""
url=${url%.git*}
# 替换掉第一个冒号,即 github.com:foo/bar => github.com/foo/bar
url=${url/:/\/}
[[ -n $GITCD_USEHOST ]] && [[ "${GITCD_USEHOST:l}" == "false" ]] && {
# echo $url
url=$(echo $url | cut -d "/" -f 2-)
}
# 用 echo 返回给调用方,而不是用 return
echo $url
}