gitlab:使用脚本批量下载项目,实现全项目检索

目的

当需要知道gitlab中所有项目是否存在某段代码时,gitlab免费版只提供了当个项目内的检索,当项目过多时一个个查太过繁琐。下面通过 GitLab API 将指定 Group 下的所有项目克隆到本地。此脚本会自动获取项目列表并逐一克隆它们,再在本地进行检索的方案。

准备工作

当前环境支持一下命令

  • curl:用于调用 GitLab API。

  • jq:解析 JSON 数据。
    *

    bash 复制代码
    # MAC 安装
    brew install jq
  • git:用于克隆项目。

gitlab上生成一个token令牌

  • read_api和read_repository权限

下载项目

sh脚本,替换参数

bash 复制代码
# 创建脚本文件
vim cloneGitlab.sh
bash 复制代码
#!/bin/bash

# 配置部分
GITLAB_URL="http://gitlab.example.com" # 替换为你的 GitLab 实例地址
GROUP_ID="12345"                        # 替换为你的 Group ID
PRIVATE_TOKEN="gitlab_token"      # 替换为你的 GitLab 私有访问令牌
CLONE_DIR="./gitlab-projects"           # 本地存储路径

# 创建存储目录
mkdir -p "$CLONE_DIR"

# 获取项目列表,100个
echo "Fetching project list from GitLab..."
PROJECTS=$(curl --header "PRIVATE-TOKEN: $PRIVATE_TOKEN" \
  --silent \
  "$GITLAB_URL/api/v4/groups/$GROUP_ID/projects?per_page=100" | jq -r '.[].http_url_to_repo')

# 检查是否有项目返回
if [[ -z "$PROJECTS" ]]; then
  echo "No projects found or API request failed. Please check your configuration."
  exit 1
fi

# 克隆项目
echo "Cloning projects..."
cd "$CLONE_DIR" || exit

for PROJECT in $PROJECTS; do
  PROJECT_NAME=$(basename "$PROJECT" .git)
  
  if [[ -d "$PROJECT_NAME" ]]; then
    echo "Project $PROJECT_NAME already exists. Skipping..."
  else
    echo "Cloning $PROJECT..."
    git clone "$PROJECT"
  fi
done

echo "All projects cloned to $CLONE_DIR."
bash 复制代码
# 执行脚本
sh cloneGitlab.sh

检索内容

bash 复制代码
find . -name ".git" -execdir git --no-pager grep -n "your_key" \;
  • 显示检索的项目名称
bash 复制代码
find . -name ".git" -execdir sh -c '
    basename `pwd` && git --no-pager grep -n "bike_riding_order" 
' \;
相关推荐
一念一花一世界1 天前
Arbess从初级到进阶(9) - 使用Arbess+GitLab实现C++项目自动化部署
c++·ci/cd·gitlab·arbess
X***48961 天前
GitLab
gitlab
一世一生命1 天前
GitLab Package依赖管理:从 Dependabot 到 Renovate 的迁移实践和两者对比
gitlab
t***L2661 天前
GitLab API使用实例
运维·gitlab
x***B4112 天前
GitLab Runner配置教程
gitlab
9***Y482 天前
GitLab CI/CD配置教程
ci/cd·gitlab
y***54882 天前
GitLab CI缓存配置
缓存·ci/cd·gitlab
p***c9492 天前
GitLab CI/CD变量
git·ci/cd·gitlab
O***p6042 天前
GitLab CI/CD自动化部署实践
ci/cd·自动化·gitlab
知兀2 天前
私有化部署的gitlab的push failed问题,使用http远程连接(使用token或用户、密码)
gitlab