program tip

GitHub에서 한 번에 모든 저장소를 복제하는 방법은 무엇입니까?

radiobox 2020. 10. 9. 10:41
반응형

GitHub에서 한 번에 모든 저장소를 복제하는 방법은 무엇입니까?


회사 GitHub 계정이 있고 자동화 목적으로 생성 될 수있는 새로운 항목을 고려하여 내부의 모든 저장소를 백업하고 싶습니다. 나는 다음과 같은 것을 바라고 있었다.

git clone git@github.com:company/*.git 

또는 유사하게 작동하지만 와일드 카드가 마음에 들지 않는 것 같습니다.

Git에 적절한 권한이 있다고 가정하고 모든 것을 복제 한 다음 가져 오는 방법이 있습니까?


그렇게하는 것이 가능하지 않다고 생각합니다. 가장 좋은 방법은 API를 사용하여 조직의 저장소 목록을 찾고 반복하는 것입니다.

이 시도:

  • 계정 설정-> 애플리케이션으로 이동하여 API 토큰을 만듭니다.
  • 전화 걸기 : http://${GITHUB_BASE_URL}/api/v3/orgs/${ORG_NAME}/repos?access_token=${ACCESS_TOKEN}
  • 응답은 객체의 JSON 배열입니다. 각 개체에는 해당 조직 아래의 저장소 중 하나에 대한 정보가 포함됩니다. 귀하의 경우에는 해당 ssh_url부동산을 구체적으로 찾고 계실 것입니다 .
  • 그런 다음 git clone각각 ssh_url의.

약간의 추가 작업이 필요하지만 GitHub에 적절한 인증이 필요합니다.


윈도우 및 모든 UNIX / LINUX를 사용하는 시스템, 힘내 배쉬 또는 다른 터미널을 대체 YOURUSERNAME사용자 이름과 사용에 의해 :

CNTX={users|orgs}; NAME={username|orgname}; PAGE=1
curl "https://api.github.com/$CNTX/$NAME/repos?page=$PAGE&per_page=100" |
  grep -e 'git_url*' |
  cut -d \" -f 4 |
  xargs -L1 git clone

모든 저장소를 다운로드하려면 CNTX=users및을 설정 NAME=yourusername하십시오. 조직의 모든 저장소를 다운로드하려면 CNTX = orgs 및 NAME = yourorgname을 설정하십시오.

최대 페이지 크기는 100이므로 모든 저장소를 가져 오려면 올바른 페이지 번호로 여러 번 호출해야합니다 ( PAGE다운로드하려는 원하는 페이지 번호로 설정 ).

다음은 위의 작업을 수행하는 쉘 스크립트입니다. https://gist.github.com/erdincay/4f1d2e092c50e78ae1ffa39d13fa404e


조직 저장소

조직의 모든 저장소를 복제하려면 다음 셸 한 줄을 시도하십시오.

GHORG=company; curl "https://api.github.com/orgs/$GHORG/repos?per_page=1000" | grep -o 'git@[^"]*' | xargs -L1 git clone

사용자 저장소

Git 저장소 URL을 사용하여 모두 복제 :

GHUSER=CHANGEME; curl "https://api.github.com/users/$GHUSER/repos?per_page=1000" | grep -o 'git@[^"]*' | xargs -L1 git clone

복제 URL을 사용하여 모두 복제 :

GHUSER=CHANGEME; curl "https://api.github.com/users/$GHUSER/repos?per_page=1000" | grep -w clone_url | grep -o '[^"]\+://.\+.git' | xargs -L1 git clone

다음은 사용자의 시작 파일에 추가 할 수있는 유용한 셸 기능입니다 ( curl+ 사용 jq).

# Usage: gh-clone-user (user)
gh-clone-user() {
  curl -sL "https://api.github.com/users/$1/repos?per_page=1000" | jq -r '.[]|.clone_url' | xargs -L1 git clone
}

개인 저장소

비공개 저장소를 복제해야하는 경우 다음 과 같이 헤더에 인증 토큰을 추가 할 수 있습니다 .

-H 'Authorization: token <token>'

또는 매개 변수 ( ?access_token=TOKEN) 에 전달합니다. 예를 들면 다음과 같습니다.

curl -s "https://api.github.com/users/$GHUSER/repos?access_token=$GITHUB_API_TOKEN&per_page=1000" | grep -w clone_url | grep -o '[^"]\+://.\+.git' | xargs -L1 git clone

메모:

  • 개인 저장소 만 가져 오려면 type=private쿼리 문자열에 추가 하십시오.
  • 또 다른 방법은 hubAPI 키를 구성한 후 사용하는 것입니다.

또한보십시오:


힌트 :
-속도를 높이려면 ( = 4 프로세스)에 -P대한 매개 변수를 지정하여 병렬 프로세스 수를 설정하십시오 . xargs-P4
-GitHub 제한을 높여야하는 경우 API 키를 지정하여 인증을 시도하세요.
- --recursive등록 된 서브 모듈에 재귀를 추가 하고 그 안에 중첩 된 서브 모듈을 업데이트합니다.


이 요점 은 명령 줄에서 한 줄로 작업을 수행합니다.

curl -s https://api.github.com/orgs/[your_org]/repos?per_page=200 | ruby -rubygems -e 'require "json"; JSON.load(STDIN.read).each { |repo| %x[git clone #{repo["ssh_url"]} ]}'

[your_org]조직의 이름으로 바꿉니다 . 그리고 per_page필요한 경우 설정하십시오 .

최신 정보:

ATutorMe가 언급했듯이 GitHub 문서에 따르면 최대 페이지 크기는 100 입니다.

리포지토리가 100 개 이상인 경우 pageURL에 매개 변수를 추가해야 하며 각 페이지에 대해 명령을 실행할 수 있습니다.

curl -s "https://api.github.com/orgs/[your_org]/repos?page=2&per_page=100" | ruby -rubygems -e 'require "json"; JSON.load(STDIN.read).each { |repo| %x[git clone #{repo["ssh_url"]} ]}'

참고 : 기본 per_page매개 변수는 30입니다.


계정 설정-> 애플리케이션으로 이동하여 API 키를 생성 한
다음 아래 스크립트에 API 키, github 인스턴스 URL 및 조직 이름을 삽입합니다.

#!/bin/bash

# Substitute variables here
ORG_NAME="<ORG NAME>"
ACCESS_TOKEN="<API KEY>"
GITHUB_INSTANCE="<GITHUB INSTANCE>

URL="https://${GITHUB_INSTANCE}/api/v3/orgs/${ORG_NAME}/repos?access_token=${ACCESS_TOKEN}"

curl ${URL} | ruby -rjson -e 'JSON.load(STDIN.read).each {|repo| %x[git clone #{repo["ssh_url"]} ]}'

파일, 파일에 저장 chmod u+x한 다음 실행하십시오.

루비 코드에 대해 Arnaud 에게 감사드립니다 .


그래서 내 대답도 추가하겠습니다. :) (간단하다는 것을 알았습니다)

가져 오기 목록 ( "magento"회사를 사용했습니다) :

curl -si https://api.github.com/users/magento/repos | grep ssh_url | cut -d '"' -f4

HTTP 액세스를 사용 하려면 clone_url대신 사용하십시오 ssh_url.

자, 모두 복제합시다! :)

curl -si https://api.github.com/users/magento/repos | \
    grep ssh_url | cut -d '"' -f4 | xargs -i git clone {}

개인 저장소를 가져 오려는 경우-GET 매개 변수를 추가하기 만하면됩니다. ?access_token=YOURTOKEN


@seancdavis가 제공 한 요점 에서 매우 도움이되는 댓글을 찾았습니다. 특히 원본 포스터와 마찬가지로 빠른 액세스를 위해 모든 리포지토리를 동기화하고 싶었지만 대부분은 비공개였습니다.

curl -u [[USERNAME]] -s https://api.github.com/orgs/[[ORGANIZATION]]/repos?per_page=200 |
  ruby -rubygems -e 'require "json"; JSON.load(STDIN.read).each { |repo| %x[git clone #{repo["ssh_url"]} ]}'

[[USERNAME]]을 github 사용자 이름으로, [[ORGANIZATION]]을 Github 조직으로 바꿉니다. 출력 (JSON 리포지토리 메타 데이터)은 간단한 루비 스크립트로 전달됩니다.

# bring in the Ruby json library
require "json"

# read from STDIN, parse into ruby Hash and iterate over each repo
JSON.load(STDIN.read).each do |repo|
  # run a system command (re: "%x") of the style "git clone <ssh_url>"
  %x[git clone #{repo["ssh_url"]} ]
end

Python3 및 Github APIv3로 스크립트를 작성했습니다.

https://github.com/muhasturk/gitim

그냥 달려

./gitim

curl -s https://api.github.com/orgs/[GITHUBORG_NAME]/repos | grep clone_url | awk -F '":' '{ print $2 }' | sed 's/\"//g' | sed 's/,//' | while read line; do git clone "$line"; done

위의 몇 가지 명령과 도구를 시도했지만 너무 번거 롭다고 판단했기 때문에이를 수행하기 위해라는 또 다른 명령 줄 도구를 작성했습니다 github-dl.

사용하려면 (nodejs가 설치되어 있다고 가정)

npx github-dl -d /tmp/test wires

그러면 CLI에서 제공하는 권한 부여 세부 정보 (사용자 / 패스)를 사용하여 모든 저장소의 목록을 가져 wires오고 test디렉터리에 정보를 씁니다 .

자세하게는

  1. 인증 요청 (2FA 지원)
  2. Github API를 통해 사용자 / 조직의 저장소 목록을 가져옵니다.
  3. 이를 위해 페이지 매김을 수행하므로 100 개 이상의 저장소가 지원됩니다.

실제로 저장소를 복제하지는 않지만 대신 복제를 수행하기 위해 .txt전달할 수 있는 파일을 작성합니다 xargs. 예 :

cd /tmp/test
cat wires-repo-urls.txt | xargs -n2 git clone

# or to pull
cat /tmp/test/wires-repo-urls.txt | xargs -n2 git pull

아마도 이것은 당신에게 유용 할 것입니다. JS 몇 줄이면 필요에 맞게 쉽게 조정할 수 있습니다.


이 python one-liner는 필요한 작업을 수행합니다. 그것:

  • github에서 사용 가능한 저장소를 확인합니다.
  • 각각에 대해 시스템 호출을 만듭니다. git clone

    python -c "import json, urllib, os; [os.system('git clone ' + r['ssh_url']) for r in json.load(urllib.urlopen('https://api.github.com/orgs/<<ORG_NAME>>/repos?per_page=200'))]"
    

이를 수행하는 데 매우 유용한 npm 모듈 도 있습니다 . 복제 할 수있을뿐만 아니라 끌어 올 수도 있습니다 (이미 가지고있는 데이터를 업데이트하기 위해).

다음과 같이 구성을 만듭니다.

[{
   "username": "BoyCook",
   "dir": "/Users/boycook/code/boycook",
   "protocol": "ssh"
}]

그리고 gitall clone예를 들어. 또는gitall pull


누군가 Windows 솔루션을 찾는 경우, 여기 PowerShell에서 트릭을 수행하는 작은 기능이 있습니다 (프록시를 사용하거나 사용하지 않고 모두 작업하는 데 필요한 사실이 아니라면 oneliner / alias 일 수 있음).

function Unj-GitCloneAllBy($User, $Proxy = $null) {
    (curl -Proxy $Proxy "https://api.github.com/users/$User/repos?page=1&per_page=100").Content 
      | ConvertFrom-Json 
      | %{ $_.clone_url } 
      # workaround git printing to stderr by @wekempf aka William Kempf
      # https://github.com/dahlbyk/posh-git/issues/109#issuecomment-21638678
      | %{ & git clone $_ 2>&1 } 
      | % { $_.ToString() }
}

따라서 실제로 FOO일치 하는 조직의 모든 저장소를 복제 BAR하려면 아래의 한 줄을 사용할 수 있습니다. 여기에는 jq 및 공통 CLI 유틸리티 가 필요합니다.

curl 'https://api.github.com/orgs/FOO/repos?access_token=SECRET' |
  jq '.[] |
  .ssh_url' |
  awk '/BAR/ {print "git clone " $0 " & "}' |
  sh

이를 위해 pip 모듈을 만들었습니다. Windows, Linux 및 OSX에서 작동합니다.

https://github.com/zeusofjuice/starclone

다음을 사용하여 저장소를 복제 할 수 있습니다.

starclone <user> 

도움말 파일이나 README에서 지정할 수있는 몇 가지 플래그가 있습니다.


간단한 솔루션 :

NUM_REPOS=1000
DW_FOLDER="Github_${NUM_REPOS}_repos"
mkdir ${DW_FOLDER}
cd ${DW_FOLDER}
for REPO in $(curl https://api.github.com/users/${GITHUB_USER}/repos?per_page=${NUM_REPOS} | awk '/ssh_url/{print $2}' | sed 's/^"//g' | sed 's/",$//g') ; do git clone ${REPO} ; done

을 사용하여 리포지토리 목록을 curl가져온 다음 bash 루프로 해당 목록을 반복 할 수 있습니다 .

GIT_REPOS=`curl -s curl https://${GITHUB_BASE_URL}/api/v3/orgs/${ORG_NAME}/repos?access_token=${ACCESS_TOKEN} | grep ssh_url | awk -F': ' '{print $2}' | sed -e 's/",//g' | sed -e 's/"//g'`
for REPO in $GIT_REPOS; do
  git clone $REPO
done

오픈 소스 도구를 사용하여 여러 github 저장소를 복제 할 수 있습니다. https://github.com/artiomn/git_cloner

예:

git_cloner --type github --owner octocat --login user --password user https://my_bitbucket

.NET에서 JSON API를 사용합니다 api.github.com. github 문서에서 코드 예제를 볼 수 있습니다 : https://developer.github.com/v3/

또는 거기 :

https://github.com/artiomn/git_cloner/blob/master/src/git_cloner/github.py


액세스 키와 Python 3 및 요청 모듈이 설치되어있는 개인 저장소 만 복제하려면 :

ORG=company; ACCESS_KEY=0000000000000000000000000000000000000000; for i in $(python -c "import requests; print(' '.join([x['ssh_url'] for x in list(filter(lambda x: x['private'] ,requests.get('https://api.github.com/orgs/$ORG/repos?per_page=1000&access_token=$ACCESS_KEY').json()))]))"); do git clone $i; done;

Link헤더 를 통한 완전한 페이지 매김을 포함하는 Python3 솔루션입니다 .

전제 조건 :


import json
import requests
from requests.auth import HTTPBasicAuth
import links_from_header

respget = lambda url: requests.get(url, auth=HTTPBasicAuth('githubusername', 'githubtoken'))

myorgname = 'abc'
nexturl = f"https://api.github.com/orgs/{myorgname}/repos?per_page=100"

while nexturl:
    print(nexturl)
    resp = respget(nexturl)

    linkheads = resp.headers.get('Link', None)
    if linkheads:
        linkheads_parsed = links_from_header.extract(linkheads)
        nexturl = linkheads_parsed.get('next', None)
    else:
        nexturl = None

    respcon = json.loads(resp.content)
    with open('repolist', 'a') as fh:
        fh.writelines([f'{respconi["full_name"]}\n' for respconi in respcon])

Then, you can use xargs or parallel and: cat repolist | parallel -I% hub clone %


If you have list of repositories in a list like this, then this shell script works:

user="https://github.com/user/"

declare -a arr=("repo1", "repo2")

for i in "${arr[@]}"

do

   echo $user"$i"

   git clone $user"$i"

done 

I created a sample batch script. You can download all private/public repositories from github.com. After a repository is downloaded, it is automatically converted to a zip file.

@echo off
setlocal EnableDelayedExpansion
SET "username=olyanren"
SET "password=G....."
set "mypath=%cd%\"
SET "url=https://%username%:%password%@github.com/%username%/"
FOR /F "tokens=* delims=" %%i in (files.txt) do (
SET repo=%%i
rmdir /s /q !repo!
git clone "!url!!repo!.git"
cd !repo!
echo !mypath!
git archive --format=zip -o "!mypath!!repo!.zip" HEAD
cd ..
)

Note: files.txt file should contain only repository names like:

repository1
repository2

Update from May 19

use this bash command for an organization (private repo included)

curl -u "{username}" "https://api.github.com/orgs/{org}/repos?page=1&per_page=100" | grep -o 'git@[^"]*' | xargs -L1 git clone

The prevailing answers here don't take into account that the Github API will only return a maximum of 100 repositories despite what you may specify in per_page. If you are cloning a Github org with more than 100 repositories, you will have to follow the paging links in the API response.

I wrote a CLI tool to do just that:

clone-github-org -o myorg

This will clone all repositories in the myorg organization to the current working directory.


Another shell script with comments that clones all repositories (public and private) from a user:

#!/bin/bash

USERNAME=INSERT_USERNAME_HERE
PASSWORD=INSERT_PASSWORD_HERE

# Generate auth header
AUTH=$(echo -n $USERNAME:$PASSWORD | base64)

# Get repository URLs
curl -iH "Authorization: Basic "$AUTH https://api.github.com/user/repos | grep -w clone_url > repos.txt

# Clean URLs (remove " and ,) and print only the second column
cat repos.txt | tr -d \"\, | awk '{print $2}'  > repos_clean.txt

# Insert username:password after protocol:// to generate clone URLs
cat repos_clean.txt |  sed "s/:\/\/git/:\/\/$USERNAME\:$PASSWORD\@git/g" > repos_clone.txt

while read FILE; do
    git clone $FILE
done <repos_clone.txt

rm repos.txt & rm repos_clone.txt

참고URL : https://stackoverflow.com/questions/19576742/how-to-clone-all-repos-at-once-from-github

반응형