Как скачать чужой репозиторий с github

от admin

Как скачать чужой репозиторий с github

Git clone illustration

The git clone command is used to create a copy of a specific repository or branch within a repository.

Git is a distributed version control system. Maximize the advantages of a full repository on your own machine by cloning.

What Does git clone Do?

When you clone a repository, you don’t get one file, like you may in other centralized version control systems. By cloning with Git, you get the entire repository — all files, all branches, and all commits.

Cloning a repository is typically only done once, at the beginning of your interaction with a project. Once a repository already exists on a remote, like on GitHub, then you would clone that repository so you could interact with it locally. Once you have cloned a repository, you won’t need to clone it again to do regular development.

The ability to work with the entire repository means that all developers can work more freely. Without being limited by which files you can work on, you can work on a feature branch to make changes safely. Then, you can:

  • later use git push to share your branch with the remote repository
  • open a pull request to compare the changes with your collaborators
  • test and deploy as needed from the branch
  • merge into the main branch.

How to Use git clone

Common usages and options for git clone

  • git clone [url] : Clone (download) a repository that already exists on GitHub, including all of the files, branches, and commits.
  • git clone —mirror : Clone a repository but without the ability to edit any of the files. This includes the refs, or branches. You may want to use this if you are trying to create a secondary copy of a repository on a separate remote and you want to match all of the branches. This may occur during configuration using a new remote for your Git hosting, or when using Git during automated testing.
  • git clone —single-branch : Clone only a single branch
  • git clone —sparse : Instead of populating the working directory with all of the files in the current commit recursively, only populate the files present in the root directory. This could help with performance when cloning large repositories with many directories and sub-directories.
  • `git clone —recurse-submodules[=<pathspec]: After the clone is created, initialize and clone submodules within based on the provided pathspec. This may be a good option if you are cloning a repository that you know to have submodules, and you will be working with those submodules as dependencies in your local development.

You can see all of the many options with git clone in git-scm’s documentation.

Examples of git clone

The most common usage of cloning is to simply clone a repository. This is only done once, when you begin working on a project, and would follow the syntax of git clone [url] .

git clone A Branch

git clone —single-branch : By default, git clone will create remote tracking branches for all of the branches currently present in the remote which is being cloned. The only local branch that is created is the default branch.

But, maybe for some reason you would like to only get a remote tracking branch for one specific branch, or clone one branch which isn’t the default branch. Both of these things happen when you use —single-branch with git clone .

This will create a clone that only has commits included in the current line of history. This means no other branches will be cloned. You can specify a certain branch to clone, but the default branch, usually main , will be selected by default.

To clone one specific branch, use:

git clone [url] —branch [branch] —single-branch

Cloning only one branch does not add any benefits unless the repository is very large and contains binary files that slow down the performance of the repository. The recommended solution is to optimize the performance of the repository before relying on single branch cloning strategies.

git clone With SSH

Depending on how you authenticate with the remote server, you may choose to clone using SSH.

If you choose to clone with SSH, you would use a specific SSH path for the repository instead of a URL. Typically, developers are authenticated with SSH from the machine level. This means that you would probably clone with HTTPS or with SSH — not a mix of both for your repositories.

  • git branch : This shows the existing branches in your local repository. You can also use git branch [banch-name] to create a branch from your current location, or git branch —all to see all branches, both the local ones on your machine, and the remote tracking branches stored from the last git pull or git fetch from the remote.
  • git pull : Updates your current local working branch with all new commits from the corresponding remote branch on GitHub. git pull is a combination of git fetch and git merge .
  • git push : Uploads all local branch commits to the remote.
  • git remote -v : Show the associated remote repositories and their stored name, like origin .

Get started with git and GitHub

Review code, manage projects, and build software alongside 40 million developers.

Cloning a repository

When you create a repository on GitHub.com, it exists as a remote repository. You can clone your repository to create a local copy on your computer and sync between the two locations.

About cloning a repository

You can clone a repository from GitHub.com to your local computer to make it easier to fix merge conflicts, add or remove files, and push larger commits. When you clone a repository, you copy the repository from GitHub.com to your local machine.

Cloning a repository pulls down a full copy of all the repository data that GitHub.com has at that point in time, including all versions of every file and folder for the project. You can push your changes to the remote repository on GitHub.com, or pull other people’s changes from GitHub.com. For more information, see «Using Git».

You can clone your existing repository or clone another person’s existing repository to contribute to a project.

Cloning a repository

On GitHub.com, navigate to the main page of the repository.

Above the list of files, click

Code.

Copy the URL for the repository.

    To clone the repository using HTTPS, under «HTTPS», click

The clipboard icon for copying the URL to clone a repository with GitHub CLI

Open Terminal Terminal Git Bash .

Change the current working directory to the location where you want the cloned directory.

Type git clone , and then paste the URL you copied earlier.

Press Enter to create your local clone.

To learn more about GitHub CLI, see «About GitHub CLI.»

To clone a repository locally, use the repo clone subcommand. Replace the repository parameter with the repository name. For example, octo-org/octo-repo , monalisa/octo-repo , or octo-repo . If the OWNER/ portion of the OWNER/REPO repository argument is omitted, it defaults to the name of the authenticating user.

You can also use the GitHub URL to clone a repository.

  1. On GitHub.com, navigate to the main page of the repository.
  2. Above the list of files, click

Code.

Open with GitHub Desktop to clone and open the repository with GitHub Desktop.

"Open with GitHub Desktop" button

Cloning an empty repository

An empty repository contains no files. It’s often made if you don’t initialize the repository with a README when creating it.

On GitHub.com, navigate to the main page of the repository.

To clone your repository using the command line using HTTPS, under «Quick setup», click

. To clone the repository using an SSH key, including a certificate issued by your organization’s SSH certificate authority, click SSH, then click

Alternatively, to clone your repository in Desktop, click

Set up in Desktop and follow the prompts to complete the clone.

Open Terminal Terminal Git Bash .

Change the current working directory to the location where you want the cloned directory.

Читать:
Как в nginx обрабатывать ссылки на кириллице

Type git clone , and then paste the URL you copied earlier.

Press Enter to create your local clone.

Troubleshooting cloning errors

When cloning a repository it’s possible that you might encounter some errors.

If you’re unable to clone a repository, check that:

  • You can connect using HTTPS. For more information, see «Troubleshooting cloning errors.»
  • You have permission to access the repository you want to clone. For more information, see «Troubleshooting cloning errors.»
  • The default branch you want to clone still exists. For more information, see «Troubleshooting cloning errors.»

Help us make these docs great!

All GitHub docs are open source. See something that's wrong or unclear? Submit a pull request.

Fastest way to download a GitHub project

I need to download the source code of the project Spring data graph example into my box. It has public read-only access. Is there is an extremely fast way of downloading this code?

I have no idea of working on GitHub/committing code and most tutorials out there on the web seems to assume that «I would want to setup a project in GitHub» and inundate me with 15-20 step processes. To me, if a source repository is available for the public, it should take less than 10 seconds to have that code in my filesystem.

Tutorials that provide me with 15-20 step processes:

I need something very very very simple. Just pull the source code, and I am more interested in seeing the source code and not learn GitHub.

Are there any fast pointers/tutorials? (I have a GitHub account.)

Peter Mortensen's user avatar

8 Answers 8

When you are on a project page, you can press the Download ZIP button which is located under the green <> Code drop down:

Screenshot showing "Download ZIP" button

This allows you to download the most recent version of the code as a zip archive.

If you aren’t seeing that button, it is likely because you aren’t on the main project page. To get there, click on the left-most tab labeled <> Code .

jncraton's user avatar

To me if a source repository is available for public it should take less than 10 seconds to have that code in my filesystem.

And of course, if you want to use Git (which GitHub is all about), then what you do to get the code onto your system is called «cloning the repository».

It’s a single Git invocation on the command line, and it will give you the code just as seen when you browse the repository on the web (when getting a ZIP archive, you will need to unpack it and so on, it’s not always directly browsable). For the repository you mention, you would do:

The git: -type URL is the one from the page you linked to. On my system just now, running the above command took 3.2 seconds. Of course, unlike ZIP, the time to clone a repository will increase when the repository’s history grows. There are options for that, but let’s keep this simple.

I’m just saying: You sound very frustrated when a large part of the problem is your reluctance to actually use Git.

Что такое git Clone и как клонировать репозиторий?

«Клонирование» означает создание идентичных особей естественным или искусственным путем.

Клонирование в Git — это процесс создания идентичной копии удаленного репозитория Git на локальную машину.

 git Clone

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

Как работает клонирование в Git?

Многие люди хотят создать общий репозиторий, чтобы позволить команде разработчиков публиковать свой код на GitHub / GitLab / BitBucket и т. д. Репозиторий, загружаемый в сеть для совместной работы, называется вышестоящим репозиторием или центральным репозиторием.

Центральный репозиторий указывает, что все изменения от всех участников помещаются только в этот репозиторий. Таким образом, это самый обновленный экземпляр репозитория самого себя. Иногда это часто называют исходным хранилищем. Изображение, приведенное ниже, довольно ясно говорит о концепции клонирования.

 git Clone

Что касается приведенного выше изображения, то процесс клонирования работает на следующих этапах:

Клонирование репозитория: пользователь начинает работу с вышестоящего репозитория на GitHub. Процесс начинается с клонирования репозитория на локальную машину. Теперь у пользователя есть точная копия файлов проекта в их системе, чтобы внести изменения.

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

Проталкивание изменений: как только изменения будут сделаны, они могут быть перемещены в вышестоящий репозиторий.

Примечание: владелец репозитория может разрешить / запретить прямые изменения в Центральном репозитории, установить различные уведомления о любом изменении, перенесенном в центральное хранилище и многое другое.

Как использовать команду git Clone

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

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

Клонирование репозитория из GitHub — это простой процесс. Но, прежде чем клонировать, пожалуйста, убедитесь, что у вас есть репозиторий на вашем аккаунте GitHub.

    1. Чтобы клонировать репозиторий, перейдите на страницу репозитория, которую вы хотите клонировать. Это можно сделать с помощью боковой колонки на приборной панели. git Clone
    2. Нажмите кнопку клонировать или загрузить.
    3. Скопируйте код, который появляется после нажатия кнопки. git Clone
    4. После этого откройте Git bash в своей системе  git Clone
    5. Проверьте каталоги (или репозитории), уже созданные в этом каталоге(используя команду ls). Как видно на рисунке, у меня есть только один репозиторий в каталоге Git Repo ToolsQA. git Clone
    6. Нажмите следующую команду, чтобы клонировать репозиторий:git clone <URL>URL здесь представляет собой тот же URL, который мы скопировали на третьем шаге.git_clone_urlURL — это ссылка на репозиторий GitHub. Вы можете ввести это в адресную строку вашего браузера и проверить, открывается ли страница репозитория или нет.
    7. При нажатии клавиши enter появится следующее сообщение. git CloneЭто займет несколько секунд, чтобы клонировать хранилище в вашей системе.Примечание: обратите внимание, что клонирование зависит от подключения к интернету, а время будет зависеть от пропускной способности вашего соединения. Если Git не может клонировать из-за слабого соединения, он будет отображать фатальную ошибку, и пользователю будет предложено повторить попытку до тех пор, пока вышеуказанное сообщение не появится.
    8. Подтвердите клонирование, проверив каталоги еще раз с помощью команды ls, которая перечисляет все файлы и папки.  git CloneПоскольку Централизованное хранилище в нашем случае называется ToolsQA, то же самое было скопировано на мою локальную машину.Проверьте локальный диск, перейдя к нему вручную.git Clone

    Каковы основные различия между раздвоением и клонированием?

    Чтобы очистить свой разум от воздуха, если он у вас есть, давайте посмотрим, чем отличаются эти два термина:

    Difference between Git Clone and Git Fork

    Разветвление делается на аккаунт github, а клонирование осуществляется с использованием git. При форке репозитория вы создаете копию исходного репозитория (вышестоящего репозитория), но этот репозиторий остается в вашей учетной записи GitHub. В то же время, когда вы клонируете репозиторий, он копируется на вашу локальную машину с помощью Git.

    Раздвоение — это понятие, а клонирование — это процесс. Разветвление — это просто содержащая отдельную копию репозитория команда, которая не участвует в этом процессе. Клонирование выполняется с помощью команды «git clone», и это процесс получения всех файлов кода на локальную машину.

    git pull

    В последнем уроке мы познакомились с командой Git fetch и Read more

    Git Fetch и Git Merge

    В одной из последних статей мы узнали о команде Git Read more

    Мы уже знаем, как вносить изменения в локальное хранилище и Read more

    Git Push

    Команда git push при выполнении перемещает изменения, внесенные пользователем на Read more

    Git Fork

    Сегодня мы узнаем, как скопировать чужой репозиторий в наш аккаунт Read more

    Подключение локального репозитория к удаленному репозиторию GitHub

    Все данные, доступные в локальном репозитории, могут быть загружены в Read more

Related Posts