Подтвердить что ты не робот

Клонировать несколько репозиториев git в одном локальном каталоге?

Можно ли git clone несколько репозиториев git одной командой (например: git clone "1.git,2.git,3.git.." в одном локальном каталоге?

4b9b3361

Ответ 1

Вы можете найти пример скрипта как этот:

У меня есть этот файл под названием "клон", содержащий URL-адреса нескольких репозиториев git (взят с сайта djangosites.com. Потрясающий сайт. Обязательно посетите)

Snippet:

$ cat clone
https://github.com/igorsobreira/igorsobreira.com https://github.com/ella/ella https://github.com/divio/django-cms/ https://github.com/palewire/palewire.com https://github.com/jabapyth/jfcom https://github.com/humanfromearth/snippify https://github.com/scaphilo/koalixcrm https://github.com/jlev/Boycott-Toolkit https://github.com/jbalogh/zamboni/ https://github.com/ASKBOT/askbot-devel https://github.com/emesik/djiki https://github.com/vicalloy/LBForum https://github.com/agiliq/agiliq https://github.com/bartTC/dpaste.de https://github.com/bartTC/django-paste https://github.com/bartTC/dpaste_de/ https://github.com/fotochest/fotochest https://esp.mit.edu/git/esp-project.git https://github.com/titan2x/bashoneliners.git

По-видимому, сложнее клонировать несколько репо одновременно (git clone <repo1> <repo2>... <repon> не работает). Поэтому я написал этот короткий код bash, чтобы он работал:

Код:

atm in /home/atm/git/django_repos
$ for f in 'cat clone'; do 'git clone $f'; done 

На gist.github.com вы найдете много других, таких как этот, для клонирования всех ваших репозиториев из GitHub:

#!/bin/bash
#
# Copyright 2011, Tim Branyen @tbranyen <[email protected]>
# Dual licensed under the MIT and GPL licenses.
#
# Automatically clone single or multiple repos into a folder, 
# great for setting up a git projects folder.
#
# Install: curl https://gist.github.com/raw/902154/github.sh > /usr/local/bin/gh
#          chmod +x /usr/local/bin/gh
#

# Internal properties
[email protected]:
GITHUB_USERNAME=$(git config --global github.user)

function main {
  # Improperly configured user
  detect_user

  # Missing arguments
  args=$1
  if [ -z $args ]; then
    echo '
      gh: try '''gh --help''' for more information
    '
    exit
  fi

  # Display help text
  if [ $args = '--help' ]; then
    echo '
      Clone repos from your GitHub
        gh repo1 repo2

      Clone repos from others GitHub
        gh username/repo1 username/repo2

      Clone mixed repos:
        gh repo1 username/repo2

      Clone line separated repos from file:
        cat file | xargs gh
    '
    exit
  fi

  # Parse arguments and clone repos.
  find_repos
}

function detect_user {
  # If no username configured, attempt to pull from git --config
  if [ -n "$GITHUB_USERNAME" ]; then
    USERNAME=$GITHUB_USERNAME
  else
    echo '
      gh: missing username
      configure username with '''git config --global github.user username'''
    '
    exit
  fi
}

function find_repos {
  for repo in $args; do
    # If a user provides the parameter username/repo pull in that specific repository.
    if [ 'awk -v repo="$repo" -v delimit="/" 'BEGIN{print index(repo,delimit)}'' -ne 0 ]; then
      echo "Pulling in $repo";
      git clone $GITHUB_PREFIX$repo.git

    # Default to you.
    else
      echo "Pulling in $USERNAME/$repo";
      git clone $GITHUB_PREFIX$USERNAME/$repo.git
    fi
  done
}

main $*

В более общем случае необходим подход сценариев, и lilgeek упомянул bl4ckbo7/agt, сценарий python, который включает в себя клонирование с самой быстрой и параллельной функцией клонирования.

https://raw.githubusercontent.com/bl4ckbo7/agt/master/screenshots/agt_clone1.png

Ответ 2

Вот как почти решил для себя:

git clone https://myrepo.com/folder.git && \
git clone https://myrepo.com/folder2.git && \
git clone https://myrepo.com/folder3.git

Это гораздо проще построить с помощью редактора кода, такого как Sublime или VSCode.

Единственный недостаток для меня: если вы не сохранили свои учетные данные, вам придется вводить их снова и снова.

Ответ 3

Я создал образец script для моего проекта. Наш проект включает множество репозиториев, которые нужно клонировать, когда новый человек присоединяется к команде.

Итак, вот содержание script, которое вы можете сохранить в некоторые исполняемые файлы и выполнить.

   echo -n Please Enter your GitHub Username:
        read username
        echo -n Please Enter your GitHub Password
        read -s password // doesn't echoes the password on screen
        git clone 

https://$username:[email protected]/location/reponame1.git
https://$username:[email protected]/location/reponame2.git
....
https://$username:[email protected]/location/reponamen.git

Его тихое полезна, чтобы избежать скучных ручных усилий и гарантировать, что все необходимые проекты будут клонированы за один раз.

Надеюсь, мой ответ поможет и кому-то другому.

Ответ 4

Вы можете использовать смесь решений.

Используйте git credential.helper, чтобы установить тайм-аут кэша (см. Это), затем вы можете использовать скрипт/список, подобный тому, который был предложен Фабио. Таким образом, вам нужно будет ввести свои учетные данные только один раз (обычно, если только клон не займет больше времени, чем тайм-аут кеша).

git config --global credential.helper 'cache timeout 3600'
git clone https://[email protected]/myproject/myrepo.git
### password should be prompted 
git clone https://[email protected]/myproject/mysecondrepo.git
### look ma, no password prompt!
git clone https://[email protected]/myproject/mythirdrepo.git
git clone https://[email protected]/myproject/myfourthrepo.git
git clone https://[email protected]/myproject/andsoforthrepo.git

Это все еще последовательно, но это помогает и довольно просто, ИМХО.

Ответ 5

Я уверен, что этот инструмент поможет вам в широком масштабе.

https://github.com/bl4ckbo7/agt [Расширенный инструмент Git]

Поблагодаришь меня позже. ;)

@vonc @vir2al

Ответ 6

Прочитав этот и другие посты, я закончил с этим сценарием.

Мне нужна аутентификация в моей локальной среде для моих репозиториев.

Итак, скрипт попросит вас ввести имя пользователя, пароль и параметр, если вы хотите запомнить свои учетные данные в хранилище.

В целях безопасности я удаляю имя пользователя и пароль из файла конфигурации в git. (Не уверен, что эти учетные данные хранятся в другом месте)

#!/bin/bash
#
#This script is intended to be used with repositories that need authentication
#

#Funtion to erase the $username:[email protected] from the config file from git in the repo
function erase_user_pass() {
  printf "${green}lets clean $1 from $2 \n${normal}"
  sed -i 's/'"$1"'/'""'/g' $2
}

#function to download the repo
#1-clone the repo
#2-fix the config file by deleting the user and password
#3-execute the git command to automatically store the credentials if the user answer yes on the startup
#
# param 1 = name of the repo
# param 2 = string to complet the url of the repo
#
# example repo in https://git.something.com/yourcompany/your.project.git
#
# the param1 should be your.project
# the param2 should be git.something.com/yourcompany/your.project.git (without 'https://')
#
# download_repo 'your.project' 'git.something.com/yourcompany/your.project.git'
#
function download_repo() {
  path=$(pwd)
  printf "${blue}\n Importing $1\n\n${normal}"
  git clone https://$username:[email protected]$2
  file="$(pwd)/$1/.git/config"
  replace_string="$username:[email protected]"
  erase_user_pass $replace_string $file
  cd ./$1
  if [ "$STORE_OK" == 'Yes' ]
    then
     printf "${green} store credentials for the repo $1  \n${normal}"
     git config credential.helper store
  fi
  cd $path
}

blue=$(tput setaf 4)
green=$(tput setaf 2)
normal=$(tput sgr0)

echo -n Please Enter your GitHub Username:
read username
echo -n Please Enter your GitHub Password:
read -s password

printf "\n\nDo you want to store your credentials locally?:"
STORE_OK=
select STORE_OK in Yes No
do
  case $STORE_OK in
    '') echo 'Please enter 1 for Yes, or 2 for No.';;
    ?*) break
  esac
done

printf "${blue}\n\n lets import your repos\n\n${normal}"

# repo 1 https://git.something.com/yourcompany/your.project.git
download_repo 'your.project' 'git.something.com/yourcompany/your.project.git'
# repo 2 https://git.something.com/yourcompany/your.project2.git
download_repo 'your.project2' 'git.something.com/yourcompany/your.project2.git'

printf "${blue}\n Enjoy :)"

exit 0

Вам необходимо заменить вызовы download_repo, чтобы они указывали на ваши репозитории, это фальшивка.

С уважением и благодарностью за ответы других.