Git Magic
Paul Brown · 24/01/2024 · 2 min read
To pull in changes from just one file on another branch:
git checkout [branch_name] -- [file_path]
The -- relates to the UNIX shell, not Git, where -- means "everything that follows -- is a filename".
To rename an existing local branch. Switch to/checkout that branch and run:
git branch -m new-branch-name
# so, if you want to name a branch 'user-test-fix' the line would be:
git branch -m user-test-fix
To add parts of a file
git add -p <filename>
# so:
git add -p app/Models/Post.php
when git then asks Stage this hunk [y,n,q,a,d,/,j,J,g,s,e,?]?
These options are:
stage this hunk for the next commit
- n do not stage this hunk for the next commit
- q quit; do not stage this hunk or any of the remaining hunks
- a stage this hunk and all later hunks in the file
- d do not stage this hunk or any of the later hunks in the file
- g select a hunk to go to
- / search for a hunk matching the given regex
- j leave this hunk undecided, see next undecided hunk
- J leave this hunk undecided, see next hunk
- k leave this hunk undecided, see previous undecided hunk
- K leave this hunk undecided, see previous hunk
- s split the current hunk into smaller hunks
-
e manually edit the current hunk
- You can then edit the hunk manually by replacing +/- by #
- ? print hunk help
Get the number of files changed between the current branch and a given branch
git --no-pager diff --shortstat <GIVEN BRANCH NAME>
# so:
git --no-pager diff --shortstat my-feature-branch
How to undo changes from a given commit
To undo the changes to a file from a given commit id, run the following:
git restore --source <commit-id>^ --<path/to/file>
The caret (^) symbol refers to the parent of the specified commit, effectively pointing to the state before the commit.
How to create a branch and switch to it
git checkout -b my-new-feature
This command does two things: it creates the branch "my-new-feature" and switches your working directory to this new branch.
How to make an empty commit
Sometimes it's useful to push an empty commit. You can use the --allow-empty
flag for this:
git commit --allow-empty -m "Trigger CI"
Discussions
Login to Post Comments