BASH script to clone all git repository in a Group on GitLab, or Organization on GitHub.

Introduction

Starting at a new employer always mean checking out various git repositories.

As the amount of repositories a company has grows, the time needed to clone all of those repositories also grows.

This script automates this task.

In order for this script to work, a personal access token
is needed.

To avoid unexpected behaviour, use Group's ID, rather than its key/name. Informations about Groups can be found in the API at
https://gitlab.example.com/api/v4/groups.

Usage

Call bash gitlab-clone-projects.sh <gitlab-domain> <group-name> <gitlab-token>

For full usage details gitlab-clone-projects --help is available:

Usage: gitlab-clone-projects.sh [-dh] <gitlab-domain> <group-id> <gitlab-token>

Where:

  • <gitlab-domain> is the domain where gitlab lives (for instance: 'gitlab.com')
  • <group-id> is the ID of the group who's repos should be cloned
  • <gitlab-token> is the API access token to make REST API calls with

Options:

  • -d|--dry-run Only list the repositories, without actually cloning them
  • -h|--help Print this help dialogue and exit
  • -u|--user The given ID is a user, not a group

The repositories will be cloned into a sub-directory under the path from Where
this script has been called. The repository will be cloned into ./{group-id}/{repo-name}

The git executable can be overridden by setting the GIT environmental variable
before calling this script:
GIT=/usr/local/git-plus gitlab-clone-projects.sh <gitlab-domain> <group-id> <gitlab-token>

github-clone-projects.bash

#!/usr/bin/env bash

# ==============================================================================
# Copyright (C) 2021 Potherca
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at https://mozilla.org/MPL/2.0/.
# ==============================================================================
# There are a few standards this code tries to adhere to, these are listed below.
#
# - Code follows the BASH style-guide described at:
#   http://guides.dealerdirect.io/code-styling/bash/
#
# - Variables are named using an adaption of Systems Hungarian explained at:
#   http://blog.pother.ca/VariableNamingConvention
#
# ==============================================================================

set -o errexit  # Exit script when a command exits with non-zero status.
set -o errtrace # Exit on error inside any functions or sub-shells.
set -o nounset  # Exit script on use of an undefined variable.
set -o pipefail # Return exit status of the last command in the pipe that exited with a non-zero exit code

# ==============================================================================
#                       Git Clone All Projects in GitHub Organisation
# ------------------------------------------------------------------------------
## Usage: $0 [-dh] <github-domain> <group-id> <github-token>
##
## Where:
##       - <github-domain> is the domain where github lives (for instance: 'github.com')
##       - <group-id> is the ID of the group who's repos should be cloned
##       - <github-token> is the API access token to make REST API calls with
##
## Options:
##   -d|--dry-run   Only list the repositories, without actually cloning them
##   -h|--help      Print this help dialogue and exit
##   -u|--user      The given ID is a user, not a organisation
##
## The repositories will be cloned into a sub-directory under the path from Where
## this script has been called. The repository will be cloned into ./${group-id}/${repo-name}
##
## The git executable can be overridden by setting the GIT environmental variable
## before calling this script:
##
##        GIT=/usr/local/git-plus $0 <github-domain> <group-id> <github-token>
# ==============================================================================

: readonly "${GIT:=git}"

usage() {
    local sScript sUsage

    readonly sScript="$(basename "$0")"
    readonly sUsage="$(grep '^##' <"$0" | cut -c4-)"

    echo -e "${sUsage//\$0/${sScript}}"
}

github-clone-projects() {

    local -a aParameters aRepos
    local g_sGithubDomain g_sGithubToken g_sId
    local bIsUser bDryRun
    local sDirectory sRepo sRepos

    call-api() {
      local -r sSubject="${1?One parameter required: <api-subject>}"
      curl --silent -u "username:${g_sGithubToken}" "https://api.${g_sGithubDomain}/${sSubject}?per_page=100"
    }

    fetch-projects() {
      local iId sSubject

      readonly sSubject="${1?Two parameters required: <subject> <id>}"
      readonly iId="${2?Two parameters required: <subject> <id>}"

      call-api "${sSubject}/${iId}/repos" \
        | grep -E -o '"ssh_url"\s*:\s*"[^"]+"' \
        | cut -d '"' -f4
    }

    fetch-group-projects() {
      local -r iId="${1?One parameters required: <id>}"
      fetch-projects 'orgs' "${iId}"
    }

    fetch-user-projects() {
      local -r iId="${1?One parameters required: <id>}"
      fetch-projects 'users' "${iId}"
    }

    bIsUser=false
    bDryRun=false
    aParameters=()

    for arg in "$@";do
      case $arg in
        -h|--help )
          usage
          exit
        ;;

        -d|--dry-run )
          readonly bDryRun=true
          shift
        ;;

        -u|--user )
          readonly bIsUser=true
          shift
        ;;

        * )
          aParameters+=( "$1" )
          shift
        ;;
      esac
    done
    readonly aParameters

    readonly g_sGithubDomain="${aParameters[0]?Three parameters required: <github-domain> <group-id> <github-token>}"
    readonly g_sId="${aParameters[1]?Three parameters required: <github-domain> <group-id> <github-token>}"
    readonly g_sGithubToken="${aParameters[2]?Three parameters required: <github-domain> <group-id> <github-token>}"

    if [[ "${bIsUser}" = 'true' ]];then
      readonly sRepos=$(fetch-user-projects "${g_sId}")
    else
      readonly sRepos=$(fetch-group-projects "${g_sId}")
    fi

    aRepos=()
    for sRepo in ${sRepos[*]}; do
      aRepos+=("${sRepo}")
    done

    echo ' =====> Found ' ${#aRepos[@]} ' repositories'

    for sRepo in "${aRepos[@]}"; do
      # Grab repo name
      sDirectory="$(echo "${sRepo}" | grep -o -E ':(.*)\.')"
      # Lowercase the name
      sDirectory="$(echo "${sDirectory}" | tr '[:upper:]' '[:lower:]')"
      # Prepend the current location
      sDirectory="$(realpath --canonicalize-missing --relative-to=./ "${sDirectory:1:-1}")"

      if [[ -d "${sDirectory}" ]];then
        echo " -----> Skipping '${sRepo}', directory '${sDirectory}' already exists"
      else
        echo " -----> Cloning '${sRepo}' into directory '${sDirectory}'"

        if [[ "${bDryRun}" != 'true' ]];then
          mkdir -p "${sDirectory}"
          "${GIT}" clone --recursive "${sRepo}" "${sDirectory}" \
            || {
              rm -rf "${sDirectory}"
              echo -e "\n ! ERROR !\n           Could not clone ${sRepo}"
          }
          echo ""
        fi
      fi
    done
}

if [[ "${BASH_SOURCE[0]}" != "$0" ]]; then
  export -f github-clone-projects
else
  github-clone-projects "${@}"
  exit $?
fi

#EOF

gitlab-clone-projects.bash

#!/usr/bin/env bash

# ==============================================================================
# Copyright (C) 2018, 2020 Potherca
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at https://mozilla.org/MPL/2.0/.
# ==============================================================================
# There are a few standards this code tries to adhere to, these are listed below.
#
# - Code follows the BASH style-guide described at:
#   http://guides.dealerdirect.io/code-styling/bash/
#
# - Variables are named using an adaption of Systems Hungarian explained at:
#   http://blog.pother.ca/VariableNamingConvention
#
# ==============================================================================

set -o errexit  # Exit script when a command exits with non-zero status.
set -o errtrace # Exit on error inside any functions or sub-shells.
set -o nounset  # Exit script on use of an undefined variable.
set -o pipefail # Return exit status of the last command in the pipe that exited with a non-zero exit code

# ==============================================================================
#                       Git Clone All Projects in Gitlab Group
# ------------------------------------------------------------------------------
## Usage: $0 [-dh] <gitlab-domain> <group-id> <gitlab-token>
##
## Where:
##       - <gitlab-domain> is the domain where gitlab lives (for instance: 'gitlab.com')
##       - <group-id> is the ID of the group who's repos should be cloned
##       - <gitlab-token> is the API access token to make REST API calls with
##
## Options:
##   -d|--dry-run   Only list the repositories, without actually cloning them
##   -h|--help      Print this help dialogue and exit
##   -u|--user      The given ID is a user, not a group
##
## The repositories will be cloned into a sub-directory under the path from Where
## this script has been called. The repository will be cloned into ./${group-id}/${repo-name}
##
## The git executable can be overridden by setting the GIT environmental variable
## before calling this script:
##
##        GIT=/usr/local/git-plus $0 <gitlab-domain> <group-id> <gitlab-token>
# ==============================================================================

: readonly "${GIT:=git}"

usage() {
    local sScript sUsage

    readonly sScript="$(basename "$0")"
    readonly sUsage="$(grep '^##' <"$0" | cut -c4-)"

    echo -e "${sUsage//\$0/${sScript}}"
}

gitlab-clone-projects() {

    local -a aParameters aRepos
    local g_sGitlabDomain g_sGitlabToken g_sId
    local bIsUser bDryRun
    local sDirectory sRepo

    call-api() {
      local -r sSubject="${1?One parameter required: <api-subject>}"
      curl --silent --header "PRIVATE-TOKEN: ${g_sGitlabToken}" "https://${g_sGitlabDomain}/api/v4/${sSubject}?per_page=100"
    }

    fetch-projects() {
      local iId sSubject

      readonly sSubject="${1?Two parameters required: <subject> <id>}"
      readonly iId="${2?Two parameters required: <subject> <id>}"

      call-api "${sSubject}/${iId}/projects" \
        | grep -E -o '"ssh_url_to_repo":"[^"]+"' \
        | cut -d '"' -f4
    }

    fetch-group-projects() {
      local -r iId="${1?One parameters required: <id>}"
      fetch-projects 'groups' "${iId}"
    }

    fetch-user-projects() {
      local -r iId="${1?One parameters required: <id>}"
      fetch-projects 'users' "${iId}"
    }

    bIsUser=false
    bDryRun=false
    aParameters=()

    for arg in "$@";do
      case $arg in
        -h|--help )
          usage
          exit
        ;;

        -d|--dry-run )
          readonly bDryRun=true
          shift
        ;;

        -u|--user )
          readonly bIsUser=true
          shift
        ;;

        * )
          aParameters+=( "$1" )
          shift
        ;;
      esac
    done
    readonly aParameters

    readonly g_sGitlabDomain="${aParameters[0]?Three parameters required: <gitlab-domain> <group-id> <gitlab-token>}"
    readonly g_sId="${aParameters[1]?Three parameters required: <gitlab-domain> <group-id> <gitlab-token>}"
    readonly g_sGitlabToken="${aParameters[2]?Three parameters required: <gitlab-domain> <group-id> <gitlab-token>}"

    if [[ "${bIsUser}" = 'true' ]];then
      readonly sRepos=$(fetch-user-projects "${g_sId}")
    else
      readonly sRepos=$(fetch-group-projects "${g_sId}")
    fi

    aRepos=()
    for sRepo in ${sRepos[*]}; do
      aRepos+=("${sRepo}")
    done

    echo ' =====> Found ' ${#aRepos[@]} ' repositories'

    for sRepo in "${aRepos[@]}"; do
      # Grab repo name
      sDirectory="$(echo "${sRepo}" | grep -o -E ':(.*)\.')"
      # Lowercase the name
      sDirectory="$(echo "${sDirectory}" | tr '[:upper:]' '[:lower:]')"
      # Prepend the current location
      sDirectory="$(realpath --canonicalize-missing --relative-to=./ "${sDirectory:1:-1}")"

      if [[ -d "${sDirectory}" ]];then
        echo " -----> Skipping '${sRepo}', directory '${sDirectory}' already exists"
      else
        echo " -----> Cloning '${sRepo}' into directory '${sDirectory}'"

        if [[ "${bDryRun}" != 'true' ]];then
          mkdir -p "${sDirectory}"
          "${GIT}" clone --recursive "${sRepo}" "${sDirectory}" \
            || {
              rm -rf "${sDirectory}"
              echo -e "\n ! ERROR !\n           Could not clone ${sRepo}"
          }
          echo ""
        fi
      fi
    done
}

if [[ "${BASH_SOURCE[0]}" != "$0" ]]; then
  export -f gitlab-clone-projects
else
  gitlab-clone-projects "${@}"
  exit $?
fi

#EOF

参考

https://bl.ocks.org/Potherca/9dd4306eb27cad26d27874acd4b31376

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,277评论 6 503
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,689评论 3 393
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 163,624评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,356评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,402评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,292评论 1 301
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,135评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,992评论 0 275
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,429评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,636评论 3 334
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,785评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,492评论 5 345
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,092评论 3 328
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,723评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,858评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,891评论 2 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,713评论 2 354

推荐阅读更多精彩内容