Pagine

Showing posts with label git. Show all posts
Showing posts with label git. Show all posts

Monday, 12 June 2017

How to resolve some git errors

This post will help the readers a lot because the errors mentioned can occur very frequently.

Remote origin already exists

This error occurs when you already have a remote repository specified and the remote origin removed and added. Example:
$ git remote rm origin
$ git remote add origin https://gitserver.com/scm/myproject.git

Git push fails with rejected error

This error occurs because you didn't execute git pull before git push. Example:
$ git pull
$ git push

Git push fails caused by "fatal: The remote end hung up unexpectedly"

This one is common and you should check whether your remote URL is correct and Git has access to the remote repository. I suggest add (if not already setted) the origin; else set the correct origin.

Restoring a changed file to its last committed state

Run git checkout followed by the filename and you will lose your changes. However, this will be restored as a clean copy of the file. Example:
$ git checkout fileName

Unstaging a file

Did you run git add too soon? Run git reset HEAD followed by the filename to unstage it:
$ git reset HEAD fileName

How to fix the most recent commit message

The –amend option will edit a commit message:
$ git commit --amend
The editor will open to edit the last message.

Reset the most recent commit

There are two ways to do this: with and without your changes.
1) Without losing changes:
$ git reset HEAD~1
2) By losing changes:
$ git reset --hard HEAD~1

I found a bug after releasing the product but it was in the commit that I did a long time ago

In this case, you should not use git reset because it rewrites the history and the product is already released. Therefore, you should make a commit that reverts the buggy commit and pushes it to
share with your colleagues:
$ git revert 17cc9433abcf23c42aef6b9aad24b5fcfc353f7c

There are many garbage files in the working directory. How to delete them?

In this situation, the files are not maintained by Git, so you have to use git clean:
1) To check the files that will be removed
$ git clean -n
2) Now remove them:
$ git clean -f

I think I made a mistake while resolving conflicted files. How do I restore it to the state just after git merge?

To do this, you can use git checkout:
$ git checkout --merge fileName

Gitindex file is corrupt

No need to worry. This one is rare but can be annoying! Git will display the error as "bad index file sha1 signature: fatal: index file corrupt". You just have to remove the backup index file; remove it, and then reset the repository:
$ mv .git/index .git/indexOLD

$ git reset

Git refuses to start a merge/pull command.

The typical error messages look like this:
  • Error: The myfile.txt entry is not up to date; it cannot be merged.
  • Error: The myfile.txt entry will be overwritten by the merge command.
To resolve this, perform the following steps:
1. Stash the changes or throw them out:
$ git stash save "a message"
$ git checkout myfile.txt
2. Check that the changes are staged:
$ git status
3. Bring the changes from the remote repository:
$ git pull
4. Repopulate if you made a stash:
$ git stash pop

Friday, 9 June 2017

How to use git bisect

The git bisect command allows you to run a binary search through the commit history to find a commit that has an issue. For example, you pulled the last commits and the website isn't working anymore. You know that before the last pull everything was okay. So you have to find the commit ID before it crashes and the last ID after the pull:
$ git bisect start
$ git bisect bad <commit_id_after_pull>
$ git bisect good <commit_id_before_pull>
Now, the bisecting loop begins and Git will check for an alternative commit.
Reset the given commit and tell Git whether the website is working:
$git bisect <bad_commit_id>
Git will search again and again to find which commit crashed the website:
$ git show <commit_id>
Instead of trying to locate a bug inside all your files, you have a shortened list of files.

How to reset a git commit via bash script 

If you don't want to reset to a given commit and test your software, you can create a bash script and tell Git to use it. The script has to return 0 if the condition is fulfilled, and nonzero if it isn't.
check_file.sh

#!/bin/bash
FILE=$1
If [ -f $FILE];
then
    exit 0;
else
    exit 1;
fi
Now it's time to run git bisect to specify the last 10 commits:
$ git bisect start HEAD HEAD~10
$ git bisect run ./check_file.sh MyFile.java

Bisect algorithm

The algorithm used by git bisect always returns the commit that is at the middle position of the array.
In the following diagram, you will see how the algorithm found the good commit in three steps:
  1. The Commit6 option is selected by Git. After checking it, you tell Git that it's good.
  2. Git reduces the array because if Commit6 is good, then every commit between Commit1 and Commit6 is good too.
  3. Then Git asks you to test Commit9, and you say that it's good too.
  4. So the error can only be inside Commit10 and Commit11.

Thursday, 8 June 2017

How to solving merge conflits with git

When you are working with several branches, a conflict will probably occur while merging them. It appears if two commits from different branches modify the same content and git isn't able to merge them. If it occurs, Git will mark the conflict and you have to resolve it.
For example, Developer1 modified the myfile.txt on a feature branch and Developer2 has to edit it on another branch. When Developer2 merges the two branches, the conflict occurs.
Git will tell you to edit the file to resolve the conflict. In this file, you will find the following:
<<<<<<< HEAD
Changes from Developer2
=======
Changes from Developer1
>>>>>>> 5df2fcdc89e0a33fcf8cbbbbd89cb8eabbdb61b7
The <<<<<<< characters indicate the start of the merge conflict, the ====== characters indicate the break points used for comparison, and >>>>>>> indicate the end of the conflict.
To resolve a conflict, you have to analyze the differences between the two changes and merge them manually. Don't forget to delete the signs added by Git. After resolving it, simply commit the changes.
If your merge conflict is too complicated to resolve because you can't easily find the differences, Git provides a useful tool to help you.
The "git diff" and "git mergetool" help you to find differences. Other tools to visually compare and merge files are:

Wednesday, 7 June 2017

How to configure git alias

Git allows you to use aliases for command lines. The alias concept is similar to linux. Setup git alias is very fast: in your $HOME edit the .gitconfig file and add the following text:
[alias]
    l = log --pretty=format:"%C(yellow)%h\\ %ad%Cred%d\\ %Creset%s%Cblue\\ [%cn]" --decorate --date=short
Now if you run the following command:
$ git l
see the output of alias "l". Now you are ready to create a new customer alias or add other aliases available in web.

Examples of aliase are:

    l = log --pretty=format:"%C(yellow)%h\\ %ad%Cred%d\\ %Creset%s%Cblue\\ [%cn]" --decorate --date=short
    a = add    
    ap = add -p
    c = commit --verbose
    cm = commit -m
    cam = commit -a -m
    d = diff
    ds = diff --stat
    dc = diff --cached
    s = status -s
    co = checkout
    cob = checkout -b
    cmp = "!f() { git add -A && git commit -m "$@" && git push; }; f"
    la = "!git config -l | grep alias | cut -c 7-"

Tuesday, 6 June 2017

How to rewrite commit history with git

Someone accidentally commits a huge binary file with a thoughtless git add ., and you want to remove it everywhere. Perhaps you accidentally committed a file that contained a password, and you want to make your project open source. filter-branch is the tool you probably want to use to scrub your entire history. The --tree-filter option runs the specified command after each checkout of the project and then recommits the results. 

Examples:

1) To remove a file named mypasswords.txt from your entire history, you can use the --tree-filter option to filter-branch: 
$ git filter-branch --tree-filter 'rm -f mypasswords.txt' HEAD
Rewrite 802a096d79b9b5872544a6b35d6a52cbdf55274a (21/21)
Ref 'refs/heads/master' was rewritten 
2) If you want to remove all accidentally committed editor backup files, you can run something like
$ git filter-branch --tree-filter 'rm -f *~' HEAD.

--index-filter option

The --index-filter is another option similar to the tree filter but does not check out the tree, which makes it much faster.
$ git filter-branch --index-filter 'git rm --cached --ignore-unmatch myfilename.txt' HEAD
The --ignore-unmatch option is needed because "git rm" will fail if the file is absent from the tree.

Monday, 5 June 2017

Canceling a commit with git

The git revert command allows you to cancel your last unpushed commit. The type of cancel is only logical because Git doesn't drop phisically the commit but it creates a new commit that executes the opposite of your commit. A pushed commit is irreversible, so you cannot change it.

Example

The following example illustrates how to remove last pushed commit. First step, let's have a look at the last commits:
$ git log
commit dc2d9f3deda6f49902c1879b7b861fac51683865
Author: infoamodomio <infoamodomio@infoamodomio.com>
Date:   Thu May 25 12:19:01 2017 +0200
    Added a new file
Second step, We want to cancel the dc2d9f… commit:
$ git revert dc2d9f
Canceling this commit isn't necessary to enter the full commit ID, but just the first characters. Git will find it, but you will have to enter at least six characters to be sure that there isn't another commit that starts with the same characters.

Thursday, 1 June 2017

How to edit a commit with git

It is possible three actions to edit a commit:
  1. Change the comment;
  2. Add one or more files in a commit;
  3. Remove one or more files in a commit.

Examples

1) If you want to edit the description of your last commit, use the following line: 
 $ git commit --amend
2) Let's suppose that your last commit contains buggy code; you can specify that your changes on the file are part of the last commit:
 $ git add file.txt
 $ git commit -v -amend
3) Now I want to remove a file I included accidentally in the last commit (because this file deserves a new commit):
 $ git reset HEAD^1 file.txt
 $ git commit --amend -v
 $ git commit -v file.txt

Monday, 29 May 2017

How to use the git reset command

The git reset command will allow you to go back to a previous state (for example, commit). The git reset command has three options (soft, hard, or mixed, by default). In general, the git reset command's aim is to take the current branch, reset it to point somewhere else, and possibly bring the index and work tree along. 
This means that
 git reset <paths>
is the opposite of
 git add <paths>
More concretely, if the master branch (currently checked out) looks like the first row (in the following figure) and you want it to point to B and not C, you will use this command:
 git reset B
The more options that you can provide on the reset command can be easily explained:
  • --hard: This option is the simplest. It will restore the content to the given commit. All the local changes will be erased. The git reset --hard command means git reset --hard HEAD, which will reset your files to the previous version and erase your local changes.
  • --mixed: This option resets the index, but not the work tree. It will reset your local files, but the differences found during the process will be marked as local modifications if you analyze them using git status. It's very helpful if you make some bugs on previous commits and want to keep your local changes.
  • --soft: This option will keep all your files, such as mixed, intact. If you use git status, it will appear as changes to commit. You can use this option when you have not committed files as expected, but your work is correct.
  • --merge: this option resets the index and updates the files in the working tree that are different between <commit> and HEAD, but keeps those which are different between the index and working tree (i.e. which have changes which have not been added). If a file that is different between <commit> and the index has unstaged changes, reset is aborted. In other words, --merge does something like a git read-tree -u -m <commit>, but carries forward unmerged index entries.
  • --keep: this options resets index entries and updates files in the working tree that are different between <commit> and HEAD. If a file that is different between <commit> and HEAD has local changes, reset is aborted.
The git reset command doesn't remove untracked files; use git clean instead.

Examples

1) Undo add:
 $ git add myfile.txt
 $ git reset
2) Undo a commit and redo:
 $ git commit -m "a comment"
 $ git reset --soft HEAD^
 $ git commit -a -c ORIG_HEAD
3) Undo a commit, making it a topic branch:
 $ git branch atopicbranch    
 $ git reset --hard HEAD~3  
 $ git checkout atopicbranch
4) Undo commits permanently:
 $ git commit ...
 $ git reset --hard HEAD~3
5) Undo a merge or pull:
 $ git pull
 Auto-merging ...
 CONFLICT (content): Merge conflict in ...
 Automatic merge failed; fix conflicts and then commit the result.
 $ git reset --hard
 $ git pull . atopicbranch
 Updating from 81683... to 43984...
 Fast-forward
 $ git reset --hard ORIG_HEAD
6) Undo a merge or pull inside a dirty working tree:
 $ git pull
 Auto-merging ....
 Merge made by recursive.
  ...                |   20 +++++----
  ...
 $ git reset --merge ORIG_HEAD
7) Interrupted workflow:
 $ git checkout feature ;
...developement...
 $ git commit -a -m "snapshot"
 $ git checkout master
...bug fixing...
 $ git commit 
 $ git checkout feature
 $ git reset --soft HEAD^ ;# go back to before bug fixing 
 $ git reset
8) Keep changes in working tree while discarding some previous commits:
 $ git tag 1.0
 $ git checkout -b branch1
... edit one o more files...
 $ git commit -m "a comment"
... edit one o more files...
 $ git checkout -b branch2
 $ git reset --keep 1.0
9) Split a commit apart into a sequence of commits:
 $ git reset -N HEAD^
 $ git add -p
 $ git diff --cached
 $ git commit -c HEAD@{1}
...
 $ git add file.txt
 $ git diff --cached
 $ git commit -m "a comment"

Friday, 26 May 2017

How to revert uncommitted changes with git

Let's suppose you edited a file on the production working directory, but didn't commit it. On your last push, you edited it, and the changes in production aren't needed anymore. So, your goal is to erase changes on this file and reset the file to the last committed version:
$ git checkout myfile.txt
This command is really nice if you want to restore a deleted file. You can also specify a commit pointer to use (useful if you stash [1] your changes):
$ rm myfile.txt
$ git checkout HEAD myfile.txt

Link

[1] Stashing your changes with git

Thursday, 25 May 2017

Stashing your changes with git

Git has a command that allows you to save the current state of the local working repository and go back to the last committed revision with git stash. This is really helpful when you have to develop an urgent fix. After this, you can restore the stashed changes and continue with your development.
To use this command, just execute the following command snippet:
$ git stash
Do your fix and then unstash edit:
$ git stash pop
Of course, you can do more with this command, such as save a list of stashes:
$ git stash
See the list of available stashes
$ git stash list
Apply the second stash
$ git stash apply stash@"1}
Delete a stash
$ git stash drop stash@"1}
Or delete all stashes
$ git stash clear
Let's suppose that your stash concerns a feature and you haven't created a dedicated branch for it. You can simply create a branch executing this command:
$ git stash branch mynewbranch
Remember this command is only for urgent fixes. If you want to add a new feature, you should use a new branch.

Wednesday, 24 May 2017

How to use the Cherry-pick git command

The cherry-pick git command lets you select a commit from a branch to apply it to another. The patch will be considered as a new commit in the selected branch.
The synopsis is:
git cherry-pick <id_commit>

Example

Let's try to understand this by exploring the following example: Developer1 creates the deve1 branch from master and adds a new file in it:
$ touch file.txt
$ git add file.txt
$ git commit -m 'add file.txt'
$ echo "new line" > file.txt
$ git commit -a -m 'updated file.txt'
As you can see, the developer creates the file.txt, adds it into Git, and commits it.Then he edits it and commits again. Now, let's see the commit history for this branch.
$ git log --oneline
5f8ed47 add file.txt
44c67b9 updated file.txt
Now, the developer will apply the first commit to the master branch:
$ git checkout master
$ git cherry-pick 44c67b9 
Let's imagine that the cherry-pick went wrong and the developer wants to abort it:
$ git cherry-pick --abort 
However, if you want to roll back a cherry-pick, you have two ways to do it:
  • If it's in a private branch, you can use the git rebase command.
  • If it's already in a public branch, use the git revert command.

Tuesday, 23 May 2017

Git - rebase vs merge

The merge command combines the changes from two branches. Instead the rebase command will take the changes from the first branch and apply them to the other branch.

The rebase command can be used if you want to get a feature (commits) from one branch to another and be sure to be close to the tip of the upstream branch. The command applies the changes from the branch called branch to the master branch.

The following examples show the usage of these two commands.

Example of merge:
$ git checkout mybranch
$ git merge master
Example of rebase:
$ git checkout mybranch
$ git rebase master
Note: In the rebase command do not merge commit.

Monday, 22 May 2017

How to create a patch with git

When a developer to make small fixes in a part of the project, but he didn't want to give him access to the repository. In this scenario the developer can create a git patch and send it via mail.
The following command will create .patch files per commit:
$ git format-patch origin patch-myproject.patch
Later you can send the patch by mail:
$ git send-email patch-myproject.patch
The patch can be imported with by executing this:
$ git apply /tmp/patch-myproject.patch
This command will apply the patch, but it doesn't create commits. So, to generate a series of commits, use the git am command:
$ git am /tmp/patch-myproject.patch

Friday, 19 May 2017

How to removing a file with git

If you don't want a file anymore, there are two ways to remove it. First mode: delete the file manually and commit the changes. This will delete the file locally and on the repository. Use the following command line:
$ rm myfile.txt
$ git commit -m 'delete the file with name: myfile.txt'
Second mode: delete the file only through git:
$ git rm --cached myfile.txt

Thursday, 18 May 2017

Git - fatal: refusing to merge unrelated histories

During a merge between two branches, if the following error is returned:
$ git branch
* master
develop
$ git merge develop
fatal: refusing to merge unrelated histories
Error redoing merge <version-id>
Retry with the following option:
$ git merge develop --allow-unrelated-histories
This option is used in a rare event that merges histories of two projects that started their lives independently.

Thursday, 11 May 2017

How to migrate a branch in a new git repository

For a reason with almost zero probability but not impossible you may find yourself in the situation of having to migrate a single branch between two git repositories.
Follow these steps for migration:
 git clone <old_repo>
 git checkout <branch_target>
 git remote set-url origin <new_repository>
 git push origin <branch_target>
Now clean your workspace, clone the old repository and remove branch target.
See the previous post "How to delete local and remote branches with git" for more details about delete of a branch.

Friday, 5 May 2017

How to rename a tag with git

The tag rename operation is not atomic but more steps are needed.
1) Create the tag with new name from old tag:
 git tag <new_tag> <old_tag>
2) Delete the old tag from local repository:
 git tag -d <old_tag>
3) Delete the old tag from remote repository:
 git push origin :refs/tags/<old_tag>
4) Push the local tag in remote repository:
 git push --tags
5) Lastly synchronize the tag list among local and remote repositories:
 git fetch -f

Thursday, 4 May 2017

How to create a branch with git

Create a local branch from current branch:
 git checkout -b <new_branch>
Otherwise you can use the following command:
 git checkout -b <new_branch> <start_point>
where the start point can be an other branch or a tag.
Now if the new branch must become a remote branch then use also the following command:
 git push origin <new_branch>

Wednesday, 3 May 2017

How to delete local and remote branches with git

Delete a local branch

Use the following command to delete a branch already merged:
 git branch -d <branch_name>
If the branch is not merged, use -D option to force the delete:
 git branch -D <branch_name>

Delete a remote branch

Use one of following commands to delete a remote branch (valid with git version 1.7 or later):
 git push origin --delete <branch_name>
or
 git push origin :<branch_name>

Monday, 1 May 2017

Git - How to get the branch remote list

Who knows the basic features of git know that branches can be of two types: local and remote.
Use the following command for the list of local branches:
 git branch
Instead use the option '-r' for remote branches:
 git branch -r
Finally the option '-a' for full list (local and remote branches):
 git branch -a