Push rejected push was rejected and update failed with an error

Push rejected push was rejected and update failed with an error 1 указывает на первый коммит в дереве коммитов ветки master в первом случае при вводе git commit —amend, откроется редактор для изменения сообщения: во втором случае команда ниже позволит внести изменение прямо из консоли: добавил картинку в виде шапки пункт «Командная строка» заменил […]

Содержание

  1. Push rejected push was rejected and update failed with an error
  2. Fix git “tip of your current branch is behind its remote counterpart” — 4 real-world solutions
  3. What causes ”tip of your current branch is behind”?
  4. How can you get your local branch back to a state that’s pushable?
  5. 1. No rebase(s): merge the remote branch into local
  6. 2. Remote rebase + no local commits: force git to overwrite files on pull
  7. 3. Remote rebase + local commits: soft git reset, stash, “hard pull”, pop stash, commit
  8. Options to “soft reset”
  9. Save your changes to the stash
  10. Run the hard pull as seen in the previous section
  11. Un-stash and re-commit your changes
  12. 4. Remote rebase + local commits 2: checkout to a new temp branch, “hard pull” the original branch, cherry-pick from temp onto branch
  13. Create a new temp branch
  14. Go back to the branch and “hard pull”
  15. Cherry-pick the commits from temp branch onto the local branch
  16. Cherry-pick each commit individually
  17. Cherry-pick a range of commits
  18. Get The Jest Handbook (100 pages)
  19. Hugo Di Francesco
  20. Get The Jest Handbook (100 pages)
  21. JavaScript Object.defineProperty for a function: create mock object instances in Jest or AVA
  22. Pass cookies with axios or fetch requests
  23. The Universe of Discourse
  24. Typical workflow
  25. 1. Fetch the remote master branch and check it out.
  26. 2. Do some work and commit it on the local master .
  27. 3. Push the new work back to the remote.
  28. 4. Refresh the tracking branch.
  29. 5. Rewrite the local changes.
  30. 6. Try the push again.
  31. Unavoidable problems

Push rejected push was rejected and update failed with an error

1 указывает на первый коммит в дереве коммитов ветки master

  • в первом случае при вводе git commit —amend, откроется редактор для изменения сообщения:

  • во втором случае команда ниже позволит внести изменение прямо из консоли:
  • добавил картинку в виде шапки
  • пункт «Командная строка» заменил на конкретное название используемой программы — cmder
  • добавил иконки к каждому пункту списка

1;Отмена последнего коммита git log -1 —name-only —oneline;Отобразить список файлов из последнего коммита git branch -v;Отобразить информацию о коммите, на который указывает указатель master (или другой ветки) git log —oneline;Отобразить список коммитов в краткой форме git reflog;Отобразить все действия, которые вы когда-либо сделали в своем репозитории с коммитам git commit —amend git commit —amend -m «Описание»;Изменить описание незапушенного коммита git push -f;Изменить принудительно историю коммитов на УР git log —pretty=format:»%h — %s» —graph;Отобразить граф в формате ASCII, который показывает текущую ветку и историю слияний git diff origin/master..master;Отобразить различия в последних коммитах в удаленной и локальной master-ветках git log —branches —not —remotes —oneline;Отобразить список коммитов, которых нет на УР

Источник

Fix git “tip of your current branch is behind its remote counterpart” — 4 real-world solutions

When working with git a selection of GitLab, GitHub, BitBucket and rebase-trigger-happy colleagues/collaborators, it’s a rite of passage to see a message like the following:

What causes ”tip of your current branch is behind”?

Git works with the concept of local and remote branches. A local branch is a branch that exists in your local version of the git repository. A remote branch is one that exists on the remote location (most repositories usually have a remote called origin ). A remote equates roughly to a place where you git repository is hosted (eg. a GitHub/GitLab/BitBucket/self-hosted Git server repository instance).

Remotes are useful to share your work or collaborate on a branch.

“the tip of your current branch is behind its remote counterpart” means that there have been changes on the remote branch that you don’t have locally.

There tend to be 2 types of changes to the remote branch: someone added commits or someone modified the history of the branch (usually some sort of rebase).

These 2 cases should be dealt with differently.

How can you get your local branch back to a state that’s pushable?

We’re now going to explore how to achieve a state in the local branch where the remote won’t reject the push.

1. No rebase(s): merge the remote branch into local

In the message we can see:

Updates were rejected because the tip of your current branch is behind its remote counterpart. Merge the remote changes (e.g. ‘git pull’) before pushing again.

So is it as simple as doing:

And solving any conflicts that arise.

We shouldn’t do this if someone has rebased on the remote. The history is different and a merge could have a nasty effect on the history. There will be a weird history with equivalent commits in 2 places plus a merge commit.

Read on for solutions to the “remote has been rebased” case.

2. Remote rebase + no local commits: force git to overwrite files on pull

If you don’t have any changes that aren’t on the remote you can just do:

Warning: this is a destructive action, it overwrites all the changes in your local branch with the changes from the remote

This is of course very seldom the case but offers a path to the two following solutions.

Solutions 3. and 4. save the local changes somewhere else (the git stash or another branch). They reset the local branch from the origin using the above command. Finally they re-apply any local changes and send them up.

3. Remote rebase + local commits: soft git reset, stash, “hard pull”, pop stash, commit

Say you’ve got local changes (maybe just a few commits).

A simple way to use the knowledge from 2. is to do a “soft reset”.

Options to “soft reset”

Option 1, say the first commit you’ve added has sha use:

Note the ^ which means the commit preceding

Option 2, if you know the number of commits you’ve added, you can also use the following, replace 3 with the number of commits you want to “undo”:

You should now be able to run git status and see un-staged (ie. “modified”) file changes from the local commits we’ve just “undone”.

Save your changes to the stash

Run git stash to save them to the stash (for more information see git docs for stash).

If you run git status you’ll see the un-staged (“modified”) files aren’t there any more.

Run the hard pull as seen in the previous section

Run git reset —hard origin/branch-name as seen in 2.

Un-stash and re-commit your changes

To restore the stashed changes:

You can now use git add (hopefully with the -p option, eg. git add -p . ) followed by git commit to add your local changes to a branch that the remote won’t reject on push.

Once you’ve added your changes, git push shouldn’t get rejected.

4. Remote rebase + local commits 2: checkout to a new temp branch, “hard pull” the original branch, cherry-pick from temp onto branch

That alternative to using stash is to branch off of the local branch, and re-apply the commits of a “hard pull”-ed version of the branch.

Create a new temp branch

To start with we’ll create a new temporary local branch. Assuming we started on branch branch-name branch (if not, run git checkout branch-name ) we can do:

This will create a new branch temp-branch-name which is a copy of our changes but in a new branch

Go back to the branch and “hard pull”

We’ll now go back to branch branch-name and overwrite our local version with the remote one:

Followed by git reset —hard origin/branch-name as seen in 2.

Cherry-pick the commits from temp branch onto the local branch

We’ll now want to switch back to temp-branch-name and get the SHAs of the commits we want to apply:

To see which commits we want to apply (to exit git log you can use q ).

Cherry-pick each commit individually

Say we want to apply commits and .

We’ll switch to the branch that has been reset to the remote version using:

We’ll then use cherry-pick (see cherry-pick git docs) to apply those commits:

Cherry-pick a range of commits

If you’ve got a bunch of commits and they’re sequential, you can use the following (for git 1.7.2+)

We’ll make sure to be on the branch that has been reset to the remote version using:

You should now be able to git push the local branch to the remote without getting rejected.

Get The Jest Handbook (100 pages)

Take your JavaScript testing to the next level by learning the ins and outs of Jest, the top JavaScript testing library.

Join 1000s of developers learning about Enterprise-grade Node.js & JavaScript

Hugo Di Francesco

Co-author of «Professional JavaScript», «Front-End Development Projects with Vue.js» with Packt, «The Jest Handbook» (self-published). Hugo runs the Code with Hugo website helping over 100,000 developers every month and holds an MEng in Mathematical Computation from University College London (UCL). He has used JavaScript extensively to create scalable and performant platforms at companies such as Canon, Elsevier and (currently) Eurostar.

Get The Jest Handbook (100 pages)

Take your JavaScript testing to the next level by learning the ins and outs of Jest, the top JavaScript testing library.

JavaScript Object.defineProperty for a function: create mock object instances in Jest or AVA

This post goes through how to use Object.defineProperty to mock how constructors create methods, ie. non-enumerable properties that are functions. The gist of Object.defineProperty use with a function value boils down to: const obj = <> Object.defineProperty(obj, ‘yes’, < value: () =>Math.random() > .5 >) console.log(obj) // <> console.log(obj.yes()) // false or true depending on the call 😀 As you can see, the yes property is not enumerated, but it does exist. That’s great for setting functions as method mocks. It’s useful to testing code that uses things like Mongo’s ObjectId. We don’t want actual ObjectIds strewn around our code. Although I did create an app that allows you generate ObjectId compatible values (see it here Mongo ObjectId Generator). All the test and a quick explanation of what we’re doing and why we’re doing it, culminating in our glorious use of Object.defineProperty, is on GitHub github.com/HugoDF/mock-mongo-object-id. Leave it a star if you’re a fan 🙂 . .

Hugo Di Francesco

Pass cookies with axios or fetch requests

When sending requests from client-side JavaScript, by default cookies are not passed. By default, fetch won’t send or receive any cookies from the server, resulting in unauthenticated requests https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch Two JavaScript HTTP clients I use are axios, a “Promise based HTTP client for the browser and Node.js” and the fetch API (see Fetch API on MDN). .

Hugo Di Francesco

Источник

The Universe of Discourse

Archive:

2022: JFMAMJ
JASOND
2021: JFMAMJ
JASOND
2020: JFMAMJ
JASOND
2019: JFMAMJ
JASOND
2018: JFMAMJ
JASOND
2017: JFMAMJ
JASOND
2016: JFMAMJ
JASOND
2015: JFMAMJ
JASOND
2014: JFMAMJ
JASOND
2013: JFMAMJ
JASOND
2012: JFMAMJ
JASOND
2011: JFMAMJ
JASOND
2010: JFMAMJ
JASOND
2009: JFMAMJ
JASOND
2008: JFMAMJ
JASOND
2007: JFMAMJ
JASOND
2006: JFMAMJ
JASOND
2005: OND
Mathematics 219
Programming 95
Language 82
Miscellaneous 59
Book 48
Tech 42
Haskell 33
Oops 29
Unix 26
Etymology 26
Cosmic Call 25
Physics 21
Law 17
Perl 17
Math SE 15

On Saturday I posted an article explaining how remote branches and remote-tracking branches work in Git. That article is a prerequisite for this one. But here’s the quick summary:

When dealing with a branch (say, master) copied from a remote repository (say, origin), there are three branches one must consider:

  1. The copy of master in the local repository
  2. The copy of master in the remote repository
  3. The local branch origin/master that records the last known position of the remote branch

Branch 3 is known as a “remote-tracking branch”. This is because it tracks the remote branch, not because it is itself a remote branch. Actually it is a local copy of the remote branch. From now on I will just call it a “tracking branch”.

The git-fetch command (green) copies branch (2) to (3).

The git-push command (red) copies branch (1) to (2), and incidentally updates (3) to match the new (2).

The diagram at right summarizes this.

We will consider the following typical workflow:

  1. Fetch the remote master branch and check it out.
  2. Do some work and commit it on the local master .
  3. Push the new work back to the remote.

But step 3 fails, saying something like:

In older versions of Git the hint was a little shorter:

Everyone at some point gets one of these messages, and in my experience it is one of the most confusing and distressing things for beginners. It cannot be avoided, worked around, or postponed; it must be understood and dealt with.

Not everyone gets a clear explanation. (Reading it over, the actual message seems reasonably clear, but I know many people find it long and frighting and ignore it. It is tough in cases like this to decide how to trade off making the message shorter (and perhaps thereby harder to understand) or longer (and frightening people away). There may be no good solution. But here we are, and I am going to try to explain it myself, with pictures.)

In a large project, the remote branch is always moving, as other people add to it, and they do this without your knowing about it. Immediately after you do the fetch in step 1 above, the tracking branch origin/master reflects the state of the remote branch. Ten seconds later, it may not; someone else may have come along and put some more commits on the remote branch in the interval. This is a fundamental reality that new Git users must internalize.

Typical workflow

We were trying to do this:

  1. Fetch the remote master branch and check it out.
  2. Do some work and commit it on the local master .
  3. Push the new work back to the remote.

and the failure occurred in step 3. Let’s look at what each of these operations actually does.

1. Fetch the remote master branch and check it out.

The black circles at the top represent some commits that we want to fetch from the remote repository. The fetch copies them to the local repository, and the tracking branch origin/master points to the local copy. Then we check out master and the local branch master also points to the local copy.

Branch names like master or origin/master are called “refs”. At this moment all three refs refer to the same commit (although there are separate copies in the two repositories) and the three branches have identical contents.

2. Do some work and commit it on the local master .

The blue dots on the local master branch are your new commits. This happens entirely inside your local repository and doesn’t involve the remote one at all.

But unbeknownst to you, something else is happening where you can’t see it. Your collaborators or co-workers are doing their own work in their own repositories, and some of them have published this work to the remote repository. These commits are represented by the red dots in the remote repository. They are there, but you don’t know it yet because you haven’t looked at the remote repository since they appeared.

3. Push the new work back to the remote.

Here we are trying to push our local master , which means that we are asking the remote repo to overwrite its master with our local one. If the remote repo agreed to this, the red commits would be lost (possibly forever!) and would be completely replaced by the blue commits. The error message that is the subject of this article is Git quite properly refusing to fulfill your request:

Let’s read through that slowly:

Updates were rejected because the remote contains work that you do not have locally.

This refers specifically to the red commits.

This is usually caused by another repository pushing to the same ref.

In this case, the other repository is your co-worker’s repo, not shown in the diagram. They pushed to the same ref ( master ) before you did.

You may want to first integrate the remote changes (e.g., ‘git pull . ‘) before pushing again.

This is a little vague. There are many ways one could conceivably “integrate the remote changes” and not all of them will solve the problem.

One alternative (which does not integrate the changes) is to use git push -f . The -f is for “force”, and instructs the remote repository that you really do want to discard the red commits in favor of the blue ones. Depending on who owns it and how it is configured, the remote repository may agree to this and discard the red commits, or it may refuse. (And if it does agree, the coworker whose commits you just destroyed may try to feed you poisoned lemonade, so use -f with caution.)

To “fast-forward” the remote ref means that your local branch is a direct forward extension of the remote branch, containing everything that the remote branch does, in exactly the same order. If this is the case, overwriting the remote branch with the local branch is perfectly safe. Nothing will be lost or changed, because the local branch contains everything the remote branch already had. The only change will be the addition of new commits at the end.

There are several ways to construct such a local branch, and choosing between them depends on many factors including personal preference, your familiarity with the Git tool set, and the repository owner’s policies. Discussing all of this is outside the scope of the article, so I’ll just use one as an example: We are going to rebase the blue commits onto the red ones.

4. Refresh the tracking branch.

The first thing to do is to copy the red commits into the local repo; we haven’t even seen them yet. We do that as before, with git-fetch . This updates the tracking branch with a copy of the remote branch just as it did in step 1.

If instead of git fetch origin master we did git pull —rebase origin master , Git would do exactly the same fetch, and then automatically do a rebase as described in the next section. If we did git pull origin master without —rebase , it would do exactly the same fetch, and then instead of a rebase it would do a merge, which I am not planning to describe. The point to remember is that git pull is just a convenient way to combine the commands of this section and the next one, nothing more.

5. Rewrite the local changes.

Now is the moment when we “integrate the remote changes” with our own changes. One way to do this is git rebase origin/master . This tells Git to try to construct new commits that are just like the blue ones, but instead of starting from the last black commit, they will start from the last red one. (For more details about how this works, see my talk slides about it.) There are many alternatives here to rebase , some quite elaborate, but that is a subject for another article, or several other articles.

If none of the files modified in the blue commits have also been modified in any of the red commits, there is no issue and everything proceeds automatically. And if some of the same files are modified, but only in non-overlapping portions, Git can automatically combine them. But if some of the files are modified in incompatible ways, the rebase process will stop in the middle and ask how to proceed, which is another subject for another article. This article will suppose that the rebase completed automatically. In this case the blue commits have been “rebased onto” the red commits, as in the diagram at right.

The diagram is a bit misleading here: it looks as though those black and red commits appear in two places in the local repository, once on the local master branch and once on the tracking branch. They don’t. The two branches share those commits, which are stored only once.

Notice that the command is git rebase origin/master . This is different in form from git fetch origin master or git push origin master . Why a slash instead of a space? Because with git-fetch or git-push , we tell it the name of the remote repo, origin , and the name of the remote branch we want to fetch or push, master . But git-rebase operates locally and has no use for the name of a remote repo. Instead, we give it the name of the branch onto which we want to rebase the new commits. In this case, the target branch is the tracking branch origin/master .

6. Try the push again.

We try the exact same git push origin master that failed in step 3, and this time it succeeds, because this time the operation is a “fast-forward”. Before, our blue commits would have replaced the red commits. But our rewritten local branch does not have that problem: it includes the red commits in exactly the same places as they are already on the remote branch. When the remote repository replaces its master with the one we are pushing, it loses nothing, because the red commits are identical. All it needs to do is to add the blue commits onto the end and then move its master ref forward to point to the last blue commit instead of to the last red commit. This is a “fast-forward”.

At this point, the push is successful, and the git-push command also updates the tracking branch to reflect that the remote branch has moved forward. I did not show this in the illustration.

But wait, what if someone else had added yet more commits to the remote master while we were executing steps 4 and 5? Wouldn’t our new push attempt fail just like the first one did? Yes, absolutely! We would have to repeat steps 4 and 5 and try a third time. It is possible, in principle, to be completely prevented from pushing commits to a remote repo because it is always changing so quickly that you never get caught up on its current state. Repeated push failures of this type are sign that the project is large enough that repository’s owner needs to set up a more structured code release mechanism than “everyone lands stuff on master whenever they feel like it”.

An earlier draft of this article ended at this point with “That is all I have to say about this.” Ha!

Unavoidable problems

Everyone suffers through this issue at some point or another. It is tempting to wonder if Git couldn’t somehow make it easier for people to deal with. I think the answer is no. Git has multiple, distributed repositories. To abandon that feature would be to go back to the dark ages of galley slaves, smallpox, and SVN. But if you have multiple distributed anythings, you must face the issue of how to synchronize them. This is intrinsic to distributed systems: two components receive different updates at the same time, and how do you reconcile them?

For reasons I have discussed before, it does not appear possible to automate the reconciliation in every case in a source code control system, because sometimes the reconciliation may require going over to a co-worker’s desk and arguing for two hours, then calling in three managers and the CTO and making a strategic decision which then has to be approved by a representative of the legal department. The VCS is not going to do this for you.

I’m going to digress a bit and then come back to the main point. Twenty-five years ago I taught an introductory programming class in C. The previous curriculum had tried hard to defer pointers to the middle of the semester, as K&R does (chapter 7, I think). I decided this was a mistake. Pointers are everywhere in C and without them you can’t call scanf or pass an array to a function (or access the command-line arguments or operate on strings or use most of the standard library or return anything that isn’t a number…). Looking back a few years later I wrote:

Pointers are an essential part of [C’s] solution to the data hiding problem, which is an essential issue. Therefore, they cannot be avoided, and in fact should be addressed as soon as possible. … They presented themselves in the earliest parts of the material not out of perversity, but because they were central to the topic.

I developed a new curriculum that began treating pointers early on, as early as possible, and which then came back to them repeatedly, each time elaborating on the idea. This was a big success. I am certain that it is the right way to do it.

(And I’ve been intending since 2006 to write an article about K&R’s crappy discussion of pointers and how its deficiencies and omissions have been replicated down the years by generation after generation of C programmers.)

I think there’s an important pedagogical principle here. A good teacher makes the subject as simple as possible, but no simpler. Many difficult issues, perhaps most, can be ignored, postponed, hidden, prevaricated, fudged, glossed over, or even solved. But some must be met head-on and dealt with, and for these I think the sooner they are met and dealt with, the better.

Push conflicts in Git, like pointers in C, are not minor or peripheral; they are an intrinsic and central issue. Almost everyone is going to run into push conflicts, not eventually, but right away. They are going to be completely stuck until they have dealt with it, so they had better be prepared to deal with it right away.

If I were to write a book about Git, this discussion would be in chapter 2. Dealing with merge conflicts would be in chapter 3. All the other stuff could wait.

That is all I have to say about this. Thank you for your kind attention, and thanks to Sumana Harihareswara and AJ Jordan for inspiration.

Источник

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

Данная статья не ставит перед собой цель быть энциклопедией решений на все случаи жизни. Было бы неверным давать ответы на вопросы, которые на данном этапе изучения Git просто не могут возникнуть. Любая информация должна соответствовать вашему текущему уровню.

1. Самое простое решение многих проблем

Вы «натворили делов» со своим репозиторием, и вам кажется, что все сломалось и ничего не работает. В качестве максимально быстрого решения этой проблемы можно удалить локальный репозиторий (скрытую папку .git в корне вашего проекта) и репозиторий на GitHub, а затем выполнить git init. При этом ваши файлы удалять не нужно.

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

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

2. Как изменить URL удаленного репозитория?

Вы неверно назвали свой репозиторий, например, вместо StartJava почему-то написали Lesson1 или JavaOps. На что наставник вам сказал, что его нужно переименовать.

Или вы удалили свой репозиторий на GitHub, а у себя на компьютере — оставили. После этого создали новый удаленный репозиторий (УР), изменив его первоначальное имя.

Например, URL репозитория выглядел так:


https://github.com/ichimax/lesson1.git

А после изменений ссылка стала следующей:


https://github.com/ichimax/startjava.git

При этом в настройках локального репозитория (ЛР) адрес старого репозитория никуда не делся — его нужно обновить.

Свяжем ЛР с новым адресом УР:


> git remote set-url origin новый_url.git
> git remote -v

Когда вам в дальнейшем потребуется выполнить push, то необходимо будет написать полную версию команды git push -u origin master, чтобы заново связать ЛР с новым УР, а затем снова можете использовать сокращенный вариант.

3. Как удалить файл из репозитория?

3.1. Удаление файла из индекса

Представим, что вы забыли занести в .gitignore правило, которое позволяло бы игнорировать class-файлы. В итоге применив команду git add, добавили их случайно в индекс.

Это очень частая ошибка у начинающих, которая влечет за собой попадание мусорных файлов в УР.

Скомпилируем исходник, создав class-файл:

Внесем изменения в класс из предыдущих статей:


import java.util.Scanner;

public class MyFirstApp {
    public static void main(String[] args) {
        System.out.println("У какого языка программирования следующий слоган:");
        System.out.print(""Написано однажды, ");
        System.out.println("работает везде!"");

        String answer = new Scanner(System.in).next();
        if (answer.equalsIgnoreCase("Java")) {
            System.out.println("Вы угадали");
        } else System.out.println("Увы, но - это Java");
    }
}

Далее введем привычные команды:


> git add . && git status
Changes to be committed:
  (use "git restore --staged <file>..." to unstage)
        new file:   MyFirstApp.class
        modified:   MyFirstApp.java

MyFirstApp.class в итоге попал в индекс Git. Необходимо его оттуда удалить, т. к. отслеживание изменений у данного вида файлов не несет никакой практической пользы.

Воспользуемся командой, подсказанной Git:


> git restore --staged MyFirstApp.class && git status
Changes to be committed:
        modified:   MyFirstApp.java

Untracked files:
        MyFirstApp.class

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

Чтобы обезопасить себя, перед использованием команды git add, всегда нужно просматривать список файлов (git status), которые вы планируете добавить в индекс. Также обязательно добавьте шаблон *.class в .gitignore, чтобы больше не спотыкаться о class-файлы.

3.2. Удаление файла из коммита

Пойдем дальше и научимся удалять MyFirstApp.class из коммита.


> git status

Changes to be committed:
        new file:   MyFirstApp.class
        modified:   MyFirstApp.java

Добавим все изменения в коммит:


> git commit -m "Добавил quiz по слогану Java"

Перед тем, как запушить коммит, программист решил посмотреть, какие файлы в него входят:


> git log -1 --name-only --oneline
ead5167 (HEAD -> master) Добавил quiz по слогану Java
src/MyFirstApp.class
src/MyFirstApp.java

С командной git log мы уже сталкивались в предыдущей статье. Из нового — аргумент —name-only, который позволяет вывести только имена измененных файлов, находящихся в коммите.

Использование log позволило заметить, что MyFirstApp.class оказался в коммите. Его нужно оттуда убрать.


> git reset --soft HEAD~1

Разберем эту команду по частям:

  • reset — отменяет коммиты
  • —soft — позволяет выполнить отмену коммита без потери изменений
  • HEAD — указатель на локальную ветку в которой мы находимся. В нашем случае HEAD~1 указывает на первый коммит в дереве коммитов ветки master

Более подробно про команду reset (1, 2).

Тут следует сказать, что HEAD указывает на ветку, в которой вы находитесь в данный момент. Благодаря ему мы можем перемещаться по дереву коммитов и откатываться к любому из них.

Получается следующая картина: HEAD указывает на ветку master, а master является указателем на вершину в дереве коммитов.

Отобразим, куда указывает HEAD:

* обозначается текущая ветка.

Если команду ввести с параметром -v, то кроме названия ветки отобразится информация о коммите, на который указывает master:


> git branch -v
* master b59d871 Изменил вывод текста, отображаемого в консоль

После отмены коммита отобразим список оставшихся коммитов:


> git log --oneline
b59d871 (HEAD -> master, origin/master) Изменил вывод текста, отображаемого в консоль
39ba195 Переименовал about.txt в README.md и внес в него описание проекта
1e36e0f Инициализация проекта

Видим, что благодаря reset последний коммит из него был исключен.

При этом log отображает ту же самую информацию, о которой мы говорили выше: HEAD указывает на master, а он — на вершину дерева коммитов (коммит b59d871).

Стоит отметить, что команду reset необходимо использовать только для отмены коммитов, которые находятся исключительно на вашем компьютере и еще не попали на УР. Т. к. эта команда меняет историю коммитов, то это может принести множество проблем для других людей, которые совместно с вами работают в одном репозитории, если вы отмените с ее помощью коммит, а затем запушите изменения на УР.

Посмотрим, в каком состоянии теперь находится ЛР:


> git status
Changes to be committed:
        new file:   MyFirstApp.class
        modified:   MyFirstApp.java

Что делать дальше, вы уже знаете: нужно убрать из индекса class-файл, и закоммитить java-класс.

Исключаем MyFirstApp.class:


> git restore --staged MyFirstApp.class
> git status
Changes to be committed:
        modified:   MyFirstApp.java

Untracked files:
        MyFirstApp.class

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

Есть одна волшебная команда git reflog, которая отобразит все, что вы когда-либо сделали в своем репозитории с коммитами. Это своего рода лог всех ваших операций. Приведу его малую часть, которая нам необходима:


> git reflog
b59d871 (HEAD -> master, origin/master) HEAD@{0}: reset: moving to HEAD~1
ead5167 HEAD@{1}: commit: Добавил quiz по слогану Java

Из вывода видно описание отмененного коммита. Используем его для нового:


> git commit -m "Добавил quiz по слогану Java"

Больше подробностей о reflog по ссылке.

Не забудьте добавить *.class в.gitignore.

3.3. Удаление файла с GitHub

Самый неприятный случай — это когда мусорный файл все же пробрался на GitHub, т. е. был запушен:

В этом случае наставник вам может написать замечание: «на GitHub не должно быть файлов с расширением *.class, только *.java. Необходимо удалить из УР все class-файлы».

Самый простой выход из этой ситуации — это удалить в ЛР class-файлы, добавить в .gitignore маску *.class и сделать новый пуш. После этих действий на GitHub class-файл удалится. Он также автоматически удалится и у всех людей, которые работают с вами в одном репозитории. Например, когда наставник перед проверкой вашего ДЗ сделает git pull, то удаленные вами class-файлы, удалятся автоматически и у него.

Выглядеть это может примерно так:


D:JavaStartJava (master -> origin)
> git rm src*.class
rm 'src/MyFirstApp.class'


> git status
On branch master

Changes to be committed:
        new file:   .gitignore
        deleted:    src/MyFirstApp.class

> git commit -m "Добавил .gitignore с маской *.class"
[master 4bf0ddd] Добавил .gitignore с маской *.class
 2 files changed, 1 insertion(+)
 create mode 100644 .gitignore
 delete mode 100644 src/MyFirstApp.class

> git push

4. Как изменить описание коммита?

4.1. Коммит не был запушен

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

Внесем ряд изменений в файл MyFirstApp.java, добавив в него код, запрашивающий у участника квиза его имя, которое будет выводиться, если он ответит правильно на вопрос:


import java.util.Scanner;

public class MyFirstApp {
    public static void main(String[] args) {
        Scanner console = new Scanner(System.in, "cp866");
        System.out.print("Введите, пожалуйста, свое имя: ");
        String name = console.next();

        System.out.println("У какого языка программирования следующий слоган:");
        System.out.print(""Написано однажды, ");
        System.out.println("работает везде!"");

        String answer = console.next();
        if (answer.equalsIgnoreCase("Java")) {
            System.out.println(name + ", вы угадали!");
        } else System.out.println("Увы, но - это Java");
    }
}

> git add MyFirstApp.java
> git commit -m "Добавил ввод имени учасника"

Выясняется, что описание содержит опечатку в слове «учасника».

Для исправления воспользуемся двумя вариантами команды commit:

  • в первом случае при вводе git commit —amend, откроется редактор для изменения сообщения:

Такой способ подходит для исправления многострочных комментариев. Нам же больше подходит второй способ.

  • во втором случае команда ниже позволит внести изменение прямо из консоли:

> git commit --amend -m "Добавил ввод имени участника"
[master 96e2847] Добавил ввод имени участника

Убедимся, что описание к коммиту изменилось, а прежнее — не сохранилось, отобразив сокращенную информацию по последнему коммиту:


> git log --oneline -1
96e2847 (HEAD -> master) Добавил ввод имени участника

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

4.2.1. Принудительная перезапись истории

Что описание к коммиту нужно изменить, вы вспомнили, когда он был уже отправлен на GitHub.

Чтобы решить эту задачу, необходимо к команде из предыдущего пункта добавить git push -f, которая принудительно перезапишет коммит с ошибочным описанием — исправленным:


> git commit --amend -m "Добавил ввод имени участника"
> git push -f

Среди прочего, в консоли отобразится примерно следующая строка:


+ 5aa3d6d...ce3cf6f master -> master (forced update).

Она сообщает, что было сделано принудительное обновление репозитория.

У ваших коллег (или наставника) после ввода git pull отобразятся строки, тоже сообщающие о принудительном изменении и последующем успешном слиянии (merge):


+ 5aa3d6d...ce3cf6f master     -> origin/master  (forced update)
Merge made by the 'ort' strategy.

5. Как выполнить пуш, если Git не дает это сделать?

Представим, что на первых порах вы еще не до конца освоили Git и какое-то время вносили изменения в файлы прямо на GitHub. Но рано или поздно поняли, что для своего профессионального роста все же нужно изучить базовые команды Git, и применять их в консоли.

После этого у себя на компьютере начали писать код очередного домашнего задания, а затем решили его запушить на GitHub для проверки наставником. Но сделать пуш у вас в итоге не получилось, а в консоли отобразилась ошибка:


hint: Updates were rejected because the remote contains work that you do
hint: not have locally. This is usually caused by another repository pushing
hint: to the same ref. You may want to first integrate the remote changes

Возможна и другая ситуация, когда вы пушите в один репозиторий на GitHub с разных компьютеров. Например, днем, в свободное от работы время, порешали домашку, а затем запушили ее на удаленный репозиторий. Вечером, придя домой, продолжили писать код для следующего ДЗ. А про код, запушенный на GitHub, либо забыли, либо подумали, что из-за него проблем не будет. Но в действительности оказалось все иначе.

Или на GitHub случайно попали class-файлы и вы без задней мысли пошли на сайт и удалили их.

Во всех этих ситуациях пуш приведет к одной и той же ошибке, связанной с тем, что истории изменений на локальном и удаленном репозитории пошли разными путями: на GitHub есть коммит, которого нет в ЛР. В дереве коммитов на ЛР на какое-то количество коммитов меньше, чем на УР.

Научимся решать эту проблему.

5.1. Подтягивание изменений с GitHub

Зайдя в свой репозиторий на GitHub, я внес в README.md следующие мелкие изменения:

  • добавил картинку в виде шапки
  • пункт «Командная строка» заменил на конкретное название используемой программы — cmder
  • добавил иконки к каждому пункту списка

В качестве описания к коммиту указал следующий текст:

При этом README.md содержит следующий код:


# [StartJava](https://topjava.ru/startjava) -- курс на Java для начинающих

![image](https://user-images.githubusercontent.com/29703461/194078652-25a6e509-cdc6-4af4-9ab0-78b6b336c749.png)

## Используемые на курсе инструменты и технологии

:coffee: Java

:octocat: Git/GitHub

:pager: cmder

:bookmark_tabs: Sublime Text

:fire: Intellij IDEA

:gem: SQL

:elephant: PostgreSQL

:newspaper: psql

Проделанные только что изменения я благополучно забыл подтянуть на свой компьютер с помощью git pull. И продолжил работать над классом MyFirstApp.java в ЛР, добавив в него еще один квиз и немного мелких правок.

В итоге класс (у меня на компьютере, не в GitHub) стал выглядеть так:


import java.util.Scanner;

public class MyFirstApp {
    public static void main(String[] args) {
        Scanner console = new Scanner(System.in, "cp866");
        System.out.print("Введите, пожалуйста, свое имя: ");
        String name = console.nextLine();

        System.out.println("n1. У какого языка программирования следующий слоган:");
        System.out.print(""Написано однажды, ");
        System.out.println("работает везде!"");

        String answer = console.nextLine();
        if (answer.equalsIgnoreCase("Java")) {
            System.out.println(name + ", вы угадали!");
        } else System.out.println("Увы, но - это Java");

        System.out.println("n2. Какая фамилия у автора языка Java?");

        answer = console.nextLine();
        if (answer.equals("Гослинг") || answer.equals("Gosling")) {
            System.out.println(name + ", вы угадали!");
        } else System.out.println("Увы, но - это Гослинг (Gosling)");
    }
}

Добавил изменения в коммит:


> git add MyFirstApp.java
> git commit -m "Добавил quiz по автору Java"

Отобразим полученный результат в консоли:


> git log --oneline -1
7106587 (HEAD -> master) Добавил quiz по автору Java

А теперь самое интересное: попробуем сделать push:


> git push
To https://github.com/ichimax/startjava2.git
 ! [rejected]        master -> master (fetch first)
error: failed to push some refs to 'https://github.com/ichimax/startjava2.git'
hint: Updates were rejected because the remote contains work that you do
hint: not have locally. This is usually caused by another repository pushing
hint: to the same ref. You may want to first integrate the remote changes
hint: (e.g., 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.

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

Для решения этой проблемы Git предлагает выполнить команду pull, которая подтянет коммиты с УР, а затем объединит их с локальными, чтобы выровнять историю:


> git pull
remote: Enumerating objects: 5, done.
remote: Counting objects: 100% (5/5), done.
remote: Compressing objects: 100% (3/3), done.
remote: Total 3 (delta 0), reused 0 (delta 0), pack-reused 0
Unpacking objects: 100% (3/3), 1.16 KiB | 62.00 KiB/s, done.
From https://github.com/ichimax/startjava2
   ce3cf6f..2bdecf7  master     -> origin/master
Merge made by the 'ort' strategy.
 README.md | 25 +++++++++++++++++--------
 1 file changed, 17 insertions(+), 8 deletions(-)

В этом сообщении стоить обратить внимание на строку Merge made by the ‘ort’ strategy. Из нее мы можем сделать вывод, что произошло слияние (merge).

Слияние — это объединение истории коммитов из разных веток в одну. У нас ветка хоть и одна (master), но история коммитов на GitHub и в ЛР стала с какого-то момента различаться. Из-за этого и не удавалось сделать push. Когда мы выполнили git pull, то Git автоматически объединил (что бывает не всегда) последний коммит из УР с последним коммитом из ЛР, создав новый.

Не всегда Git может выполнить слияние автоматически, что вызывает конфликт слияния. Такое бывает, когда в разных ветках был изменен один и тот же фрагмент кода. Из-за этого Git не сможет определить, какую версию использовать. Для решения проблемы потребуется вмешательство пользователя. Более подробно об этом можно узнать по ссылке.

Для того, чтобы минимизировать возникновение подобных ситуаций (конфликтов), рекомендуется каждый раз перед началом работы с проектом делать git pull, чтобы синхронизировать историю коммитов ЛР с историей УР.

Отобразим 4 последних коммита:


> git log --oneline -4
1b4a7b7 (HEAD -> master) Merge branch 'master' of https://github.com/ichimax/startjava2
7106587 Добавил quiz по автору Java
2bdecf7 (origin/master) Обновил README.md
ce3cf6f Добавил ввод имени участника

Из этого списка видно, что:
2bdecf7 — был сделан на GitHub
7106587 — был сделан в ЛР
1b4a7b7 — получился автоматически после слияния двух предыдущих коммитов

Обратите внимание, что у коммита, сделанного на GitHub, ветка называется не master, а origin/master. Разница в том, что master — это имя локальной ветки, а origin/master является удаленной веткой с именем master.

Отобразим ветки, связанные с нашим репозиторием:


> git branch -a
* master
  remotes/origin/master

Ветка master является текущей (помечена *) веткой ЛР. remotes/origin/master — это ветвь с именем master и псевдонимом origin на УР.

То, что это — разные ветки, можно убедиться визуально, введя следующую команду:


D:JavaStartJavasrc (master -> origin)
> git log --pretty=format:"%h - %s" --graph
*   1b4a7b7 - Merge branch 'master' of https://github.com/ichimax/startjava2
| 
| * 2bdecf7 - Обновил README.md
* | 7106587 - Добавил quiz по автору Java
|/
* ce3cf6f - Добавил ввод имени участника
* 4bf0ddd - Добавил .gitignore с маской *.class
* 90ca67c - Добавил quiz по слогану Java
* b59d871 - Изменил вывод текста, отображаемого в консоль
* 39ba195 - Переименовал about.txt в README.md и внес в него описание проекта
* 1e36e0f - Инициализация проекта

Опция —graph позволяет вывести граф в формате ASCII, который показывает текущую ветку и историю слияний. Более подробно с разными опциями команды log можно ознакомиться по ссылке.

Давайте взглянем на различия в последних коммитах в удаленной и локальной master-ветках:


D:JavaStartJavasrc (master -> origin)
> git diff origin/master..master
diff --git a/src/MyFirstApp.java b/src/MyFirstApp.java
index 8e25560..08099ad 100644
--- a/src/MyFirstApp.java
+++ b/src/MyFirstApp.java
@@ -4,15 +4,22 @@ public class MyFirstApp {
     public static void main(String[] args) {
         Scanner console = new Scanner(System.in, "cp866");
         System.out.print("Введите, пожалуйста, свое имя: ");
-        String name = console.next();
+        String name = console.nextLine();

-        System.out.println("У какого языка программирования следующий слоган:");
+       System.out.println("n1. У какого языка программирования следующий слоган:");
         System.out.print(""Написано однажды, ");
         System.out.println("работает везде!"");

-        String answer = console.next();
+        String answer = console.nextLine();
         if (answer.equalsIgnoreCase("Java")) {
             System.out.println(name + ", вы угадали!");
         } else System.out.println("Увы, но - это Java");
+
+        System.out.println("n2. Какая фамилия у автора языка Java?");
+
+        answer = console.nextLine();
+        if (answer.equals("Гослинг") || answer.equals("Gosling")) {
+            System.out.println(name + ", вы угадали!");
+        } else System.out.println("Увы, но - это Гослинг (Gosling)");
     }
 }

После всех манипуляций отобразим состояние репозитория:


> git status
On branch master
Your branch is ahead of 'origin/master' by 2 commits.
  (use "git push" to publish your local commits)
 
nothing to commit, working tree clean

Посмотрим, какие два коммита мы должны запушить:


> git log --branches --not --remotes --oneline
1b4a7b7 (HEAD -> master) Merge branch 'master' of https://github.com/ichimax/startjava2
7106587 Добавил quiz по автору Java

Выполним push и снова введем команду, отображающую список из 4 коммитов:


> git push
> git log --oneline -4
1b4a7b7 (HEAD -> master, origin/master) Merge branch 'master' of https://github.com/ichimax/startjava2
7106587 Добавил quiz по автору Java
2bdecf7 Обновил README.md
ce3cf6f Добавил ввод имени участника

Видим, что история коммитов выровнялась: HEAD в ЛР и УР указывают на самый последний коммит 1b4a7b7.

Список решений тех или иных задач с помощью Git, разобранных в статье, с кратким описанием.

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

Оцените статью, если она вам понравилась!

Урок, в котором мы изучим команды git push и git pull и научимся работать с удаленным репозиторием

Видеоурок

Конспект урока

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

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

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

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

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

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

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

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

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

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


    $ git status
    
    On branch master
    $ git status
    On branch master
    Your branch is ahead of 'origin/master' by 5 commits.
      (use "git push" to publish your local commits)
    (use "git push" to publish your local commits)

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


    $ git status
    
    On branch master
    Your branch is up-to-date with 'origin/master'.

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

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

master и origin/master

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

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


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

Как пушить в PhpStorm

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

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

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

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

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

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


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

Как пулить в PhpStorm

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

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

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

git push rejected

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


    $ git push origin master
    To git@github.com:Webdevkin/site-git.git
     ! [rejected]        master -> master (fetch first)
    error: failed to push some refs to 'git@github.com:Webdevkin/site-git.git'
    hint: Updates were rejected because the remote contains work that you do
    hint: not have locally. This is usually caused by another repository pushing
    hint: to the same ref. You may want to first integrate the remote changes
    hint: (e.g., 'git pull ...') before pushing again.
    hint: See the 'Note about fast-forwards' in 'git push --help' for details.

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

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

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


    $ git pull origin master
    remote: Enumerating objects: 4, done.
    remote: Counting objects: 100% (4/4), done.
    remote: Compressing objects: 100% (2/2), done.
    remote: Total 3 (delta 0), reused 0 (delta 0), pack-reused 0
    Unpacking objects: 100% (3/3), done.
    From github.com:Webdevkin/site-git
     * branch            master     -> FETCH_HEAD
       239892a..383b385  master     -> origin/master
    Merge made by the 'recursive' strategy.
     README.md | 3 +++
     1 file changed, 3 insertions(+)
     create mode 100644 README.md

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


    $ git push origin master 
    Counting objects: 19, done.
    Delta compression using up to 4 threads.
    Compressing objects: 100% (17/17), done.
    Writing objects: 100% (19/19), 1.98 KiB | 0 bytes/s, done.
    Total 19 (delta 4), reused 0 (delta 0)
    remote: Resolving deltas: 100% (4/4), completed with 1 local object.
    To git@github.com:Webdevkin/site-git.git
       383b385..f32b91e  master -> master

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

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

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

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

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


    $ git pull --rebase origin master 

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

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

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

Внимание

Объяснения в тексте не передают точно возникающие проблемы, это нужно видеть в динамике.
Поэтому лучше смотрите видеоуроки и еще лучше пробуйте сами повторять их содержание.

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

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

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

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

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

git push pull whaaat

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

Спасибо за внимание и до встречи!

Все уроки курса

  • Вводный урок
  • 1. Установка и базовая настройка git
  • 2. Создание и клонирование репозитория git
  • 3. Делаем первые изменения, git status и git diff
  • 4. Коммиты и история коммитов, git commit, git log и git show
  • 5. Подробнее об истории коммитов. Путешествие по истории
  • 6. Работа с сервером, git push и git pull
  • 7. Ветки — главная фишка git, git branch и git checkout
  • 8. Работа с ветками на сервере, git fetch
  • 9. Слияния или мерджи веток, git merge
  • 10. Конфликты и их разрешение
  • Платная часть курса. Презентация
  • * 11. Работа с gitignore и git exclude
  • * 12. Буфер обмена git, git stash
  • * 13. Копирование коммитов, git cherry-pick
  • * 14. Отмена и редактирование последнего коммита
  • * 15. Отмена произвольного коммита, git revert
  •    16. Склеивание коммитов, git rebase —interactive и git reflog
  • * 17. Зачем склеивать коммиты. Плюсы и минусы сквоша
  • * 18. Работа с git rebase. Отличия от merge
  • * 19. Что такое git push —force и как с ним работать
  • * 20. Ищем баги с помощью git, git bisect
  • * 21. Как и зачем работать с тегами git
  • * 22. Процессы: github flow и git flow
  • * 23. Псевдонимы в git
  •    24. Мердж-реквесты
  • * 25. Форки

* платные уроки

список обновляется…




Содержание статьи


fatal: No such remote ‘origin’

fatal: No such remote ‘origin’

fatal: No such remote ‘origin’

Скорее всего Вы пытаетесь выполнить

$ git remote set-url origin https://github.com/name/project.git

Попробуйте сперва выполнить

$ git remote add origin https://github.com/name/project.git

2

To https://github.com/YourName/yourproject.git

! [rejected] master -> master (non-fast-forward)
error: failed to push some refs to ‘https://github.com/YourName/yourproject.git’


hint: Updates were rejected because the tip of your current branch is behind

hint: its remote counterpart. Integrate the remote changes (e.g.

hint: ‘git pull …’) before pushing again.

hint: See the ‘Note about fast-forwards’ in ‘git push —help’ for details.

Скорее всего Вы пытаетесь выполнить

git push origin master

в новом репозитории.

При этом, когда
Вы создавали удалённый репозиторий на github Вы отметили опцию initialize with readme file.

Таким образом на удалённом репозитории файл

README.md

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

Первым делом попробуйте

$ git pull origin master

$ git push origin master

Git скачает файл

README.md

с удалённого репозитория и затем можно будет спокойно пушить

Если сделать pull не получилось, например, возникла ошибка

From https://github.com/andreiolegovichru/heiheiru

* branch master -> FETCH_HEAD

fatal: refusing to merge unrelated histories

Попробуйте

$ git pull —allow-unrelated-histories origin master

$ git push origin master

ERROR: Permission to AndreiOlegovich/qa-demo-project.git denied to andreiolegovichru.
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

Возможная причина — git не видит ваш ключ. Либо ваш ключ уже используется для другого удалённого
хранилища.

Решить можно удалив стандарный ключ id_rsa.pub создать новую пару и добавить на удалённое хранилище.

Если этот способ не подходит — нужно настроить config.

Понравилась статья? Поделить с друзьями:
  • Pure как изменить разрешение
  • Pure как изменить город
  • Pure virtual function being called while application was running gisrunning 1 xcom 2 как исправить
  • Purchases are not permitted from your region at this time fortnite как исправить
  • Purchase completed error occurred murder mystery 2 коды