Error failed to push some refs to https

Sometimes, Git can't make your change to a remote repository without losing commits. When this happens, your push is refused.

Sometimes, Git can’t make your change to a remote repository without losing commits. When this happens, your push is refused.

If another person has pushed to the same branch as you, Git won’t be able to push your changes:

$ git push origin main
> To https://github.com/USERNAME/REPOSITORY.git
>  ! [rejected]        main -> main (non-fast-forward)
> error: failed to push some refs to 'https://github.com/USERNAME/REPOSITORY.git'
> To prevent you from losing history, non-fast-forward updates were rejected
> Merge the remote changes (e.g. 'git pull') before pushing again.  See the
> 'Note about fast-forwards' section of 'git push --help' for details.

You can fix this by fetching and merging the changes made on the remote branch with the changes that you have made locally:

$ git fetch origin
# Fetches updates made to an online repository
$ git merge origin YOUR_BRANCH_NAME
# Merges updates made online with your local work

Or, you can simply use git pull to perform both commands at once:

$ git pull origin YOUR_BRANCH_NAME
# Grabs online updates and merges them with your local work

Error: failed to push some refs to – How to Fix in Git

When collaborating with other developers using Git, you might encounter the error: failed to push some refs to [remote repo] error.

This error mainly occurs when you attempt to push your local changes to GitHub while the local repository (repo) has not yet been updated with any changes made in the remote repo.

So Git is trying to tell you to update the local repo with the current changes in the remote before pushing your own changes. This is necessary so that you don’t override the changes made by others.

We’ll be discussing two possible ways of fixing this error in the sections that follow.

We can fix the error: failed to push some refs to [remote repo] error in Git using the  git pull origin [branch] or git pull --rebase origin [branch] commands. In most cases, the latter fixes the error.

Let’s go over how you can use the commands above.

How to Fix error: failed to push some refs to Error in Git Using git pull

To send a pull request means to «fetch» new changes made to the remote repo and merge them with the local repo.

Once the merging is done, you can then push your own code changes to GitHub.

In our case, we’re trying to get rid of the error: failed to push some refs to [remote repo] error by sending a pull request.

Here’s how you can do that:

git pull origin main

If you’re working with a different branch, then you’d have to replace main in the example above with the name of your branch.

Just keep in mind that there are chances of failure when using this command to sync your remote and local repos to get rid of the error. If the request succeeds, then go on and run the command below to push your own changes:

git push -u origin main

If the error persists, you’ll get an error that says: fatal: refusing to merge unrelated histories. In that case, use the solution in the next section.

How to Fix error: failed to push some refs to Error in Git Using git pull --rebase

The git pull --rebase  command is helpful in situations where your local branch is a commit behind the remote branch.

To fix the error, go on and run following commands:

git pull --rebase origin main

git push -u origin main 

If the first command above runs successfully, you should get a response that says: Successfully rebased and updated refs/heads/main.

The second command pushes your local repo’s current state to the remote branch.

Summary

In this article, we talked about the error: failed to push some refs to [remote repo] error.

This error occurs when you attempt to push your local changes to the remote repo without updating your local repo with new changes made to the remote repo.

We discussed two commands that you can use to fix the error: the git pull origin [branch] and git pull --rebase origin [branch] commands.

I hope this helps you fix the error.

Happy coding!



Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started

What is ‘failed to push some refs to’ error

failed to push some refs to is a Git error that many developers frequently face. It occurs when a developer attempts to push committed code to an external git repository. The ability to push code stopped working suddenly, despite it working yesterday or the day before. It can be a source of frustration and annoyance for many.

failed to push some refs to errors are often caused when changes are not committed before pushing, issues with Git pre-push hook, incorrect branch name, or the local repository not being in sync with the Git repository. It occurs most of the time because multiple contributors are working on the same branch and the remote repository is further along than what you currently have on your local machine.

It is easy for git pushes to overlap when working in teams or for ref heads to be in different positions. This overlap can cause the repository to be out of sync, which is why the failed to push some refs to error are so frequent.

What causes ‘failed to push some refs to’ error

When multiple developers work on the same branch, it can cause a sequencing issue in Git. A commit gets rejected and causes a failed to push some refs to error because the remote branch contains code that you do not have locally. What this means is that your local git repository is not compatible with the remote origin.

Here is an abstraction of what incompatibility looks like in Git:

A -- B -- C -- D (on the remote)
A -- B -- E (on your local machine)

Based on the above, your local machine is missing commits C and D. Meanwhile, you are trying to slot in your commit – E – between B and C on the remote.

Before Git lets you proceed, you will need to integrate the remote changes into your local repository. This step will fix any incompatibility issues and ensure that your version is up to date with the remote.

How can you fix ‘failed to push some refs to’ errors

Here are the scenarios that may cause the failed to push some refs error, and how to correct them:

1.Another developer pushed a commit to the same branch

The error in your terminal looks like this:

To [email protected]:sometest.git
! [rejected] your-branch -] your-branch (non-fast-forward)

When this occurs, the head sits at different positions on the same code timeline, and Git does not know how to handle it. This is because the origin repository is ahead of where you currently are. To fix this issue, run git pull on your local repository. This should allow you to push to origin again.

git pull origin [your-branch]
git push origin [your-branch]

2. You got a ‘master (non-fast-forward)’ error with a ‘failed to push some refs to’ error

A git fast-forward happens when the ref pointer gets moved forward in the commit history. However, if your code diverges before it reaches the latest commit, it can cause the non-fast-forward issue and lead to a failed to push some refs to error.

To solve this issue, you can pull with the --rebase flag. --rebase will let you move your intended files to commit over to the latest pull code.

Here is how to pull with --rebase:

git pull --rebase origin [branch]

3. You got a ‘master (fetch first)’ error with a ‘failed to push some refs to’ error

When this occurs, someone has pushed to the branch before you. Git wants you to pull first before you can push your committed changes.

To prevent the loss of your work during the pull, you can stash your local changes.

The common suggested fix is to use --force flag to push through the local changes. However, it is good practice to avoid using the --force flag as it can cause inconsistency issues. Instead, use --rebase to move the ref heads and update your local repository without causing a divergence in the remote repository.

Using --force to try and fix the failed to push some refs to error will only result in more errors in the long run. This occurs because --force uses a brute force method that puts your current code and its ref head as the source of truth.

As a result, the changes in the remote can be overwritten by what you have pushed, removing any features or updates that other developers may have committed.

Only use --force if you are comfortable with features not on your local being overwritten with what you’ve currently got. Use the --force flag if you are confident that your local repository in its current state is correct.

How to prevent ‘failed to push some refs to’ errors

To prevent failed to push some refs to errors in Git, it is good practice to avoid having multiple developers work on the same branch simultaneously. Instead, use feature branches that merge into a master branch or something equivalent.

If you get a failed to push some refs to error, the main thing to do is git pull to bring your local repo up to date with the remote. Avoid employing the --force flag when using git pull and prevent other developers’ accidental overwrites of committed features.

Use the --rebase flag instead to avoid other errors from occurring while fixing your original failed to push some refs to error.

Kubernetes Troubleshooting with Komodor

We hope that the guide above helps you better understand the troubleshooting steps you need to fix the failed to push some refs to error.

Keep in mind that this is just one of many Git errors that can pop up in your K8s logs and cause the system to fail. Due to the complex and distributed nature of k8s,
the search for the root cause of each such failure can be stressful, disorienting, and time-consuming.

This is why we created Komodor, which acts as a single source of truth (SSOT) to streamline and shorten your k8s troubleshooting processes. Among other features, it offers:

  • Change intelligence: Every issue is a result of a change. Within seconds we can help you understand exactly who did what and when.
  • In-depth visibility: A complete activity timeline, showing all code and config changes, deployments, alerts, code diffs, pod logs, etc. All within one pane of glass with easy drill-down options.
  • Insights into service dependencies: An easy way to understand cross-service changes and visualize their ripple effects across your entire system.
  • Seamless notifications: Direct integration with your existing communication channels (e.g., Slack) so you’ll have all the information you need, when you need it.

A quick guide to fix Git error: failed to push some refs to in 5 ways

1. Overview

In this tutorial, We’ll learn how to fix the git error failed to push some refs to in 5 ways.

Most of the time you get this error while pushing your change git remote repository.

This might be working a few days back but suddenly started showing a weird error message «failed to push some refs to».

You are stuck at this point and do not what to do now. And you might be thinking because of my new changes?

For this error, there are mainly two reasons.

a) Your branch is set to main and not master

b) Remote repo has new changes and you do not have those changes on your laptop or local branch

Now, you knew about the actual reasons to get this common error.

Let us jump into the fixes.

Git error: failed to push some refs to

2. Fix 1 Heroku — Git error: failed to push some refs to

To solve this error, you need to check what is the default branch on your github.com.

Once you find the right branch then you need to switch to the correct branch using git push command.

If the default branch is main on remote but it is master on your branch then please run below git push command.

Otherwise, it could be master as below.

If some else have pushed the new changes before you push to the remote repo. In this case, you do not have the recent commits on your laptop local repo.

So, you need to first pull the changes from that branch and then push your new commits.

To fix this error, follow the below steps.

git pull origin <your-branch>
git push origin <your-branch>

It is strongly recommended to pull always changes first before pushing your commits to remote origin.

4. Fix 3 — Git error: failed to push some refs to

Sometimes, fix 2 did not work if you have more commits that produce the conflicts. In this case, the normal git pull command won’t work properly.

The solution to this problem is git-rebase.

Git rebase is a process of moving and arranging the sequence of comments into the new base commit.

Follow the below commands. Here the branch can be modified based on your branch.

Branch name can be master or main or another branch name.

git pull -rebase origin <your-branch-name>
git push origin <your-branch-name>

5. Fix 4 — Git error: failed to push some refs to

You can try force push also. But not sure this will work always. If there are no conflicts, this will work.

git push -f origin master

6. Fix 5 — Git error: failed to push some refs to

the last solution is below. That deregister the current local repo and re-register with the remote.

rm -rf .git

git init

git remote add origin https://github.com/JavaProgramTo/Kotlin-Demo.git

git remote -v (to see the remote origin)

git add -A(add all files)

git commit -m 'Added my project'

git pull --rebase origin master

git push  origin master

7. Conclusion

In this article, We’ve seen how to fix the git error — failed to push some refs to.

1. Overview

Working with Git is an essential part of any developer’s day-to-day work. However, in the beginning, it could be overwhelming, and error messages might not be obvious. One of the most common issues people receive when starting working with Git is the error with refspec:

error: src refspec master does not match any 
error: failed to push some refs to 'https://github.com/profile/repository.git'

In this tutorial, we’ll learn the reasons for this issue and how to resolve and mitigate it.

2. The Description of a Problem

Many of us have seen the refspec error message at least once within the console. This error occurs on pushing to a remote repository. Let’s try to understand what this line exactly means:

error: src refspec master does not match any

Simply put, this error message tells us that we don’t have a branch we want to push, which is the main reason for this error.

3. Going Through the Steps

The refspec error might appear when we cloned an uninitialized repository and tried to push a local repository. This is how Git services explain setting up a local repository. Here are the steps from GitHub:

$ echo "# repository" >> README.md
$ git init
$ git add README.md
$ git commit -m "first commit"
$ git branch -M main
$ git remote add origin https://github.com/profile/repository.git
$ git push -u origin main

We’ll refer to these steps in the paragraphs below.

4. Pushing a Non-existent Branch

Let’s go step by step through the instruction GitHub provides us.

4.1. Initializing a Repository

The first line creates a README.md file:

$ echo "# repository" >> README.md

The following command will initialize a local Git repository:

$ git init

This command may issue the following message:

hint: Using 'master' as the name for the initial branch. This default branch name
hint: is subject to change. To configure the initial branch name to use in all
hint: of your new repositories, which will suppress this warning, call:
hint: 
hint: 	git config --global init.defaultBranch <name>
hint: 
hint: Names commonly chosen instead of 'master' are 'main', 'trunk' and
hint: 'development'. The just-created branch can be renamed via this command:
hint: 
hint: 	git branch -m <name>

In 2020 GitHub changed the default name of the branch created in a new repository from “master” to “main.” The same changes have happened on GitLab. It’s still configurable on GitHub, GitLab, and Git.

4.2. The First Commit

The subsequent two commands create a commit in our local repository:

$ git add README.md 
$ git commit -m "first commit"

4.3. Renaming a Branch

The interesting thing happens in the following line:

$ git branch -M main

This line is responsible for renaming our current local branch to “main.” This happens because of the reason explained in the hint message. This line will rename our default branch to match the default branch name on our remote repository.

The steps provided by GitHub will contain the default name configured on the platform. However, this remaining became one of the most common reasons behind the refspec error. Let’s see what will happen if we have a local repository that uses “master” as a default branch and a remote which uses “main.” We’ll skip the renaming step for this example and go straight to setting up our remote repository:

$ git remote add origin https://github.com/profile/repository.git

4.4. The Problem

We’ll start experiencing problems on this line:

$ git push -u origin main

Let’s review this line and consult the documentation to understand what’s happening. This line pushes the changes from a branch, in this case, “main,” to a remote repository we configured in the previous line.

That means that the local repository should contain the “main” branch. However, the default local branch name is set to “master,” and we didn’t create a newmain branch or rename the “master” branch. In this case, Git won’t be able to find themain branch to push, and we’ll get this error message:

error: src refspec main does not match any
error: failed to push some refs to 'origin'

Now this message makes more sense. As mentioned previously, this error tells us we don’t have the “main” branch. There is a couple of ways to resolve this problem. The first one is to rename our currentmaster branch to “main”:

$ git branch -M main

After the rename operation, we can repeat the push command, which will work without problems. At the same time, we can change the name of the branch we want to push frommain to “master” or any name we use as a default in our local repository. The following command will create a “master” branch on the remote repository:

$ git push -u origin master

And lastly, if we want to stick to the “master” name in our local repository and the “main” in our remote repository, we can explicitly set the upstream branch with the following command:

$ git push -u origin master:main

The flag -u will also set the upstream connection between the localmaster branch and the remote “main branch. It means that the next time we can use the command without explicitly identifying the upstream branch:

$ git push

5. Pushing an Empty Repository

Another cause for this problem is pushing an empty repository. However, the reason behind it will be the same – trying to push a branch that doesn’t exist. Let’s assume that we’ve created a new repository. The branches are appropriately named. We added a file but didn’t commit it:

$ echo "# another-test-repo" >> README.md
$ git init
$ git add README.md
$ git branch -M main
$ git remote add origin https://github.com/profile/repository.git
$ git push -u origin main

Although we’re on themain branch, technically, it doesn’t exist. For a branch to be created under .git/refs/heads, it should contain at least one commit. Let’s ensure that the folder .git/refs/heads in our repo is empty at this point:

$ ls .git/refs/heads 

This command should show us an empty folder. Thus, as in the previous example, we’re trying to push a branch that doesn’t exist. A single commit will fix the problem. It will create a branch and make it possible to push the changes:

$ git commit -m "first commit"
$ git push -u origin master

6. Conclusion

Creating and initializing a new local repository isn’t a challenging task. However, skipping steps or blindly following instructions may result in errors. These errors sometimes are not explicitly understandable, especially for new Git users.

In this article, we’ve learned how to deal with refspec errors and what is the reason behind them.

Содержание

  1. Fix git “tip of your current branch is behind its remote counterpart” — 4 real-world solutions
  2. What causes ”tip of your current branch is behind”?
  3. How can you get your local branch back to a state that’s pushable?
  4. 1. No rebase(s): merge the remote branch into local
  5. 2. Remote rebase + no local commits: force git to overwrite files on pull
  6. 3. Remote rebase + local commits: soft git reset, stash, “hard pull”, pop stash, commit
  7. Options to “soft reset”
  8. Save your changes to the stash
  9. Run the hard pull as seen in the previous section
  10. Un-stash and re-commit your changes
  11. 4. Remote rebase + local commits 2: checkout to a new temp branch, “hard pull” the original branch, cherry-pick from temp onto branch
  12. Create a new temp branch
  13. Go back to the branch and “hard pull”
  14. Cherry-pick the commits from temp branch onto the local branch
  15. Cherry-pick each commit individually
  16. Cherry-pick a range of commits
  17. Get The Jest Handbook (100 pages)
  18. Hugo Di Francesco
  19. Get The Jest Handbook (100 pages)
  20. JavaScript Object.defineProperty for a function: create mock object instances in Jest or AVA
  21. Pass cookies with axios or fetch requests
  22. Ошибка git failed to push some refs . Updates were rejected because a pushed branch tip is behind its remote + non-fast-forward
  23. Primary tabs
  24. Forums:
  25. Причина
  26. Решение (безопасное для описанное ситуации)
  27. Ошибки Git
  28. fatal: No such remote ‘origin’
  29. Что такое «git push problem: non fast forward»

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

Источник

Ошибка git failed to push some refs . Updates were rejected because a pushed branch tip is behind its remote + non-fast-forward

Primary tabs

Forums:

ВНИМАНИЕ: не делайте в этой теме резких движений! Есть риск потерять данные.

git error: failed to push some refs to
git Updates were rejected because a pushed branch tip is behind its remote

Вообще речь идёт об ошибке вида:

Предположим, что вы находитесь в ветке branch0.

Такая ошибка может возникать в ответ на

— то есть на попытку отправить изменения на удалённый сервер.

но проблема с git push всё равно сохраняется.

Причина

Проблема в том, что ваш git push пытается отправить на удалённый сервер не только текущую ветку branch0, но и вообще все ветки в которых произошли изменения на вашей машине, при этом в удалённом репозитории имеют коммиты более поздних изменений от других разработчиков — о чем и собственно и сообщает на git, не давая сделать push в эти ветки.

Решение (безопасное для описанное ситуации)

Если написано, что:

Updates were rejected because a pushed branch tip is behind its remote

То это значит, что какие-то из ваших веток не обновлены, в моё случае это 2 ветки (см .сообщение выше):

Далее в качестве решения есть два пути:

    переключиться во все эти «устаревшие» ветки и сделать

— но лучше другой способ:

Источник

Ошибки Git

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

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.

Источник

Что такое «git push problem: non fast forward»

Данная мини-заметка в первую очередь является ответом на вопрос. Так как мой аккаунт read-only, то вот такой вот способ ответа. «А жизнь-то налаживается!» ©

Первый вывод после прочтения вопроса и ответов — не делайте так, как предложил defuz. Он не понимает суть проблемы, и если вы сделаете как им предложено — скорее всего, вы потеряете данные.
Второй: alekciy тоже не совсем прав, но тут шансов на потерю данных гораздо меньше. Почти никаких.
Ну и третий: блин, ну когда же люди поймут, что владеть используемым инструментом это реально необходимо? Читайте документацию!

Скажу сразу, многие детали и «внутренности» работы git’а опущены либо упрощены, но не в ущеб пониманию. Именно появление понимания и цель статьи, и если оно у вас уже есть, и вы уверены, что оно верное 🙂 — то ничего нового для вас тут не будет. Если же понимания пока нет — то поехали!

Для начала, надо выяснить, что такое fast-forward. Это просто один из вариантов (методов, стратегий) выполнения операции merge. Он возможен только в том случае, если текущий коммит (тот, к которому будет происходить слияние, обозначим его А), является предком «сливаемого» коммита (тот, с которым будет происходить слияние, обозначим его Б). Графически это выглядит так (х — просто другие, не важные нам коммиты):

Если история коммитов выглядит вот так:

то выполнить слияние от А к Б методом fast-forward не получится — А не является предком для Б. Точно так же, в этой ситуации нельзя выполнить слияние с помощью метода fast-forward от Б к А. Но, любое из слияний «от В к А» и «от В к Б» — можно, и при выполнении одного из этих слияний git (по умолчанию) будет использовать именно метод fast-forward.

Теперь следующая вещь, которую необходимо уяснить — это что такое push. Ключевых моментов в этой операции два. Первый: это не просто передача данных о ваших коммитах «на ту сторону», а ещё и обязательная последующая операция merge «на той стороне». И второй: «та сторона» для операции merge будет использовать только fast-forward. Почему всё именно так?

Ну, с первым очевидно. Чтобы поместить что-то в историю, нужно создать новый объект-коммит в истории (который будет потомком текущего) и изменить указатель на последний коммит в ветке (который называется HEAD), на этот новый коммит. По большому счёту, для этого есть только две операции: commit и merge (слияние, которое в большинстве случаев будет приводить к появлению нового коммита). Очевидно, на сервере коммиты «вручную» никто не делает. И если на сервер просто передать вашу историю (новые коммиты), то это никак не изменит HEAD. Так что делать merge с вашими новыми коммитами сервер просто вынужден — у него просто нет другого варианта изменить HEAD.

Второй момент тоже не сложный, но не сразу очевиден. Почему сервер, делая merge, использует только fast-forward? Ведь есть же куча других замечательных методов, тот же octopus, но их сервер не использует. Почему? Всё очень просто: fast-forward это единственный вариант, который не порождает новых коммитов (помимо тех, что уже добавили вы). Ведь сервер не может порождать новые коммиты сам, так как для создания коммита git требует указания автора — сервер может только хранить ваши коммиты. И что ещё главнее — этот метод (fast-forward) при слиянии никогда не даёт конфликтов: просто по природе самого метода fast-forward конфликты при слиянии не возможны. Для сервера это важно, так как в случае возникновения конфликта решать его будет некому. На то он и конфликт, чтоб его решал человек, потому как компьютер разобраться не смог.

Понимание этих базовых вещей должно быть достаточно для «прояснения» ситуации. Но как она может возникнуть?

Всё очень просто: репозитарий используется более чем одним человеком (или одним, но на нескольких машинах), или же в локальном депозитарии был сделан rebase. В любом из этих вариантов возможно возникновение того, что отображено на второй картинке. И раз уж у вас такая ситуация возникла (то есть вы сделали «git fetch», и увидели, что всё так и есть), то давайте договоримся, что на сервере HEAD указывает на А (remotes/origin/master), на у вас локально — на Б (master).

Как же решить возникшую проблему? Вариантов два, и оба они приводят к тому, что А будет сливаться с таким коммитом (назовём его Х), для которго А будет предком. Как же этого добиться?

Вариант первый: слияние. Вам необходимо локально выполнить слияние вашего кода (Б) и того, который есть на сервере (А). Результатом слияния будет новый коммит в вашей локальной истории, тот самый Х — и сделать для него push сервер не откажется. Для убедительности — картинка:

Вариант второй: rebase. Rebase — это операция «переноса» части истории таким образом, чтобы изменить «корень» ветки, но не изменить саму ветку. Для наглядности — снова картинка. Начальное состояние — всё тот же рисунок 2, а состояние после rebase будет вот таким:

В полученном результате роль коммита Х выполняет Б — но это уже другой Б, скажем так, Б’. В этом легко убедиться, посмотрев commit-id до rebase и после. Но как уже было сказано, сама ветка (то есть содержимое коммитов, её составляющих), не поменяется — поменяются только commit-id. Но цель достигнута — можно делать push.

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

Есть и третий вариант решения, и именно его предложил defuz — forced push, например так:
git push origin +master

Он приведёт к тому, что сервер примет ваши коммиты, и безусловно изменит свой HEAD так, чтобы он указывал на последний из ваших коммитов — на Б. Таким образом, все «свои» коммиты, которых у вас нет (от В до А) сервер «забудет». Это и есть та самая потеря данных, о которой я говорил в начале. Тем не менее, иногда бывают случаи, когда это именно та операция, которая вам необходима. Но если у вас именно такой случай, и вы это понимаете, то вероятно эта статья вам уже давно не нужна.

Ну и чтоб уж расставить совсем все точки над и — по поводу ответа alekciy. Поскольку его вариант не использует forced push, то потери данных не будет. Но вполне очевидно, что после merge во-первых, нечего будет положить в stash (кроме новых файлов, которые ещё не под наблюдением git’а), а во-вторых, rebase уже не нужен (и если есть новые файлы — он обломится).

Надеюсь, этот материал прояснил происходящее и поможет решить возникшую проблему.

PS1: Для просмотра истории очень удобно использовать «gitk -a» (linux)
UPD: Terentich В Windows тоже прекрасно работает.
UPD: eyeofhell И в OSX это тоже работает 🙂
PS2: Stash (как впрочем и многие другие операции) — тема для отдельного разговора.

Источник

В предыдущей статье мы прошли базовые команды 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. Это базовый минимум, который поможет вам на первых порах не чувствовать себя растерянным, столкнувшись лицом к лицу с описанными сложностями.

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




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


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.

Понравилась статья? Поделить с друзьями:
  • Error failed to push some refs to git как исправить
  • Error failed to push some refs to git github com
  • Error failed to prepare transaction could not satisfy dependencies
  • Error failed to prepare transaction could not find database
  • Error failed to open герои 3