- Как пользоваться GitHub на компьютере с Linux
- Установка git
- Синтаксис
- Создание проекта на локальном компьютере
- Отправка данных на GitHub
- Создание репозитория
- Заливаем проект в репозиторий на GitHub
- Получение файлов с GitHub
- Клонирование проекта
- Возможные ошибки
- 1. При попытке отправить данные на GitHub, получаем ошибку:
- Git Guides
- Get started with git and GitHub
- How to Install Git and Clone a GitHub Repository
- Install and Configure Git
- Clone a GitHub Test Repository
- Create a GitHub Account and Fork the Test Repo
- Push to the Forked Repo
- Create a Pull Request Against the Original, Previously Cloned Repo
- More Information
Как пользоваться GitHub на компьютере с Linux
GitHub — один из используемых сервисов размещения проектов для совместной разработки. Он поддерживает контроль версий, возможность отслеживания изменений кода, сравнение строк, а также он бесплатен.
В данной статье приведены примеры использования сервиса на компьютере под управлением операционных систем семейства Linux. Мы рассмотрим, как создать проект на локальном компьютере и залить его на сервис с помощью командной строки. Рассмотренные варианты использования git также можно применять на desktop системах, запустив окно терминала.
Установка git
Управление выполняется с помощью приложения git. Если его нет в системе, установку можно выполнить из репозитория.
Если используем CentOS / Red Hat:
yum install git-core
Если используем Ubuntu / Debian:
apt-get install git
Если мы хотим воспользоваться сервисом с компьютера Windows или Mac OS, необходимо скачать и установить desktop версию с официального сайта.
Синтаксис
Команды имеют следующий синтаксис:
* полный перечень опций, команд и аргументов можно получить командой man git.
Создание проекта на локальном компьютере
Прежде чем отправить проект на GitHub, создаем его на нашем компьютере. Для этого переходим в каталог с файлами проекта:
Инициализируем проект для git:
Мы получим ответ похожий на:
Initialized empty Git repository in /projects/.git/
Это означает, что репозиторий git создан.
Теперь добавим файлы в репозиторий:
* данной командой мы добавили папку и ее содержимое в репозиторий git.
Отправка данных на GitHub
Теперь можно отправить данные на сервис. Для этого у нас должна быть зарегистрированная учетная запись и создан репозиторий на GitHub.
Создание репозитория
Переходим на портал github.com и входим в систему или проходим несложную регистрацию:
Проходим процесс подтверждения, что мы не робот. Затем завершаем несколько шагов регистрации, нажимая Submit. В итоге мы получим письмо на адрес электронной почты, которую указали при регистрации. Необходимо будем подтвердить email, перейдя в письме по кнопке Verify email address.
Создаем репозиторий. Для этого кликаем по иконке профиля и переходим в раздел Your repositories:
И кликаем по кнопке New. В следующем окне даем название репозиторию и нажимаем Create repository:
Мы увидим страницу с путем к репозиторию:
Заливаем проект в репозиторий на GitHub
Добавляем комментарий к нашему проекту:
git commit -m «Очередное изменение проекта» -a
* где Очередное изменение проекта — произвольный комментарий; параметр -a указывает, что комментарий нужно применить ко всем измененным файлам.
Теперь подключаемся к созданному репозиторию:
git remote add origin https://github.com/dmosktest/project1.git
* где dmosktest — логин, который был указан при регистрации на github, а project1 — название, которое мы задали, когда создавали репозиторий.
* удалить удаленный репозиторий можно командой git remote rm origin.
Закидываем проект на GitHub:
git push origin master
* где master — ветка проекта (веток может быть несколько).
В нашем проекте на GitHub должны появиться файлы проекта:
Получение файлов с GitHub
Для загрузки на компьютер файлов, создаем каталог с проектом и переходим в него:
Проводим начальную настройку локального репозитория:
Подключаемся к удаленному репозиторию:
git remote add origin https://github.com/dmosktest/project1.git
Скачиваем проект командой:
git pull https://github.com/dmosktest/project1.git master
Клонирование проекта
Например, использую наш репозиторий:
git clone https://github.com/dmosktest/project1.git
* данная команда создаст в текущей папке каталог project1 и инициализирует его как локальный репозиторий git. Также загрузит файлы проекта.
Возможные ошибки
1. При попытке отправить данные на GitHub, получаем ошибку:
error: src refspec master does not match any.
error: failed to push some refs to ‘https://github.com/dmosktest/project1.git’
* где dmosktest/project1.git — путь к нашему репозиторию.
Причина: проект ни разу не был зафиксирован (закоммичен).
Решение: добавляем комментарий к нашему проекту:
Источник
Git Guides
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 master 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[=
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 master , 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.
Источник
How to Install Git and Clone a GitHub Repository
GitHub is a website that allows collaboration between developers using the Git version control system. With Git and GitHub, programmers from across the world can share ideas and code in an organized and up-to-date process.
Install and Configure Git
The directions below are for Debian or Ubuntu. For installation on Mac, Windows, or other Linux distributions, find instructions in the Git Source Control Management guide. While that guide focuses on Git, this guide focuses more on Git with GitHub.
Configure the username, replace First Last :
Configure the email, replace [email protected] :
Now that Git has been installed, refer to the image below for help with using Git and GitHub together.
Clone a GitHub Test Repository
A repository, or repo, is a Git project. For tutorial purposes, there is a test repository setup on GitHub, which is listed below.
Go to the GitHub homepage. At the top, search for test-repo-789 . If you would like to contribute to Linode’s guides, search for linode docs .
Select test-repo-789 , it should be the first result, listed as NwayNway/test-repo-789 .
Copy the “HTTPS clone URL” link using the clipboard icon at the bottom right of the page’s side-bar, pictured below.
In the Linode terminal from the home directory, use the command git clone , then paste the link from your clipboard, or copy the command and link from below:
Change directories to the new
To ensure that your master branch is up-to-date, use the pull command:
Create a GitHub Account and Fork the Test Repo
To share new files or file revisions, you’ll need a GitHub account and a project fork. A fork is a copy of a repo held on your GitHub account.
Create a username on GitHub. At the “Welcome to GitHub” page, select the green, “Finish sign up” button at the bottom.
Select your username at the top right of the page, pictured below, which links to your profile.
To fork test-repo-789 , use the search bar at the top left of the page. Search for test-repo-789 .
After you select NwayNway/test-repo-789 , fork the repo using the “Fork” button on the top right of the page. The “Fork” button is under the username icon pictured in step 2 above.
You now have a copy of the repo on your GitHub account. Next, return to the terminal of the development Linode.
Push to the Forked Repo
Create files on the development Linode and push them to the forked repository on GitHub.
/test-repo-789 directory, create and checkout a new branch:
Create a project directory:
Create sample files:
Check the status of the Git project, with the git status command:
Add all the files in
/test-repo-789 to the Git staging area:
Check the status again with git status , then commit the files to the Git project:
Push the new files to the forked repo on your new GitHub account. Replace SampleUser1234 below with your own GitHub username, and replace the repo name with the appropriate repo name if different:
Create a Pull Request Against the Original, Previously Cloned Repo
So far, Git was installed on a development Linode, a repo project was cloned to that Linode, a GitHub username was created, and a repo fork was copied to the GitHub user account. The final step is to ask the original repo project to accept the new revisions or sample files. This final process is called a pull request.
From the GitHub browser window, select your username from the top right of the page, pictured below.
At your GitHub profile, select the test-repo-789 in the center of the page, pictured below.
At the test-repo-789 page, select “branches”.
Under “Your branches”, select “New pull request”.
Check that the branch filters are set correctly.
Select the “Create pull request” button.
Congratulations, you have used Git and GitHub for file sharing and version control. There are still many Git commands to learn, but you are off to a great start.
More Information
You may wish to consult the following resources for additional information on this topic. While these are provided in the hope that they will be useful, please note that we cannot vouch for the accuracy or timeliness of externally hosted materials.
This page was originally published on Friday, February 6, 2015.
Источник