Что такое upstream git

What Is Git Upstream And How To Set Upstream Branch

Home » SysAdmin » What Is Git Upstream And How To Set Upstream Branch

When you clone a Git repository or create new features through branches, you need know how upstream branches work and how to set them up.

This article gives an overview of how to set up a Git upstream branch, how to change it and how to have an overview of which Git branch is tracking which upstream branch.

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

Note: To install Git, check out our tutorials:

What is a Git Upstream Branch?

Using a river analogy to illustrate the flow of data, upstream is sending your data back to where the river stream is coming from. When you send something upstream, you are sending it back to the original authors of the repository.

How to Set Upstream Branch in Git

There are two ways to set an upstream branch in Git:

Method 1: Set Upstream Branch Using Git Push

Using git push to set an upstream branch is the most straightforward way to set upstream branches in Git.

Note: Forgot how to clone a repository? Freshen up your memory with our Git Commands Cheat Sheet.

1. Create a new branch and give it a name. We named ours test. Switch to it using the checkout command with the -b option:

A switch branch confirmation appears:

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

Note: From this point on, the active branch is listed as (
)
instead of (main). In our case, it’s (test).

You get confirmation that your branch has been set up to track a remote branch:

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

The test branch now has a set upstream branch.

Method 2: Set Upstream Branch Using Alias

Instead of going through these commands every time you create a new branch, set up a short alias command. You can modify your existing Git commands or create a bash command.

1. Configure the global alias command through git config with the —global command:

Or create a bash alias command using alias :

Note: Pushing to HEAD will push to a remote branch with the same name as your current branch.

2. Run your global alias by typing:

Or your bash alias by typing its name:

How to Change Upstream Branch in Git

Track a different upstream branch than the one you just set up by running:

The terminal prints out a confirmation message:

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

How to Check Which Git Branches Are Tracking Which Upstream Branch

List all your branches and branch tracking by running git branch with the -vv option:

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

The main branch has a tracking branch of [origin/main]. The test branch has a tracking branch of [origin/global]. The global branch has no tracking branches, and therefore no upstream branch.

Note: The current active branch is denoted by the asterisk (*) sign.

You should now know what upstream branches are, how they work, and most importantly, how to set an upstream branch in Git.

Feel free to experiment and get comfortable with upstream. You can easily delete a git branch remotely and locally and remove a git remote from a repository.

Источник

Определение «downstream» и «upstream»

Я начал играть с Git и столкнулся с терминами «upstream» и «downstream». Я видел это раньше, но никогда не понимал их полностью. Что означают эти термины в контексте SCM (инструменты управления конфигурацией программного обеспечения) и исходного кода?

ОТВЕТЫ

Ответ 1

С точки зрения контроля источника, вы » вниз по течению» при копировании (клонирование, проверка и т.д.) из репозитория. Информация передавалась вам «вниз по течению».

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

Иногда вы будете читать о менеджерах пакетов или выпусков (люди, а не инструмент), говорящие о внесении изменений в «вверх по течению». Обычно это означает, что они должны были корректировать исходные источники, чтобы они могли создать пакет для своей системы. Они не хотят продолжать делать эти изменения, поэтому, если они отправят «вверх по течению» в исходный источник, им не придется иметь дело с той же проблемой в следующей версии.

Ответ 2

Когда вы читаете на странице git tag :

Одним из важных аспектов git является то, что он распространяется, и его распространение в значительной степени означает, что в системе нет присущих «вверх по течению» или «вниз по течению».

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

Если «yourRepo» объявил «otherRepo» удаленным, то:

Обратите внимание на «от» и «для»: вы не просто «ниже по течению», вы «ниже по течению от/для», отсюда и относительный аспект.

Суть DVCS (распределенной системы управления версиями) такова: вы не представляете, что на самом деле представляет собой нисходящий поток, кроме вашего собственного репо относительно объявленных вами удаленных репо.

С точки зрения «потока данных», ваше репо находится в нижней части («нисходящего») потока, идущего из репозиториев в восходящем направлении («извлекать из») и возвращающегося к (тому же или другому) репозиториям в восходящем направлении («толчок в»)).

Вы можете увидеть иллюстрацию на git-rebase странице git-rebase с параграфом «ВОССТАНОВЛЕНИЕ ОТ UPSBREAM REBASE»:

Это означает, что вы вытаскиваете репо «вверх по течению», в котором произошла перебазировка, и вы (репо «вниз по течению») застряли со следствием (множество дублирующих коммитов, потому что ветвь, перебазированная вверх по течению, воссоздала коммиты той же ветки есть локально).

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

Опять же, по аналогии с «потоком данных», в DVCS одна плохая команда «вверх по течению» может иметь «волновой эффект» вниз по течению.

Примечание: это не ограничивается данными.
Это также относится к параметрам, так как команды git (например, «фарфоровые») часто вызывают внутри себя другие команды git («соединительные»). Смотрите страницу rev-parse :

Ответ 3

Восходящий поток (связанный с) Отслеживание

Термин вверх по течению также имеет недвусмысленное значение, поскольку он входит в набор инструментов GIT, особенно относительно отслеживания

будет печатать (последнее кэшированное значение) количество коммитов за (слева) и вперед (справа) от вашей текущей рабочей ветки по сравнению с (если есть) в настоящее время отслеживающей удаленной ветвью для это локальное отделение. В противном случае оно выведет сообщение об ошибке:

это «ветвь» (если есть) на «указанном удалении», которая отслеживает «текущую ветку» в вашем «локальном репозитории».

Это ветка, которую вы извлекаете/извлекаете, когда вы выдает простой git fetch / git pull без аргументов.

Предположим, хотите, чтобы источник/ветвь удаленной ветки был ветвью отслеживания для локальной ветки мастера, которую вы проверили. Просто выпустите:

теперь попробуйте (при условии, что «восходящий» пульт имеет ветвь «dev» )

.git/config теперь читает:

Upstream и Push (Gotcha)

Это предотвращает случайное нажатие на ветки, которые вы еще не готовы нажимать.

Ответ 4

Это немного неофициальная терминология.

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

Термины не ограничены репозиториями Git.

Например, Ubuntu является производным Debian, поэтому Debian находится вверх по течению для Ubuntu.

Ответ 5

Входящий вред, вызванный вводом в эксплуатацию

Например, он говорит о слиянии, что приводит к быстрой перемотке, что это происходит, потому что

фиксация, на которую указывает ваша ветка, была напрямую вверх по течению от youre на

В самом деле, сам Чакон, по-видимому, использует «нисходящий поток» позже, чтобы иметь в виду то же самое, когда он говорит о переписывании всех дочерних коммитов удаленной фиксации:

Вы должны переписать все коммиты ниже по течению от 6df76, чтобы полностью удалить этот файл из истории Git

Источник

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

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

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.

Источник

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?

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

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:

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

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

Источник

Git FAQ

Frequently asked questions around Git and Version Control.

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

How to Set Upstream Branch in Git

Why should you set up an upstream branch for a local branch?

Let’s say that your current local HEAD branch is named «development». Let’s also say that you’ve set the remote «origin/development» as its upstream branch. This relationship is very helpful for two reasons:

Git can now also tell you about unsynced commits which you haven’t pushed or pulled, yet. Here’s an example:

(a) if you have 2 commits in your local repository which you haven’t pushed to the remote yet, then your local branch is «2 commits ahead» of its upstream branch.
(b) if there are 4 commits on the remote upstream branch which you haven’t pulled yet, then your local branch is «4 commits behind» its upstream branch.

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

This information helps tremendously in staying up-to-date. Git tells you about this right in the output for «git status»:

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

The Git Cheat Sheet

Setting an Upstream Branch

The easiest way to set an upstream branch is to use the «—set-upstream» option when pushing the branch to the remote repository for the first time:

A shorter synonym is the «-u» option (instead of the self-explaining but clunky «—set-upstream»):

If the remote counterpart branch already exists or if you want to change the upstream branch, you can use the «git branch» command:

If you’re using the Tower Git client, you don’t have to do anything: Tower will automatically set the upstream when you publish a local branch. It will even inform you about any commits that you haven’t pushed or pulled, yet:

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

Learn More

Get our popular Git Cheat Sheet for free!

You’ll find the most important commands on the front and helpful best practice tips on the back. Over 100,000 developers have downloaded it to make Git a little bit easier.

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

About Us

As the makers of Tower, the best Git client for Mac and Windows, we help over 100,000 users in companies like Apple, Google, Amazon, Twitter, and Ebay get the most out of Git.

Just like with Tower, our mission with this platform is to help people become better professionals.

That’s why we provide our guides, videos, and cheat sheets (about version control with Git and lots of other topics) for free.

Источник

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

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