git что такое upstream

Удалённые ветки

Удалённые ссылки — это ссылки (указатели) в ваших удалённых репозиториях, включая ветки, теги и так далее. Полный список удалённых ссылок можно получить с помощью команды git ls-remote или команды git remote show для получения удалённых веток и дополнительной информации. Тем не менее, более распространенным способом является использование веток слежения.

Ветки слежения — это ссылки на определённое состояние удалённых веток. Это локальные ветки, которые нельзя перемещать; Git перемещает их автоматически при любой коммуникации с удаленным репозиторием, чтобы гарантировать точное соответствие с ним. Представляйте их как закладки для напоминания о том, где ветки в удалённых репозиториях находились во время последнего подключения к ним.

git что такое upstream. Смотреть фото git что такое upstream. Смотреть картинку git что такое upstream. Картинка про git что такое upstream. Фото git что такое upstream

git что такое upstream. Смотреть фото git что такое upstream. Смотреть картинку git что такое upstream. Картинка про git что такое upstream. Фото git что такое upstream

Для синхронизации ваших изменений с удаленным сервером выполните команду git fetch (в нашем случае git fetch origin ). Эта команда определяет какому серверу соответствует «origin» (в нашем случае это git.ourcompany.com ), извлекает оттуда данные, которых у вас ещё нет, и обновляет локальную базу данных, сдвигая указатель origin/master на новую позицию.

git что такое upstream. Смотреть фото git что такое upstream. Смотреть картинку git что такое upstream. Картинка про git что такое upstream. Фото git что такое upstream

git что такое upstream. Смотреть фото git что такое upstream. Смотреть картинку git что такое upstream. Картинка про git что такое upstream. Фото git что такое upstream

git что такое upstream. Смотреть фото git что такое upstream. Смотреть картинку git что такое upstream. Картинка про git что такое upstream. Фото git что такое upstream

Отправка изменений

Когда вы хотите поделиться веткой, вам необходимо отправить её на удалённый сервер, где у вас есть права на запись. Ваши локальные ветки автоматически не синхронизируются с удалёнными при отправке — вам нужно явно указать те ветки, которые вы хотите отправить. Таким образом, вы можете использовать свои личные ветки для работы, которую не хотите показывать, а отправлять только те тематические ветки, над которыми вы хотите работать с кем-то совместно.

Если вы используете HTTPS URL для отправки изменений, Git-сервер будет спрашивать имя пользователя и пароль для аутентификации. По умолчанию вам будет предложено ввести эти данные в терминале, чтобы сервер мог определить разрешена ли вам отправка изменений.

Для получения более подробной информации о различных вариантах кэша учётных данных обратитесь к разделу Хранилище учётных данных.

В следующий раз, когда один из ваших соавторов будет получать обновления с сервера, он получит ссылку на то, на что указывает serverfix на сервере, как удалённую ветку origin/serverfix :

Отслеживание веток

В действительности, это настолько распространённая команда, что существует сокращение для этого сокращения. Если вы пытаетесь извлечь ветку, которая не существует, но существует только одна удалённая ветка с точно таким же именем, то Git автоматически создаст ветку слежения:

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

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

Получение изменений

Удаление веток на удалённом сервере

Всё, что делает эта строка — удаляет указатель на сервере. Как правило, Git сервер хранит данные пока не запустится сборщик мусора, поэтому если ветка была удалена случайно, чаще всего её легко восстановить.

Источник

Git Forks and Upstreams: How-to and a cool tip

git что такое upstream. Смотреть фото git что такое upstream. Смотреть картинку git что такое upstream. Картинка про git что такое upstream. Фото git что такое upstream

Nicola Paolucci

Forking projects to make your own changes lets you easily integrate your own contributions. But if you’re not sending those changes back upstream—which means sending it back to the parent repository—you’re at risk for losing track of them, which can cause divergent lines in your repository. To make sure all contributors are drawing from the same place, you’ll need to know some principles of how git forking interacts with git upstream. In this blog, I’ll introduce you to the basics, the gotchas, and even leave you with a cool tip to get you ahead of the curve.

Git upstream: Keep up-to-date and contribute

Let me start by detailing a common setup and the most basic workflow to interact with upstream repositories.

In a standard setup, you generally have an origin and an upstream remote — the latter being the gatekeeper of the project or the source of truth to which you wish to contribute.

First, verify that you have already setup a remote for the upstream repository, and hopefully an origin too:

If you don’t have an upstream you can easily add it with the remote command:

Verify that the remote is added correctly:

Generally, you want to keep your local main branch as a close mirror of the upstream main and execute any work in feature branches, as they might later become pull requests.

You can also use rebase instead, then merge to make sure the upstream has a clean set of commits (ideally one) to evaluate:

Publish with git fork

After the above steps, publish your work in your remote fork with a simple push :

A slight problem arises if you have to update your remote branch feature-x after you’ve published it, because of some feedback from the upstream maintainers. You have a few options:

Personally I prefer to keep the history as clean as possible and go for option three, but different teams have different workflows. Note: You should do this only when working with your own fork. Rewriting history of shared repositories and branches is something you should NEVER do.

Tip of the day: Ahead/Behind numbers in the prompt

Here is how it will look on your prompt once you’ve configured it:

Inner workings

For those who like details and explanations here is how it works:

We get the symbolic name for the current HEAD, i.e. the current branch:

We get the remote that the current branch is pointing to:

We get the branch onto which this remote should be merged (with a cheap Unix trick to discard everything up to and including the last forward slash [ / ]):

Now we have what we need to collect the number of counts for the commits we are ahead or behind:

Getting started with git upstream

That is a basic walk-through on git upstream — how to set up a git upstream, create a new branch, collect changes, publish with git fork, and a sweet tip for how many commits ahead/behind you are of your remote branch.

Bitbucket Server includes fork synchronization which basically relieves the developer from all the burden of keeping up to date with its forks, and Bitbucket Cloud has an easy 1-step sync check it out!

Follow me @durdn and the awesome @Bitbucket team for more DVCS rocking.

Источник

Синхронизация в Git

В системе SVN используется единый централизованный репозиторий, служащий центром связи для разработчиков. Совместная работа ведется путем передачи наборов изменений между рабочими копиями разработчиков и центральным репозиторием. Однако модель распределенной совместной работы в Git предполагает, что каждый разработчик использует собственную копию репозитория со своей локальной историей и структурой веток. Обычно пользователи делятся не отдельными наборами изменений, а сериями коммитов. Вместо того чтобы выполнять коммит одного набора изменений из рабочей копии в центральный репозиторий, Git позволяет передавать между репозиториями целые ветки.

git remote

Команда git remote позволяет создавать, просматривать и удалять подключения к другим репозиториям. Удаленные подключения скорее похожи на закладки, чем на прямые ссылки на другие репозитории. Они служат удобными именами, с помощью которых можно сослаться на не очень удобный URL-адрес, а не предоставляют доступ к другому репозиторию в режиме реального времени.

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

git что такое upstream. Смотреть фото git что такое upstream. Смотреть картинку git что такое upstream. Картинка про git что такое upstream. Фото git что такое upstream

Обзор использования git remote

По сути, команда git remote — это интерфейс для управления списком записей об удаленных подключениях, которые хранятся в файле /.git/config репозитория. Для просмотра текущего состояния списка удаленных подключений используются следующие команды.

Просмотр конфигураций удаленных репозиториев Git

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

Аналогично команде выше, но включает URL-адрес каждого подключения.

Создание и изменение конфигураций удаленных репозиториев Git

Команда git remote также предоставляет удобный способ изменения файла /.git/config репозитория. Перечисленные ниже команды позволяют управлять подключениями к другим репозиториям и изменять файл /.git/config репозитория. Такого же результата можно достичь, напрямую отредактировав файл /.git/config с помощью текстового редактора.

Создание нового подключения к удаленному репозиторию. После добавления удаленного репозитория имя <name> можно использовать в качестве удобного ярлыка для адреса <url> в других командах Git.

Обсуждение git remote

Git предоставляет каждому разработчику полностью изолированную среду разработки. Информация не передается между репозиториями автоматически. Вместо этого разработчикам нужно вручную загружать вышестоящие коммиты в локальный репозиторий или вручную отправлять локальные коммиты обратно в центральный репозиторий. Команда git remote представляет собой простой способ передачи URL-адресов в эти команды обмена.

Удаленное подключение к origin

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

URL-адреса репозиториев

Git поддерживает различные способы ссылки на удаленный репозиторий. Два наиболее простых способа доступа к удаленному репозиторию: протоколы HTTP и SSH. Протокол HTTP — простой способ разрешить к репозиторию анонимный доступ только для чтения. Пример ниже.

Однако HTTP-адрес, как правило, не позволяет отправлять коммиты (в любом случае вы не захотите разрешать анонимную отправку изменений с помощью команды push). Чтобы использовать доступ для чтения и записи следует использовать протокол SSH:

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

Команды git remote

Вывод URL-адресов для записи об удаленном репозитории.

Удаляет из репозитория <NAME> все локальные ветки, которые отсутствуют в удаленном репозитории.

Примеры git remote

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

Просмотр удаленных репозиториев

По умолчанию команда git remote отображает ранее сохраненные удаленные подключения к другим репозиториям. Создается однострочный список закладок с именами удаленных репозиториев.

Добавление удаленных репозиториев

Проверка удаленного репозитория

Для получения подробного вывода о конфигурации удаленного репозитория к команде git remote можно добавить подкоманду show. Вывод будет содержать список веток, связанных с удаленным репозиторием, а также конечных точек, подключенных для извлечения (fetch) и отправки (push).

Получение и извлечение данных из удаленных репозиториев Git

Отправка данных в удаленные репозитории Git

Переименование и удаление удаленных репозиториев

Источник

Definition of «downstream» and «upstream»

I’ve started playing with Git and have come across the terms «upstream» and «downstream». I’ve seen these before but never understood them fully. What do these terms mean in the context of SCMs (Software Configuration Management tools) and source code?

git что такое upstream. Смотреть фото git что такое upstream. Смотреть картинку git что такое upstream. Картинка про git что такое upstream. Фото git что такое upstream

6 Answers 6

In terms of source control, you’re «downstream» when you copy (clone, checkout, etc) from a repository. Information flowed «downstream» to you.

When you make changes, you usually want to send them back «upstream» so they make it into that repository so that everyone pulling from the same source is working with all the same changes. This is mostly a social issue of how everyone can coordinate their work rather than a technical requirement of source control. You want to get your changes into the main project so you’re not tracking divergent lines of development.

Sometimes you’ll read about package or release managers (the people, not the tool) talking about submitting changes to «upstream». That usually means they had to adjust the original sources so they could create a package for their system. They don’t want to keep making those changes, so if they send them «upstream» to the original source, they shouldn’t have to deal with the same issue in the next release.

One important aspect of git is it is distributed, and being distributed largely means there is no inherent «upstream» or «downstream» in the system.

, that simply means there is no absolute upstream repo or downstream repo.
Those notions are always relative between two repos and depends on the way data flows:

If «yourRepo» has declared «otherRepo» as a remote one, then:

Note the «from» and «for»: you are not just «downstream», you are «downstream from/for«, hence the relative aspect.

The DVCS (Distributed Version Control System) twist is: you have no idea what downstream actually is, beside your own repo relative to the remote repos you have declared.

In term of «flow of data«, your repo is at the bottom («downstream») of a flow coming from upstream repos («pull from») and going back to (the same or other) upstream repos («push to»).

You can see an illustration in the git-rebase man page with the paragraph «RECOVERING FROM UPSTREAM REBASE»:

It means you are pulling from an «upstream» repo where a rebase took place, and you (the «downstream» repo) is stuck with the consequence (lots of duplicate commits, because the branch rebased upstream recreated the commits of the same branch you have locally).

That is bad because for one «upstream» repo, there can be many downstream repos (i.e. repos pulling from the upstream one, with the rebased branch), all of them having potentially to deal with the duplicate commits.

Again, with the «flow of data» analogy, in a DVCS, one bad command «upstream» can have a «ripple effect» downstream.

Note: this is not limited to data.
It also applies to parameters, as git commands (like the «porcelain» ones) often call internally other git commands (the «plumbing» ones). See rev-parse man page:

git что такое upstream. Смотреть фото git что такое upstream. Смотреть картинку git что такое upstream. Картинка про git что такое upstream. Фото git что такое upstream

Upstream (as related to) Tracking

The term upstream also has some unambiguous meaning as comes to the suite of GIT tools, especially relative to tracking

will print (the last cached value of) the number of commits behind (left) and ahead (right) of your current working branch, relative to the (if any) currently tracking remote branch for this local branch. It will print an error message otherwise:

it is ‘the branch’ (if any) on ‘said remote’, which is tracking the ‘current branch’ on your ‘local repository’.

Let’s say want to set the remote branch origin/master to be the tracking branch for the local master branch you’ve checked out. Just issue :

now try (provided ‘upstream’ remote has a ‘dev’ branch)

.git/config now reads:

Upstream and Push (Gotcha)

This is to prevent accidental pushes to branches which you’re not ready to push yet.

That’s a bit of informal terminology.

As far as Git is concerned, every other repository is just a remote.

Generally speaking, upstream is where you cloned from (the origin). Downstream is any project that integrates your work with other works.

The terms are not restricted to Git repositories.

For instance, Ubuntu is a Debian derivative, so Debian is upstream for Ubuntu.

Upstream Called Harmful

There is, alas, another use of «upstream» that the other answers here are not getting at, namely to refer to the parent-child relationship of commits within a repo. Scott Chacon in the Pro Git book is particularly prone to this, and the results are unfortunate. Do not imitate this way of speaking.

For example, he says of a merge resulting a fast-forward that this happens because

the commit pointed to by the branch you merged in was directly upstream of the commit you’re on

Indeed, Chacon himself appears to use «downstream» later to mean exactly the same thing, when he speaks of rewriting all child commits of a deleted commit:

You must rewrite all the commits downstream from 6df76 to fully remove this file from your Git history

Basically he seems not to have any clear idea what he means by «upstream» and «downstream» when referring to the history of commits over time. This use is informal, then, and not to be encouraged, as it is just confusing.

It is perfectly clear that every commit (except one) has at least one parent, and that parents of parents are thus ancestors; and in the other direction, commits have children and descendants. That’s accepted terminology, and describes the directionality of the graph unambiguously, so that’s the way to talk when you want to describe how commits relate to one another within the graph geometry of a repo. Do not use «upstream» or «downstream» loosely in this situation.

[Additional note: I’ve been thinking about the relationship between the first Chacon sentence I cite above and the git-merge man page, and it occurs to me that the former may be based on a misunderstanding of the latter. The man page does go on to describe a situation where the use of «upstream» is legitimate: fast-forwarding often happens when «you are tracking an upstream repository, you have committed no local changes, and now you want to update to a newer upstream revision.» So perhaps Chacon used «upstream» because he saw it here in the man page. But in the man page there is a remote repository; there is no remote repository in Chacon’s cited example of fast-forwarding, just a couple of locally created branches.]

Источник

How To Set Upstream Branch on Git

git что такое upstream. Смотреть фото git что такое upstream. Смотреть картинку git что такое upstream. Картинка про git что такое upstream. Фото git что такое upstream

When cloning a Git repository or creating new feature branches, you will have to set upstream branches in order to work properly.

But what are upstream branches?

Upstream branches are closely associated with remote branches.

Upstream branches define the branch tracked on the remote repository by your local remote branch (also called the remote tracking branch)

git что такое upstream. Смотреть фото git что такое upstream. Смотреть картинку git что такое upstream. Картинка про git что такое upstream. Фото git что такое upstream

When creating a new branch, or when working with existing branches, it can be quite useful to know how you can set upstream branches on Git.

Set upstream branch using git push

The easiest way to set the upstream branch is to use the “git push” command with the “-u” option for upstream branch.

Alternatively, you can use the “–set-upstream” option that is equivalent to the “-u” option.

As an example, let’s say that you created a branch named “branch” using the checkout command.

You can check tracking branches by running the “git branch” command with the “-vv” option.

As you can see, compared to master, the branch “branch” has no tracking branches yet (and no upstream branches as a consequence)

We can set the upstream branch using the “git push” command.

Let’s have a look at the tracking branches again with the branch command.

We have successfully set the upstream branch for our newly created branch.

Set upstream branch using an alias

Another way to set the upstream branch is to define an alias for your “git push” command.

In fact, pushing to HEAD is equivalent to pushing to a remote branch having the same name as your current branch.

In order to avoid having to define the upstream everytime you create a new branch, define an alias for the command we just wrote.

For aliases, you have two choices, you can either create a git alias or a bash alias.

Using a git alias

In order to create a new git alias, use the “git config” command and define a new alias named “pushd”

When you are done adding and committing fiels to your repository, set the upstream branch using your newly defined alias.

Using a bash alias

Alternatively, you can use a bash alias if you don’t want to modify your existing git commands.

Define a new bash alias using the “alias” command and define a name for it.

Let’s create a new branch and use our alias in order to push our code and create the upstream branch easily.

Set upstream branch for an existing remote branch

In some cases, you may choose to link your local branches to existing remote branches that you just pulled or cloned from the main repository.

Let’s say for example that you pulled the “dev” branch located on the “origin” remote.

As a consequence, the tracking branch is named “origin/dev”.

Set tracking branches for new local branches

In order to switch to the local “dev” branch, and to set the “origin/dev” as the tracking branch (or upstream branch), use the “–track” option.

To verify that you linked dev to the tracking branch “origin/dev” (which upstream branch is the remote dev), use the “git branch” command.

Set tracking branches for existing local branches

On the other hand, you may have chosen to work on a local branch and to set the upstream branch (or the remote tracking branch later on).

It is perfectly fine, but you will have to use the “git branch” in order to set the existing branch upstream branch.

Let’s take the example of the “feature” branch that you just created to start working.

You created some commits in your branch, you want to set the tracking branch to be master.

Great! You successfully set the upstream branch for your existing local branch.

Why are upstream branches so useful in Git?

Upstream branches are useful because :

When performing a “git fetch” command, you can bring the new commits from your remote repository and you can choose to merge them at will.

When you set your upstream (or tracking) branches, you can simply execute pulls and pushes without having to specify the target branch.

Git automatically knows that it has to fetch the new commits to the remote tracking branch. Similarly, Git already knows that it has to push new commits to the upstream branch.

But where does Git keep a reference of the upstream branches associated with local branches?

Git keeps references to upstream branches via its config file in the “.git” directory.

Inspecting tracking branches configuration

In order to inspect your current Git configuration, list the hidden files and directories in your current working Git directory.

As you can see, Git keeps a reference between your local branch, the name of the remote and the branch it has to merge with.

Conclusion

In this tutorial, you learnt more about upstream branches and how they are related to remote tracking branches in Git.

You learnt different techniques in order to set remote tracking branches using a command or an alias to set it.

You also learnt how you can link your current local branches to existing remote tracking branches easily with the branch command.

If you are interested in Software Engineering, we have a complete section dedicated to it on the website so make sure to have a look.

Источник

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

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