Куда git клонирует по умолчанию windows

Learn about when and how to use git clone.

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?

git clone https://github.com/github/training-kit.git

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

git clone [url]

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.

Related Terms

  • 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.

Contribute to this article on GitHub.

Get started with git and GitHub

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

Sign up for GitHub

Sign in

Урок, в котором мы познакомимся с репозиториями git, научимся их создавать и клонировать, а также узнаем, зачем нужны ssh-ключи

Видеоурок. Часть 1. Практика

Все о репозиториях

  • что это такое
  • клонирование
  • публичные и приватные репозитории
  • создаем собственный репозиторий
  • Инициализация репозитория
  • Генерируем ssh-ключи

ssh-ключи

  • что это такое и зачем они нужны
  • генерируем свой ключ

Видеоурок. Часть 2

  • Что выбрать: github или bitbucket?
  • Копирование ssh-ключей

Конспект урока

Краткое содержание урока, основные инструкции для командной строки, полезные ссылки и советы.

Что такое репозиторий

Это каталог в файловой системе, где хранится информация о проекте:

  • файлы и папки проекта
  • история проекта
  • настройки проекта
  • служебная информация

Информация о репозитории хранится в скрытой папке .git в корне проекта.

Можно ли работать с git локально

Да, можно. Но при этом проект находится только на нашей машине и в случае поломки железа или случайной потери данных мы не сможем восстановить проект.

Локальный репозиторий

Это репозиторий, который хранится на нашей машине, в рабочей папке проекта. Это та самая скрытая папка .git

Удаленный репозиторий, зачем он нужен

Это репозиторий, который хранится в облаке, на сторонних сервисах, специально созданных под работу с проектами git.

Плюсы удаленного репозитория

  • выполняет роль резервной копии
  • возможность работать в команде
  • некоторые дополнительные возможности, которые предоставляет хостинг. Например, визуализация истории или возможность работать над проектом прямо в веб-интерфейсе

Что такое клонирование

Это копирование удаленного репозитория на локальную машину. Обычно это первое действие при работе с проектом.
При клонировании на нашу машину копируются файлы и папки проекта и вся его история.
То есть мы получаем доступ к истории не с момента начала нашей работы над проектом, а с самого начала проекта.

Как клонировать готовый проект

В первую очередь, нужно получить ссылку на проект. Мы можем найти ее сами или получим готовую, например, на новой работе.
Возьмем для примера репозиторий vuejs — https://github.com/vuejs/vue.git

Наберем в командной строке


    $ git clone https://github.com/vuejs/vue.git

При этом в текущем каталоге создастся папка vue, в ней окажутся все файлы проекта vue и специальная скрытая папка .git, то есть сам репозиторий, или информация о нем.

Как клонировать проект в другую папку

При клонировании по умолчанию создается папка с таким же названием, как и у репозитория. Но можно склонировать репозиторий и в другую папку вот так


    $ git clone https://github.com/vuejs/vue.git vue-new

Где vue-new — нужное название папки.

Свой удаленный репозиторий

Для своих проектов нам понадобится собственный репозиторий. Можно работать и локально, но плюсы удаленного мы уже рассматривали выше. Теперь нужно выбрать хостинг для наших git-проектов.

Где держать репозиторий

Есть множество вариантов, самые известные — это github и bitbucket. Нужно выбирать.

github или bitbucket

На самом деле не парьтесь. У них схожий функционал, и в начале работы с git мы не заметим разницы.
bitbucket мне нравится больше из-за интерфейса, но в уроках выберем github из-за его большей популярности.

Чтобы продолжить уроки, нужно зарегистрироваться на github. Если у вас нет там аккаунта, то форму регистрации увидите сразу на главной странице — https://github.com/

Как создать репозиторий в github

После регистрации создание репозитория доступно с главной страницы github. При создании нужно указать название проекта и тип (публичный или приватный). На остальное пока не обращаем внимания.

Права на репозиторий, публичные и приватные

Есть 2 типа репозиториев:

  • публичный (public), открыт всем
  • приватный (private), доступен только определенному кругу лиц — в первую очередь, нам самим

Публичные репозитории хороши для opensource-проектов и чтобы показать в резюме. Пока нам это не нужно.

Для себя будем создавать приватные репозитории. Для этого нам понадобятся ssh-ключи.

нельзя просто так клонировать приватный репозиторий

Что такое ssh-ключи

ssh-ключи используются для идентификации клиента на сервере при подключении по безопасному ssh-протоколу.
Другими словами, ssh-ключ нужен для того, чтобы пускать на сервер только определенных клиентов. Только тех, кому разрешен доступ к проекту.

ssh-ключ не имеет прямого отношения к git, но так репозитории находятся на удаленных серверах, то ssh-ключи используются для разграничения доступа к приватным репозиториям.

ssh-ключ состоит из пары ключей: публичного и приватного ключа. Это просто 2 текстовых файла:

  • /домашний-каталог/.ssh/id_rsa.pub — публичный
  • /домашний-каталог/.ssh/id_rsa — приватный

Публичный ключ передается сторонним серверам, например, github, для открытия доступа на эти сервера. Приватный ключ хранится только на нашей машине и никому не передается.
То есть когда у нас просят ssh-ключ, чтобы дать доступ на какой-нибудь сервер, мы отдаем именно публичный ключ, id_rsa.pub

Как сгенерировать ssh-ключ

ssh-ключи сами собой не появляются, но стоит проверить, возможно, они были установлены раньше. Запустим в терминале команды


    $ cd ~/.ssh
    $ ls -l

Если видим файлы id_rsa и id_rsa.pub — отлично, ключи уже есть.

Если этих файлов нет, то нужно сгенерировать ключи утилитой ssh-keygen. В Windows она устанавливается вместе с git, в Linux и MacOS при необходимости установите. В Linux, например, вот так


    $ sudo apt install ssh-keygen

После этого нужно сгенерировать пару ключей, запустив команду в терминале


    $ ssh-keygen -t rsa -b 4096 -C "your_email@example.com"

Проверяем


    $ ls -l
    total 24
    -rw-------  1 sn8 sn8 1675 Feb 11  2017 id_rsa
    -rw-r--r--  1 sn8 sn8  392 Feb 11  2017 id_rsa.pub
    -rw-r--r--  1 sn8 sn8 5746 Oct 28 21:52 known_hosts

Появились файлы id_rsa и id_rsa.pub — значит, ключи успешно сгенерированы.

known_hosts — это файл, в котором ssh прописывает сервера, на которые мы заходим.
При первом подключении к github нужно будет разрешить доступ к github.com (напечатать yes в терминале)

Как добавить ssh-ключ в настройках github

Открываем публичный ключ id_rsa.pub и копируем его содержимое. В настройках github ищем раздел «SSH и GPG keys» — https://github.com/settings/keys.
Жмем «New SSH key», задаем название ключа, например, имя, и вставляем форму публичный ключ, прямо текстом. Все, теперь у нас есть доступ к нашим приватным репозиториям.

Два способа создания проекта

Первый, когда мы начинаем новый проект. Удобнее будет создать репозиторий на github и склонировать пустой проект на локальную машину.

Второй, когда у нас уже есть проект. Нужно зайти в папку проекта и связать его с уже существующим репозиторием на github. Это называется инициализация.

Рассмотрим оба способа.

Пустой проект

Создаем приватный репозиторий на github, назовем его first-site.
Я зарегистрировался под именем Webdevkin, моя ссылка для клонирования будет такая — git@github.com:Webdevkin/first-site.git. Ваша зависит от имени пользователя.

Идем в командную строку и запускаем


    $ git clone git@github.com:Webdevkin/first-site.git

В текущей папке получим новую папку с названием first-site — это и есть наш проект.

P.S. У вас склонировать этот репозиторий не получится — он закрытый. Создайте свой :-)

Непустой проект

Допустим, у нас на локальной машине уже есть проект second-site. Создаем в github репозиторий second-site. Заходим в папку проекта и выполняем команды


    $ git init
    $ git add .
    $ git commit -m "Initial commit"
    $ git remote add origin git@github.com:Webdevkin/second-site.git
    $ git push -u origin master

Все, можно приступать к работе над проектом. Команды add, commit и push мы разберем в следующих уроках.

Это единственный урок, в котором мы разбирались с тонкостями репозиториев. В дальнейшем будем считать, что репозиторий = проект.

Что могу посоветовать

  • github или bitbucket? Для личных проектов неважно, оба сервиса разрешают бесплатно создавать приватные репозитории. Для open source или резюме — github
  • не увлекайтесь клонированием в папку со своим названием. Есть шанс запутаться, самому или коллегам
  • не путайте публичный и приватный ключи. Отдаем вовне только публичный ключ id_rsa.pub
  • при смене рабочей машины можно не генерировать ssh-ключи заново, а скопировать их со старой машины. Тогда не придется заново прописывать новые ключи на серверах

Немного подробнее о копировании ssh-ключей

Как скопировать ssh-ключи с одной машины на другую

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

  • Скопировать id_rsa и id_rsa.pub со старой машины на новую
  • Посмотреть права на файлы, возможно, ключи окажутся слишком «открытыми» для записи и потребуется сменить им права доступа — sudo chmod 700 ~/.ssh/*
  • Выполнить команду ssh-add

Ссылки, которые могут пригодиться

  • github — https://github.com/
  • bitbucket — https://bitbucket.org/
  • подробнее об ssh-ключах (en) — connecting-to-github-with-ssh

На этом все. В следующем уроке мы сделаем первые изменения в проекте и начнем понимать, в чем заключается прелесть git.

Спасибо за внимание и до встречи!

Все уроки курса

  • Вводный урок
  • 1. Установка и базовая настройка git
  • 2. Создание и клонирование репозитория git
  • 3. Делаем первые изменения, git status и git diff
  • 4. Коммиты и история коммитов, git commit, git log и git show
  • 5. Подробнее об истории коммитов. Путешествие по истории
  • 6. Работа с сервером, git push и git pull
  • 7. Ветки — главная фишка git, git branch и git checkout
  • 8. Работа с ветками на сервере, git fetch
  • 9. Слияния или мерджи веток, git merge
  • 10. Конфликты и их разрешение
  • Платная часть курса. Презентация
  • * 11. Работа с gitignore и git exclude
  • * 12. Буфер обмена git, git stash
  • * 13. Копирование коммитов, git cherry-pick
  • * 14. Отмена и редактирование последнего коммита
  • * 15. Отмена произвольного коммита, git revert
  •    16. Склеивание коммитов, git rebase —interactive и git reflog
  • * 17. Зачем склеивать коммиты. Плюсы и минусы сквоша
  • * 18. Работа с git rebase. Отличия от merge
  • * 19. Что такое git push —force и как с ним работать
  • * 20. Ищем баги с помощью git, git bisect
  • * 21. Как и зачем работать с тегами git
  • * 22. Процессы: github flow и git flow
  • * 23. Псевдонимы в git
  •    24. Мердж-реквесты
  • * 25. Форки

* платные уроки

список обновляется…

To be a bit more complete, Git works with:

  • the working tree (the root of which being where you made a git init)
  • «path to the Git repository» (where there is a .git, which will store the revisions of all your files)

GIT_DIR is an environment variable, which can be an absolute path or relative path to current working directory.

If it is not defined, the «path to the git repository» is by default at the root directory of your working tree (again, where you made a git init).

You can actually execute any Git command from anywhere from your disk, provided you specify the working tree path and the Git repository path:

git command --git-dir=<path> --work-tree=<path>

But if you execute them in one of the subdirectories of a Git repository (with no GIT-DIR or working tree path specified), Git will simply look in the current and parent directories until it find a .git, assume this it also the root directory of your working tree, and use that .git as the only container for all the revisions of your files.

Note: .git is also hidden in Windows (msysgit).
You would have to do a dir /AH to see it.
git 2.9 (June 2016) allows to configure that.


Note that Git 2.18 (Q2 2018) is starting the process to evolve how Git is storing objects, by refactoring the internal global data structure to make it possible
to open multiple repositories, work with and then close them.

See commit 4a7c05f, commit 1fea63e (23 Mar 2018) by Jonathan Nieder (artagnon).
See commit bd27f50, commit ec7283e, commit d2607fa, commit a68377b, commit e977fc7, commit e35454f, commit 332295d, commit 2ba0bfd, commit fbe33e2, commit cf78ae4, commit 13068bf, commit 77f012e, commit 0b20903, commit 93d8d1e, commit ca5e6d2, commit cfc62fc, commit 13313fc, commit 9a00580 (23 Mar 2018) by Stefan Beller (stefanbeller).
(Merged by Junio C Hamano — gitster — in commit cf0b179, 11 Apr 2018)

repository: introduce raw object store field

The raw object store field will contain any objects needed for access
to objects in a given repository.

This patch introduces the raw object store and populates it with the
objectdir, which used to be part of the repository struct.

As the struct gains members, we’ll also populate the function to clear
the memory for these members.

In a later step, we’ll introduce a struct object_parser, that will
complement the object parsing in a repository struct:

  • The raw object parser is the layer that will provide access to raw object content,
  • while the higher level object parser code will parse raw objects and
    keeps track of parenthood and other object relationships using ‘struct object‘.

    For now only add the lower level to the repository struct.

To be a bit more complete, Git works with:

  • the working tree (the root of which being where you made a git init)
  • «path to the Git repository» (where there is a .git, which will store the revisions of all your files)

GIT_DIR is an environment variable, which can be an absolute path or relative path to current working directory.

If it is not defined, the «path to the git repository» is by default at the root directory of your working tree (again, where you made a git init).

You can actually execute any Git command from anywhere from your disk, provided you specify the working tree path and the Git repository path:

git command --git-dir=<path> --work-tree=<path>

But if you execute them in one of the subdirectories of a Git repository (with no GIT-DIR or working tree path specified), Git will simply look in the current and parent directories until it find a .git, assume this it also the root directory of your working tree, and use that .git as the only container for all the revisions of your files.

Note: .git is also hidden in Windows (msysgit).
You would have to do a dir /AH to see it.
git 2.9 (June 2016) allows to configure that.


Note that Git 2.18 (Q2 2018) is starting the process to evolve how Git is storing objects, by refactoring the internal global data structure to make it possible
to open multiple repositories, work with and then close them.

See commit 4a7c05f, commit 1fea63e (23 Mar 2018) by Jonathan Nieder (artagnon).
See commit bd27f50, commit ec7283e, commit d2607fa, commit a68377b, commit e977fc7, commit e35454f, commit 332295d, commit 2ba0bfd, commit fbe33e2, commit cf78ae4, commit 13068bf, commit 77f012e, commit 0b20903, commit 93d8d1e, commit ca5e6d2, commit cfc62fc, commit 13313fc, commit 9a00580 (23 Mar 2018) by Stefan Beller (stefanbeller).
(Merged by Junio C Hamano — gitster — in commit cf0b179, 11 Apr 2018)

repository: introduce raw object store field

The raw object store field will contain any objects needed for access
to objects in a given repository.

This patch introduces the raw object store and populates it with the
objectdir, which used to be part of the repository struct.

As the struct gains members, we’ll also populate the function to clear
the memory for these members.

In a later step, we’ll introduce a struct object_parser, that will
complement the object parsing in a repository struct:

  • The raw object parser is the layer that will provide access to raw object content,
  • while the higher level object parser code will parse raw objects and
    keeps track of parenthood and other object relationships using ‘struct object‘.

    For now only add the lower level to the repository struct.

Понравилась статья? Поделить с друзьями:
  • Куда docker сохраняет образы на windows
  • Крутые живые обои на рабочий стол для windows 10 скачать бесплатно
  • Кубический корень в калькуляторе windows 10
  • Крутые виджеты для рабочего стола windows 10
  • Кубейсик скачать бесплатно для windows 7