Как пушить в гитлаб
Перейти к содержимому

Как пушить в гитлаб

  • автор:

Git для начинающих. Урок 6.
git push и git pull

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

Во втором уроке мы создавали репозитории на github и научились клонировать их. После этого мы работали только с локальным репозиторием, на своей машине. Сегодня мы рассмотрим взаимодействие с удаленным репозиторием.

Что такое push (пуш)

Это отправка данных на сервер, в удаленный репозиторий, на github. Данные — это коммиты и ветки.

Зачем пушить на сервер

  • для работы в команде, чтобы делиться своим кодом с коллегами
  • чтобы иметь резервную копию на случай потери данных на своей машине

Когда пушить на сервер

Когда сделали новый коммит или несколько коммитов

Как узнать, что есть незапушенные коммиты

В командной строке набрать git status

Ключевая фраза здесь «Your branch is ahead of ‘origin/master’ by 5 commits.». Это значит, что у нас есть 5 неотправленных на сервер коммитов. Если незапушенных коммитов нет, то картина будет такая

«is up-to-date» означает, что у нас нет незапушенных коммитов

В PhpStorm понять, есть ли неотправленные коммиты, можно посмотрев в окно Version Control — Log, где находятся метка master и origin/master. Если master выше, то есть незапушенные коммиты.

master и origin/master

Это ветки: локальная и удаленная (на сервере, в github). По умолчанию мы находимся в ветке master. Подробно работу с ветками мы рассмотрим в следующем уроке, а пока достаточно запомнить, что master — это то, что на нашей машине, а origin/master — в удаленном репозитории, на github.

git push в терминале

  • push — что сделать, отправить
  • origin — куда, на сервер
  • master — что, ветку master

Как пушить в PhpStorm

Правый клик — Git — Repository — Push. — Кнопка Push

Что такое pull (пулл)

Это скачивание данных с сервера. Похоже на клонирование репозитория, но с той разницей, что скачиваются не все коммиты, а только новые.

Зачем пулиться с сервера

Чтобы получать изменения от ваших коллег. Или от себя самого, если работаете на разных машинах

git pull в терминале

  • pull — что сделать, получить данные
  • origin — откуда, с сервера
  • master — а точнее, с ветки master

Как пулить в PhpStorm

Правый клик — Git — Repository — Pull. — Кнопка Pull

Когда что-то пошло не так.

Иногда при работе в команде git push и git pull могут вести себя не так, как пишут в учебниках. Рассмотрим примеры

git push rejected

Вы сделали новый коммит, пытаетесь запушить его, а git в ответ выдает такое

Написано много, но суть в том, что коммит отклонен, пуш не прошел. Почему?

Git устроен так, что локально мы можем коммитить сколько угодно. Но прежде чем отправить свои коммиты на сервер, то есть запушить, нужно подтянуть новые коммиты с сервера. Те самые, которые успели сделать наши коллеги. То есть сделать git pull.

Когда мы делаем git push, git сначала проверяет, а нет ли на сервере новых коммитов. Если они есть, то git выдает то самое сообщение — git push rejected. Значит, нам нужно сначала сделать git pull, а затем снова запушить

Здесь нас подстерегает неожиданность — в терминале выскакивает окно редактирования коммита. Пока просто сохраним, что предложено по умолчанию и закроем редактор. Вот теперь можно пушить свои коммиты

Все, наши коммиты на сервере. При этом появится странный коммит «Merge branch ‘master’ of github.com:Webdevkin/site-git». Это так называемый мердж-коммит, о нем чуть ниже.

Если же при попытке пуша новых коммитов на сервере нет, то git push пройдет сразу и отправит наши коммиты на сервер.

Как избавиться от мердж-коммита

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

Чтобы избавиться от него, подтягивайте изменения командой git pull с флажком —rebase

При этом ваш локальный коммит окажется «поверх» нового коммита с сервера, а мердж-коммита не будет. И не забудьте после этого запушить свой коммит на сервер.

Мердж-коммит в PhpStorm

PhpStorm помогает избавиться от мердж-коммитов через меньшее количество действий. Если мы запушим локальные коммиты и получим rejected из-за того, что на сервере есть новые коммиты, то PhpStorm выдаст предупреждение, где предложит выбрать вариант: как подтянуть новые коммиты, с мерждем или ребейзом. Жмите кнопку «Rebase», мердж-коммита не будет и при этом локальный коммит сразу запушится на сервер.

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

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

Но при работе в команде имеет смысл подумать над такими вещами:

  • пушить коммиты почаще, чтобы коллеги быстрее получали доступ к новым изменениям
  • пулиться почаще — обратная ситуация, почаще получать свежие изменения
  • всегда пультесь с флажком ребейза — git pull —rebase origin master
  • не удивляйтесь, что при пуллах и пушах могут возникать подобные ситуации, как мы рассматривали выше
  • не стесняйтесь спрашивать коллег, если увидели незнакомую ситуацию
  • больше практикуйтесь. Посадите домашний проект на git и работайте с ним

Не переживайте, если иногда будете чувствовать себя, как друзья ниже. Это нормально, новый инструмент не осваивается за 5 минут. Немного практики, и мы будем понимать, почему иногда git ведет себя не так, как хочется, и главное, будем понимать, как это исправить.

git push pull whaaat

В следующем уроке мы узнаем, что такое ветки и будем активно работать с ними. Там мы будем активно использовать git push и git pull, и это поможет закрепить уже пройденный материал.

Как пользоваться GitLab

GitLab — это онлайн сервис для работы с git репозиториями, у которого есть Open Source версия, которую можно установить и развернуть на своем сервере. Разработчики позиционируют свой сервис как альтернативу GitHub и с этой задачей он полностью справляется. Здесь есть все то же самое, что и на GitHub, плюс бесплатные неограниченные частные репозитории, создание команд, редактирование кода прямо в браузере и многое другое.

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

Как пользоваться GitLab

1. Создание аккаунта

Зарегистрироваться на GitLab очень просто. Откройте главную страницу GitLab найдите в правой части экрана форму входа и перейдите на вкладку Register. Здесь вам нужно ввести ваше имя, логин, адрес электронной почты, согласится с условиями использования и нажать кнопку Register:

После этого вам на почту придет сообщение со ссылкой для подтверждения аккаунта, перейдите по ней:

Теперь ваш аккаунт подтвержден и вы можете в нём авторизоваться:

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

2. Создание репозитория

Чтобы добавить проект GitLab кликните по значку + по центру верхней панели и выберите New Project:

Здесь вам нужно ввести имя репозитория, его описание, а также выбрать уровень доступа:

  • Private — доступен только вам;
  • Internal — доступен всем зарегистрированным пользователям;
  • Public — доступен абсолютно всем.

Ещё вы можете установить галочку напротив Инициализировать репозиторий файлом README, но если вы хотите залить сюда файлы из уже существующего репозитория, делать этого не следует:

После нажатия на кнопку Create repo вы попадаете на страницу репозитория. Здесь GitLab уже предлагает первоначальный набор действий, чтобы проиниализировать ваш репозиторий. Например, вы можете создать здесь файлы или загрузить сюда файлы из вашего компьютера.

4. Загрузка файлов проекта

Давайте создадим новый локальный репозиторий на компьютере и загрузим его содержимое на GitLab. Для этого создайте папку репозитория, например, test-repo и инициализируйте в ней новый репозиторий командой git:

mkdir test-repo && cd test-repo

Затем давайте создадим файл test.txt:

This is test losst repo

И зафиксируем изменения:

git add test.txt git commit -m «Inital commit»

Дальше нам нужно добавить наш удаленный репозиторий с GitLab к нашему локальному. Для этого выполните:

git remote add origin https://gitlab.com/losst/test-repo.git

Затем отправляем изменения в удаленный репозиторий:

git push origin master

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

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

5. SSH ключи

Во время загрузки данных репозитория на GitLab нам нужно было ввести логин и пароль на сервере. Чтобы этого избежать можно использовать SSH ключи для авторизации. Сначала вам нужно создать такой ключ. Для этого откройте терминал и выполните:

Введите путь к файлу, куда нужно сохранить ключ, а пароль оставьте пустым. Будут созданы два файла — открытый ключ с расширением .pub и закрытый. Вам нужен открытый. Откройте его в текстовом редакторе и скопируйте его содержимое в буфер обмена:

Далее возвращайтесь к интерфейсу GitLab кликните по иконке профиля и выберите Settings:

Здесь на левой панели найдите пункт SSH Keys. В этом окне найдите поле Key и вставьте туда скопированный ключ. Далее сохраните изменения. Теперь ваш ключ добавлен:

Далее вернитесь в ваш репозиторий, найдите в правом верхнем углу кнопку Clone и кликните по ней. Нас интересует адрес Clone with SSH:

Возвращаемся к нашему локальному репозиторию, удаляем адрес https и добавляем ssh:

git remote remove origin git remote add origin git@gitlab.com:losst/test-repo.git

Настройка ssh GitLab завершена. Теперь все действия будут выполняться по SSH и у вас не будет необходимости вводить логин и пароль.

6. Ветки репозитория

Разберем использование gitlab для работы с ветками. По умолчанию у репозитория есть только одна ветка — это master. Но для реализации дополнительных функций разработку можно выносить в отдельные ветки. В интерфейсе GitLab ветки отображаются слева. Здесь можно выбрать нужную ветку:

Создать новую ветку можно кликнув по значку плюс и выбрав New branch. Но это не обязательно, так как если вы создадите ветку в git и зальете изменения в репозиторий, то ветка появится там автоматически.

Чтобы изменить ветку по умолчанию откройте Settings -> Repository, а потом просто выберите нужную ветку в разделе Default branch:

6. Слияние веток

Поскольку у нас есть ветки и в них разрабатывается функциональность может возникнуть необходимость перенести её из одной ветки в другую. Для этого используются запросы слияния (Merge request gitlab). Давайте добавим ветку new-feature, а в ней создадим файл new-feature с текстом:

git checkout -b new-feature

New feature with change

git add new-feature.txt git commit -m «add feature» git push —set-upstream origin new-feature

Теперь, когда мы перейдем в новую ветку через интерфейс GitLab появится кнопка Create merge request. Нажмите на неё:

Здесь нужно написать описание Merge Request, который вы создаете, выбрать ветку источник и ветку цель. Также можно выбрать пользователя, которому будет оправлено уведомление о созданном запросе:

Далее запрос на слияние нужно одобрить. Вы можете посмотреть изменения нажав кнопку Open IDE или через терминал:

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

8. Добавление пользователей

Несмотря на то, что репозитории приватные, возможна работа с gitlab командой. Вы можете добавить к ним неограниченное количество разработчиков. Для этого откройте пункт Settings -> Members. Здесь в поле Select members to invite введите никнеймы или адреса электронной почты пользователей, которых надо пригласить, а в поле Choose a role permission выберите их уровень доступа:

Затем нажмите кнопку Add to project.

9. Удаление проекта

Чтобы удалить проект с Gitlab надо открыть Settings -> General -> Advanced и выбрать Remove Project в самом низу страницы:

После нажатия на кнопку вам нужно будет ввести имя проекта, после чего он будет удален:

Выводы

В этой статье мы кратко разобрали как пользоваться GitLab для разработки программного обеспечения. Это далеко не все возможности GitLab, которые заслуживают внимания, там ещё есть релизы, сообщения об ошибках, инструменты автоматизации и тестирования, удобный редактор кода и многое другое. В общем это полноценная альтернатива для GitHub если тот сервис больше вам не нравится. А что вы предпочитаете, GitHub или GitLab? Напишите в комментариях!

Name already in use

gitlabhq / doc / gitlab-basics / start-using-git.md

  • Go to file T
  • Go to line L
  • Copy path
  • Copy permalink
  • Open with Desktop
  • View raw
  • Copy raw contents Copy raw contents

Copy raw contents

Copy raw contents

Command line Git (FREE)

Git is an open-source distributed version control system. GitLab is built on top of Git.

You can do many Git operations directly in GitLab. However, the command line is required for advanced tasks, like fixing complex merge conflicts or rolling back commits.

If you’re new to Git and want to learn by working in your own project, learn how to make your first commit.

For a quick reference of Git commands, download a Git Cheat Sheet.

For more information about the advantages of working with Git and GitLab:

  • Watch the GitLab Source Code Management Walkthrough video.
  • Learn how GitLab became the backbone of the Worldline development environment.

To help you visualize what you’re doing locally, you can install a Git GUI app.

Choose a terminal

To execute Git commands on your computer, you must open a terminal (also known as command prompt, command shell, and command line). Here are some options:

  • For macOS users:
    • Built-in Terminal. Press ⌘ command + space and type terminal . . You can integrate it with Zsh and Oh My Zsh for color highlighting and other advanced features.
    • Built-in command line. On the Windows taskbar, select the search icon and type cmd . .
    • Git Bash. It is built into Git for Windows.
    • Built-in Linux Terminal.

    Confirm Git is installed

    You can determine if Git is already installed on your computer by opening a terminal and running this command:

    If Git is installed, the output is:

    If your computer doesn’t recognize git as a command, you must install Git.

    To start using Git from your computer, you must enter your credentials to identify yourself as the author of your work. The username and email address should match the ones you use in GitLab.

    In your shell, add your user name:

    Add your email address:

    To check the configuration, run:

    The —global option tells Git to always use this information for anything you do on your system. If you omit —global or use —local , the configuration applies only to the current repository.

    You can read more on how Git manages configurations in the Git configuration documentation.

    Choose a repository

    Before you begin, choose the repository you want to work in. You can use any project you have permission to access on GitLab.com or any other GitLab instance.

    To use the repository in the examples on this page:

    1. Go to https://gitlab.com/gitlab-tests/sample-project/.
    2. In the upper-right corner, select Fork.
    3. Choose a namespace for your fork.

    The project becomes available at https://gitlab.com/<your-namespace>/sample-project/ .

    You can fork any project you have access to.

    Clone a repository

    When you clone a repository, the files from the remote repository are downloaded to your computer, and a connection is created.

    This connection requires you to add credentials. You can either use SSH or HTTPS. SSH is recommended.

    Clone with SSH when you want to authenticate only one time.

    Authenticate with GitLab by following the instructions in the SSH documentation.

    Go to your project’s landing page and select Clone. Copy the URL for Clone with SSH.

    Open a terminal and go to the directory where you want to clone the files. Git automatically creates a folder with the repository name and downloads the files there.

    Run this command:

    To view the files, go to the new directory:

    Clone with HTTPS

    Clone with HTTPS when you want to authenticate each time you perform an operation between your computer and GitLab.

    Go to your project’s landing page and select Clone. Copy the URL for Clone with HTTPS.

    Open a terminal and go to the directory where you want to clone the files.

    Run the following command. Git automatically creates a folder with the repository name and downloads the files there.

    GitLab requests your username and password.

    If you have enabled two-factor authentication (2FA) on your account, you cannot use your account password. Instead, you can do one of the following:

      with read_repository or write_repository permissions.
    • Install Git Credential Manager.

    If you have not enabled 2FA, use your account password.

    To view the files, go to the new directory:

    NOTE: On Windows, if you enter your password incorrectly multiple times and an Access denied message appears, add your namespace (username or group) to the path: git clone https://namespace@gitlab.com/gitlab-org/gitlab.git .

    Clone using a token

    Clone with HTTPS using a token if:

    • You want to use 2FA.
    • You want to have a revocable set of credentials scoped to one or more repositories.

    You can use any of these tokens to authenticate when cloning over HTTPS:

    Convert a local directory into a repository

    You can initialize a local folder so Git tracks it as a repository.

    Open the terminal in the directory you’d like to convert.

    Run this command:

    A .git folder is created in your directory. This folder contains Git records and configuration files. You should not edit these files directly.

    Add the path to your remote repository so Git can upload your files into the correct project.

    You add a «remote» to tell Git which remote repository in GitLab is tied to the specific local folder on your computer. The remote tells Git where to push or pull from.

    To add a remote to your local copy:

    In GitLab, create a project to hold your files.

    Visit this project’s homepage, scroll down to Push an existing folder, and copy the command that starts with git remote add .

    On your computer, open the terminal in the directory you’ve initialized, paste the command you copied, and press enter :

    View your remote repositories

    To view your remote repositories, type:

    The -v flag stands for verbose.

    Download the latest changes in the project

    To work on an up-to-date copy of the project, you pull to get all the changes made by users since the last time you cloned or pulled the project. Replace <name-of-branch> with the name of your default branch to get the main branch code, or replace it with the branch name of the branch you are currently working in.

    When you clone a repository, REMOTE is typically origin . This is where the repository was cloned from, and it indicates the SSH or HTTPS URL of the repository on the remote server. <name-of-branch> is usually the name of your default branch, but it may be any existing branch. You can create additional named remotes and branches as necessary.

    You can learn more on how Git manages remote repositories in the Git Remote documentation.

    A branch is a copy of the files in the repository at the time you create the branch. You can work in your branch without affecting other branches. When you’re ready to add your changes to the main codebase, you can merge your branch into the default branch, for example, main .

    Use branches when you:

    • Want to add code to a project but you’re not sure if it works properly.
    • Are collaborating on the project with others, and don’t want your work to get mixed up.

    A new branch is often called feature branch to differentiate from the default branch.

    Create a branch

    To create a feature branch:

    Branch names cannot contain empty spaces and special characters. Use only lowercase letters, numbers, hyphens ( — ), and underscores ( _ ).

    Switch to a branch

    All work in Git is done in a branch. You can switch between branches to see the state of the files and work in that branch.

    To switch to an existing branch:

    For example, to change to the main branch:

    To view the differences between your local unstaged changes and the latest version that you cloned or pulled:

    View the files that have changes

    When you add, change, or delete files or folders, Git knows about the changes. To check which files have been changed:

    Add and commit local changes

    When you type git status , locally changed files are shown in red. These changes may be new, modified, or deleted files or folders.

    To stage a file for commit:

    Repeat step 1 for each file or folder you want to add. Or, to stage all files in the current directory and subdirectory, type git add . .

    Confirm that the files have been added to staging:

    The files should be displayed in green text.

    To commit the staged files:

    Stage and commit all changes

    As a shortcut, you can add all local changes to staging and commit them with one command:

    Send changes to GitLab.com

    To push all local changes to the remote repository:

    For example, to push your local commits to the main branch of the origin remote:

    Sometimes Git does not allow you to push to a repository. Instead, you must force an update.

    Delete all changes in the branch

    To discard all changes to tracked files:

    This action removes changes to files, not the files themselves. Untracked (new) files do not change.

    Unstage all changes that have been added to the staging area

    To unstage (remove) all files that have not been committed:

    Undo most recent commit

    To undo the most recent commit:

    This action leaves the changed files and folders unstaged in your local repository.

    WARNING: A Git commit should not be reversed if you already pushed it to the remote repository. Although you can undo a commit, the best option is to avoid the situation altogether by working carefully.

    You can learn more about the different ways Git can undo changes in the Git Undoing Things documentation.

    Merge a branch with default branch

    When you are ready to add your changes to the default branch, you merge the feature branch into it:

    In GitLab, you typically use a merge request to merge your changes, instead of using the command line.

    To create a merge request from a fork to an upstream repository, see the forking workflow.

    Advanced use of Git through the command line

    For an introduction of more advanced Git techniques, see Git rebase, force-push, and merge conflicts.

    Synchronize changes in a forked repository with the upstream

    To create a copy of a repository in your namespace, you fork it. Changes made to your copy of the repository are not automatically synchronized with the original. To keep the project in sync with the original project, you need to pull from the original repository.

    You must create a link to the remote repository to pull changes from the original repository. It is common to call this remote repository the upstream .

    You can now use the upstream as a <remote> to pull new updates from the original repository, and use the origin to push local changes and create merge requests.

    Как пушить в гитлаб

    git push pull whaaat

    Git push в удаленный репозиторий или как залить локальную ветку в origin

    Как запушить локальную ветку git в origin

    How to Push to GitLab

    how-to-push-to-gitlab primary img

    To get started with GitLab, you’ll need to create a repository and push code to it. Here’s how to push to GitLab.

    How to Create a Project (Repository) in GitLab

    Because of their larger potential in GitLab, repositories are called projects. But you can use the words interchangeably because a project behaves the same way as a repository you might find on GitHub.

    After creating your account in GitLab, go to your Projects page and click New project.

    From the Blank project tab, give the project a name and add a description. If you want it to be a public repository, click the Public option. Make sure the Initialize repository with README option is left unchecked. Then click the Create project button.

    How to Push to GitLab

    Once a new project is created, it will be blank by default. There are a couple of ways to populate it. You can directly add files online using the Add Files button.

    But if you’re going to be using GitLab as an online versioning tool, it’s best to upload your local project files using the command line. To get started, first install and set up Git on your Linux, Mac, or Windows PC.

    Then, open the Terminal (Git Bash on Windows) and navigate to the local folder that you want to sync with your GitLab project. Use the cd command to switch to the folder in question.

    Now you can start the Git process with this command:

    Now you’ll connect the remote GitLab project with your local directory. Use the following command, pasting in your GitLab project URL at the end (make sure it ends in .git ).

    git remote add origin <project link>

    After you press Enter or Return , you won’t see any confirmation. That’s because you haven’t added or transferred the files to the Git process yet. To add all the files from the current directory to the Git process, use the following command.

    Then you can check if all files were added correctly using the following command.

    Now you’ll make a commit, so you know which files were included when the local directory was first uploaded to the GitLab project. You can add your comment between the quotes at the end of the next command. It can include what changes you made recently to the code and if you added any new files.

    git commit -m «first commit»

    Now you’re ready to actually push the files and code to GitLab. Enter the following command.

    git push -u origin master

    After you press Enter or Return , you’ll be asked to enter your GitLab username and password. Since you’ve created a private repository, this step makes sure that only the project owner can make changes to the repository.

    Once the authentication is done, the upload process will begin. And shortly, you’ll see a message saying that the upload is finished.

    To check whether all the data was uploaded properly, you can open the project in your browser. Instead of the blank page, you’ll now see a list of all the files and folders in the project.

    Automate GitLab with Zapier

    Zapier lets you connect GitLab to thousands of apps, so you can automate more of your Git processes.

    For example, you could automatically get a notification or create a task in your project management tool whenever there’s a new merge request in your repo.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *