Access git repository from windows

2.1 Git Basics — Getting a Git Repository

If you can read only one chapter to get going with Git, this is it. This chapter covers every basic command you need to do the vast majority of the things you’ll eventually spend your time doing with Git. By the end of the chapter, you should be able to configure and initialize a repository, begin and stop tracking files, and stage and commit changes. We’ll also show you how to set up Git to ignore certain files and file patterns, how to undo mistakes quickly and easily, how to browse the history of your project and view changes between commits, and how to push and pull from remote repositories.

Getting a Git Repository

You typically obtain a Git repository in one of two ways:

You can take a local directory that is currently not under version control, and turn it into a Git repository, or

You can clone an existing Git repository from elsewhere.

In either case, you end up with a Git repository on your local machine, ready for work.

Initializing a Repository in an Existing Directory

If you have a project directory that is currently not under version control and you want to start controlling it with Git, you first need to go to that project’s directory. If you’ve never done this, it looks a little different depending on which system you’re running:

This creates a new subdirectory named .git that contains all of your necessary repository files — a Git repository skeleton. At this point, nothing in your project is tracked yet. See Git Internals for more information about exactly what files are contained in the .git directory you just created.

If you want to start version-controlling existing files (as opposed to an empty directory), you should probably begin tracking those files and do an initial commit. You can accomplish that with a few git add commands that specify the files you want to track, followed by a git commit :

We’ll go over what these commands do in just a minute. At this point, you have a Git repository with tracked files and an initial commit.

Cloning an Existing Repository

If you want to get a copy of an existing Git repository — for example, a project you’d like to contribute to — the command you need is git clone . If you’re familiar with other VCSs such as Subversion, you’ll notice that the command is «clone» and not «checkout». This is an important distinction — instead of getting just a working copy, Git receives a full copy of nearly all data that the server has. Every version of every file for the history of the project is pulled down by default when you run git clone . In fact, if your server disk gets corrupted, you can often use nearly any of the clones on any client to set the server back to the state it was in when it was cloned (you may lose some server-side hooks and such, but all the versioned data would be there — see Getting Git on a Server for more details).

You clone a repository with git clone . For example, if you want to clone the Git linkable library called libgit2 , you can do so like this:

That creates a directory named libgit2 , initializes a .git directory inside it, pulls down all the data for that repository, and checks out a working copy of the latest version. If you go into the new libgit2 directory that was just created, you’ll see the project files in there, ready to be worked on or used.

Читайте также:  Шрифт печкин для windows 10

If you want to clone the repository into a directory named something other than libgit2 , you can specify the new directory name as an additional argument:

That command does the same thing as the previous one, but the target directory is called mylibgit .

Локальная настройка репозитория Git для документации Set up Git repository locally for documentation

В этой статье показано, как настроить репозиторий Git на локальном компьютере для создания документации по продуктам Майкрософт. This article describes the steps to set up a Git repository on your local machine, with the intent to contribute to Microsoft documentation. Добавлять новые статьи, вносить значительные правки в существующие и изменять графическое оформление можно при помощи локально клонированного репозитория. Contributors may use a locally cloned repository to add new articles, do major edits on existing articles, or change artwork.

Чтобы приступить к работе с документацией, необходимо однократно выполнить следующие действия: You run these one-time setup activities to start contributing:

  • определить соответствующий репозиторий; Determine the appropriate repository
  • создать вилку репозитория Git в учетной записи GitHub; Fork the repository to your GitHub account
  • выбрать локальную папку для клонированных файлов; Choose a local folder for the cloned files
  • клонировать репозиторий на локальный компьютер; Clone the repository to your local machine
  • настроить значение вышестоящего удаленного источника. Configure the upstream remote value

Если вы вносите в статью лишь небольшие изменения, вам не нужно выполнять описанные здесь шаги. If you’re making only minor changes to an article, you do not need to complete the steps in this article. Вы можете перейти непосредственно к рабочему процессу по внесению быстрых изменений. You can continue directly to the quick changes workflow.

Общие сведения Overview

Для участия в разработке документации на сайте Майкрософт вы можете локально создавать и редактировать файлы Markdown, клонировав соответствующий репозиторий документации. To contribute to Microsoft’s documentation site, you can make and edit Markdown files locally by cloning the corresponding documentation repository. Чтобы получить разрешения Майкрософт на чтение и запись для соответствующего репозитория, нужно создать его вилку в учетной записи GitHub. Это позволит сохранять предлагаемые изменения. Microsoft requires you to fork the appropriate repository into your own GitHub account so that you have read/write permissions there to store your proposed changes. Затем изменения объединяются в центральном общем репозитории, доступном только для чтения, с помощью запросов на вытягивание. Then you use pull requests to merge changes into the read-only central shared repository.

Если вы раньше не работали с GitHub, посмотрите следующее видео, где представлен концептуальный обзор процесса создания вилок и клонирования репозиториев: If you’re new to GitHub, watch the following video for a conceptual overview of the forking and cloning process:

Определение репозитория Determine the repository

Документация, размещенная на сайте docs.microsoft.com, находится в нескольких разных репозиториях на github.com. Documentation hosted at docs.microsoft.com resides in several different repositories at github.com.

Если вы точно не знаете, какой репозиторий использовать, откройте статью на сайте docs.microsoft.com в своем веб-браузере. If you are unsure of which repository to use, then visit the article on docs.microsoft.com using your web browser. Справа над статьей выберите ссылку Правка (значок карандаша). Select the Edit link (pencil icon) on the upper right of the article.

По этой ссылке вы перейдете к расположению нужного файла Markdown в соответствующем репозитории на сайте github.com. That link takes you to github.com location for the corresponding Markdown file in the appropriate repository. Запишите URL-адрес, чтобы узнать имя репозитория. Note the URL to view the repository name.

Например, для участия в создании документации можно использовать следующие популярные репозитории: For example, these popular repositories are available for public contributions:

Создание вилки репозитория Fork the repository

Используя соответствующий репозиторий, создайте его вилку в своей учетной записи GitHub на сайте GitHub. Using the appropriate repository, create a fork of the repository into your own GitHub account by using the GitHub website.

Персональная вилка необходима, поскольку все основные репозитории документации предоставляют доступ только для чтения. A personal fork is required since all main documentation repositories provide read-only access. Чтобы внести изменение, вам нужно отправить из вилки в основной репозиторий запрос на вытягивание. To make changes, you must submit a pull request from your fork into the main repository. Чтобы ускорить этот процесс, сначала следует создать копию репозитория с доступом на запись. To facilitate this process, you first need your own copy of the repository, in which you have write access. Вилка в GitHub решает эту задачу. A GitHub fork serves that purpose.

Читайте также:  Viber desktop windows downloads

Перейдите в GitHub на страницу главного репозитория, а затем нажмите кнопку Fork (Создать вилку) вверху справа. Go to the main repository’s GitHub page and click the Fork button on the upper right.

Если будет предложено, выберите плитку своей учетной записи GitHub в качестве расположения для создаваемой вилки. If you are prompted, select your GitHub account tile as the destination where the fork should be created. После этого в вашей учетной записи GitHub будет создана копия репозитория, называемая вилкой. This prompt creates a copy of the repository within your GitHub account, known as a fork.

Выбор локальной папки Choose a local folder

Создайте локальную папку для локального хранения копии репозитория. Make a local folder to hold a copy of the repository locally. Размер некоторых репозиториев может быть значительным, например до 5 ГБ для azure-docs. Some of the repositories can be large; up to 5 GB for azure-docs for example. Выберите расположение с доступным местом на диске. Choose a location with available disk space.

Выберите имя папки — оно должно быть простым для запоминания и ввода. Choose a folder name should be easy for you to remember and type. Например, можно использовать корневую папку C:\docs\ или создать папку в каталоге профиля пользователя

/Documents/docs/ For example, consider a root folder C:\docs\ or make a folder in your user profile directory

Не следует выбирать путь к локальной папке, вложенной в другую папку репозитория Git. Avoid choosing a local folder path that is nested inside of another git repository folder location. Несмотря на то что, что клонированные папки Git можно хранить рядом друг с другом, вложение папок Git приводит к ошибкам отслеживания файлов. While it is acceptable to store the git cloned folders adjacent to each other, nesting git folders inside one another causes errors for the file tracking.

Запустите Git Bash Launch Git Bash

Расположением по умолчанию, в котором обычно запускается Git Bash, является домашний каталог (

) или /c/users/ / в ОС Windows. The default location that Git Bash starts in is typically the home directory (

) or /c/users/ / on Windows OS.

Чтобы определить текущий каталог, ведите pwd в запросе $. To determine the current directory, type pwd at the $ prompt.

Преобразуйте каталог (cd) в папку, созданную для локального размещения репозитория. Change directory (cd) into the folder that you created for hosting the repository locally. Обратите внимание, что Git Bash поддерживает соглашение Linux по использованию в путях к папкам прямых, а не обратных косых черт. Note that Git Bash uses the Linux convention of forward-slashes instead of back-slashes for folder paths.

Например, cd /c/docs/ или cd

/Documents/docs/ . For example, cd /c/docs/ or cd

Создание локального клона Create a local clone

С помощью Git Bash подготовьтесь выполнить команду клонирования для вытягивания копии репозитории (вашей вилки) в текущий каталог на устройстве. Using Git Bash, prepare to run the clone command to pull a copy of a repository (your fork) down to your device on the current directory.

Проверка подлинности с использованием Git Credential Manager Authenticate by using Git Credential Manager

Если вы установили последнюю версию Git для Windows и согласились на установку по умолчанию, будет по умолчанию активирован диспетчер учетных данных Git Credential Manager. If you installed the latest version of Git for Windows and accepted the default installation, Git Credential Manager is enabled by default. Git Credential Manager упрощает проверку подлинности, избавляя от необходимости отзывать личный маркер доступа при повторной установке подключений с проверкой подлинности и удаленных подключений с GitHub. Git Credential Manager makes authentication much easier because you don’t need to recall your personal access token when re-establishing authenticated connections and remotes with GitHub.

Читайте также:  Dual graphics amd windows 10 x64

Выполните команду клонирования, указав имя репозитория. Run the clone command, by providing the repository name. Во время клонирования разветвленный репозиторий скачивается (клонируется) на локальный компьютер. Cloning downloads (clone) the forked repository on your local computer.

Чтобы получить URL-адрес своей вилки GitHub для команды клонирования, нажмите кнопку Clone or download (Клонировать или скачать) в пользовательском интерфейсе GitHub: You can get your fork’s GitHub URL for the clone command from the Clone or download button in the GitHub UI:

В процессе клонирования обязательно укажите путь к своей вилке, а не к главному репозиторию, из которого вы ее создали. Be sure to specify the path to your fork during the cloning process, not the main repository from which you created the fork. В противном случае вы не сможете вносить изменения. Otherwise, you cannot contribute changes. Ссылки на вашу вилку осуществляются по имени вашей личной учетной записи GitHub, например github.com/ / . Your fork is referenced through your personal GitHub user account, such as github.com/ / .

Команда клонирования должна выглядеть приблизительно следующим образом. Your clone command should look similar to this example:

При появлении запроса введите учетные данные GitHub. When you’re prompted, enter your GitHub credentials.

При появлении запроса введите код двухфакторной проверки подлинности. When you’re prompted, enter your two-factor authentication code.

Ваши учетные данные будут сохранены для проверки подлинности последующих запросов GitHub. Your credentials will be saved and used to authenticate future GitHub requests. Проверка подлинности выполняется на каждом компьютере один раз. You only need to do this authentication once per computer.

Запущенная команда клонирования скачивает копию файлов репозитория из вашей вилки в новую папку на локальном диске. The clone command runs and downloads a copy of the repository files from your fork into a new folder on the local disk. Новая папка создается в текущей папке. A new folder is made within the current folder. В зависимости от размера репозитория этот процесс может занять несколько минут. It may take a few minutes, depending on the repository size. По его окончании вы можете открыть папку, чтобы просмотреть ее структуру. You can explore the folder to see the structure once it is finished.

Настройка удаленного вышестоящего подключения Configure remote upstream

После клонирования репозитория следует установить удаленное подключение только для чтения, называемое вышестоящим, к основному репозиторию. After cloning the repository, set up a read-only remote connection to the main repository named upstream. С помощью URL-адреса вышестоящего подключения вы сможете обеспечить синхронизацию вашего локального репозитория с последними правками, внесенными другими участниками. You use the upstream URL to keep your local repository in sync with the latest changes made by others. Команда git remote служит для задания значения конфигурации. The git remote command is used to set the configuration value. С помощью команды принесения можно обновить сведения о ветви из вышестоящего репозитория. You use the fetch command to refresh the branch info from the upstream repository.

Если вы используете Git Credential Manager, выполните следующие команды. If you’re using Git Credential Manager, use the following commands. Замените заполнители и . Replace the and placeholders.

Просмотрите настроенные значения и проверьте правильность URL-адресов. View the configured values and confirm the URLs are correct. Убедитесь, что URL-адреса исходного подключения ведут к вашей персональной вилке. Ensure the origin URLs point to your personal fork. Убедитесь, что URL-адреса вышестоящего подключения ведут к основному репозиторию, например MicrosoftDocs или Azure. Ensure the upstream URLs point to the main repository, such as MicrosoftDocs or Azure.

Далее приводится пример выходных данных для подключения к удаленному репозиторию. Example remote output is shown. Здесь вымышленная учетная запись Git с именем MyGitAccount настраивается с личным маркером доступа для обращения к репозиторию azure-docs. A fictitious git account named MyGitAccount is configured with a personal access token to access the repo azure-docs:

Если вы допустили ошибку, значение удаленного подключения можно очистить. If you made a mistake, you can remove the remote value. Чтобы удалить значение вышестоящего подключения, выполните команду git remote remove upstream . To remove the upstream value, run the command git remote remove upstream .

Оцените статью