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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
|
#!/bin/bash
# GitLab 访问 Token(需要 API 访问权限)
GITLAB_TOKEN="your_private_token"
# GitLab 域名(例如 gitlab.com 或你的私有 GitLab 服务器)
GITLAB_URL="https://gitlab.com"
# 目标群组路径(如 "my_group" 或 "my_group/subgroup")
GROUP_PATH="your_group/subgroup"
# 指定存放代码的目录(可修改)
TARGET_DIR="/path/to/store/projects"
# GitLab 账号(可选,如果需要身份验证)
GITLAB_USERNAME="your_username"
GITLAB_PASSWORD="$GITLAB_TOKEN" # 或者使用 Token 替代密码
# URL 编码函数
url_encode() {
local input="$1"
echo -n "$input" | jq -sRr @uri
}
# 递归克隆群组及其子群组的项目
function clone_group_projects() {
local group_path=$1
local encoded_group_path
encoded_group_path=$(url_encode "$group_path") # 进行 URL 编码
local local_path="$TARGET_DIR/$group_path" # 直接保留完整群组路径
# 创建本地目录,确保层级结构
mkdir -p "$local_path"
cd "$local_path" || exit
echo "当前目录: $(pwd)"
# 获取当前群组的所有项目
PROJECTS=$(curl -s --header "PRIVATE-TOKEN: $GITLAB_TOKEN" \
"$GITLAB_URL/api/v4/groups/$encoded_group_path/projects?per_page=100" | jq -r '.[] | "\(.path) \(.http_url_to_repo)"')
while read -r repo_name repo_url; do
if [ -n "$repo_name" ] && [ -n "$repo_url" ]; then
if [ ! -d "$repo_name" ]; then
echo "克隆项目: $repo_name"
# 如果返回的仓库地址为http协议,则替换为https协议
if [[ "$GITLAB_URL" =~ ^https:// ]]; then
repo_url="${repo_url/http:\/\//https:\/\/}"
fi
# 处理 Git 认证(如果仓库是私有的,需要输入用户名/Token)
repo_url_with_auth="${repo_url/https:\/\//https://$GITLAB_USERNAME:$GITLAB_PASSWORD@}"
git clone "$repo_url_with_auth" "$repo_name"
else
echo "项目已存在,跳过: $repo_name"
fi
fi
done <<< "$PROJECTS"
# 获取当前群组的所有子群组
SUBGROUPS=$(curl -s --header "PRIVATE-TOKEN: $GITLAB_TOKEN" \
"$GITLAB_URL/api/v4/groups/$encoded_group_path/subgroups?per_page=100" | jq -r '.[].full_path')
for subgroup_path in $SUBGROUPS; do
echo "进入子群组: $subgroup_path"
clone_group_projects "$subgroup_path"
done
cd "$TARGET_DIR" || exit
}
# 开始克隆
clone_group_projects "$GROUP_PATH"
echo "所有项目(包括子群组)已按层级结构克隆完成!"
|