Is Git checkout without merging a common file possible? - git-checkout

My goal involves having a file with the same name but different implementations in different branches. For example, I want to develop in a branch with verbose mode and another that works silently. Or, one branch uses a list, but the other uses a hash. Similar to prior question.
In my case, the changes are in a file with the same name. Unfortunately, checkout from one branch to the other merges the files of the same name (content?). In that case, the release version inherits the verbose print statements I had hoped to keep separate.
I learned and succeeded in using stash save; checkout; (edit other branch, add, commit); checkout back; and stash apply (to erase merge changes caused by checkout). It works, but the manual's examples (interrupted workflow, partial commits) suggest this is not the intended workflow. Creating an orphan branch for verbose destroys the history. Is there another way to switch between branches without carrying unintended changes to files with the same name?
Update I can't replicate the behavior any longer, despite seeing it five times before submitting here. It used to show the text below. But, I guess this question should be closed.
$ git checkout master
M Test.java
Switched to branch 'master'

I think the following command is what you are looking for:
git update-index --assume-unchanged <file>
To undo run:
git update-index --no-assume-unchanged <file>

From ""Difference Between 'assume-unchanged' and 'skip-worktree'", I would go with:
git update-index --skip-worktree -- a file
git update-index --no-skip-worktree -- a file
skip-worktree is useful when you instruct git not to touch a specific file ever.
That is handy for an already tracked config file.

Related

How to check file/directory changes of a multi directory git repository between two git commits?

How to check file/directory changes of a multi directory git repository between two git commits?
In linux/bash we need to findout changes to a directory of multi-directory(e-store) git repository, say it has inventory-dir, order-dir, purchase-dir etc.., directories.
So basically after we do git pull we want to know in which folderes/directories files changes were made between present changes & last commit, and based on that output take an appropriate call.
We tried to use below git commands, but not sure that's the right way to proceed.
git diff inventory-dir
git log --name-status -2 inventory-dir
You might be looking for
git diff #^1
but to reduce the result to a tractable list of just file names you could add
--stat
or
--compact-summary
or merely
--name-only
Of those, my favorite is --compact-summary — it's tremendously informative while confining the output to one line per file. So then if you have a top-level directory myDirectory to which you wish to confine your attention, you would say
git diff --compact-summary #^1 -- myDirectory

Why does Git prints an incorrect diff at the bottom of a commit message?

I use a pre-commit hook to run Prettier formatter against my HTML documents:
#!/bin/sh
# Retrieving a list of the staged files
stagedFiles=$(git diff --staged --name-only)
# Format staged files automatically
echo "Formatting with Prettier..."
npx prettier --write $stagedFiles
git add $stagedFiles
The formatting successfully applies right after I enter git commit command and right before my configured editor opens the commit message. According to commit.verbose setting, Git appends there a diff showing what is to be committed, but this diff does not take into account changes made by Prettier — it demonstrates the unformatted version of my code. If I then abort the commit (leaving the message empty), I can see that no unstaged changes are in the repository; it means that all formatting modifications had been properly staged during execution of the pre-commit hook. Moreover, if I write some text to the message and complete the commit without aborting, the resulting snapshot does contain all formatting that was missing in the diff.
I finally concluded that the diff lies. But does a solution exist?
Git for Windows version: 2.33.0
OS: Windows 10 21h1 x64
The short answer is : the pre-commit hook is not intended to modify files to be committed.
You can relate to the following rationale : the content you commit will be the exact content you could review and test before running git commit.
(the technical reason is : git creates the tree -- the content for the commit -- that will be used before calling the pre-commit hook)
A pre-commit hook should be written as a read-only action, which may prevent the commit from happening, e.g : if a file is not formatted correctly, reject the commit with a message "please run format.sh before committing".
Of course, you could work your way around that, but, FWIW, I advise you to follow this rule.

Git: How to update the master branch and switch to it in one step?

I'm working on a project that's hosted on GitLab and uses issue/work branches and merge requests to bring that work into the master branch when it's done. Usually I work on issue branches. When it has been merged by GitLab, I need to switch to the current master to do a build, locally.
My workflow is this:
Switch to master
Pull from remote (--ff-only)
Remove stale remote tracking branches
Also remove their local tracking branches
There's also a client-side tool that watches the code directory and updates some files (CSS, JavaScript). When it sees a change in the first step (switch to master), I first need to wait for it to finish before going on (to avoid confusion). If there's a difference between the issue branch and the old master, there's a good chance that the difference will disappear when updating master (as that issue branch is now merged).
I'm looking for a way to switch to the already-updated master branch in one step. How can I do that with a git command? I want to bundle up all these actions in a batch file to avoid repeating all those manual steps in TortoiseGit every time.
This question is different from the suggested one in that the local master branch already exists. I'm not switching to a new branch from a remote, but to a branch that already exists and it just behind the remote.
TL;DR
Unless you write your own script (or use a Git alias to run multiple commands and/or scripts), you can't get this down to a single command, but you can get closer. See the long section for many caveats: the biggest one is that it assumes you're not already on master when you do it. If you are, the second step won't work (see the long section for what will).
git fetch -p &&
git fetch . refs/remotes/origin/master:refs/heads/master &&
git checkout master
will take care of the first three bullet points—not in the same order—with a single work-tree-updating git checkout step.
(Note that I split this into three lines for posting purposes, but as a Git alias using !, it's really all one big line.)
Long
There are several approaches, including actual, literal batch files (shell scripts on Unix-like systems, or .BAT files, or whatever) and aliases (as suggested by Joe in a comment).
There's also a client-side tool that watches the code directory and updates some files ...
This is ... not necessarily a good idea, let's say. :-)
While git checkout master runs, it's changing various files. Let's say that for some reason, it changes one of several files that the watcher watches, but then it pauses for a few minutes (or seconds, or microseconds, or some unit of time anyway). While it is paused, the watcher tries to combine the multiple files that are now out of sync.
Maybe this is OK and self-correcting when Git un-pauses and finishes the checkout—but it might be better if you could make sure the update only happens when the checkout is done.
That aside, let's take a look at this particular series of commands, and be very concrete about which Git command you're using:
Switch to master
I assume this is git checkout master.
Pull from remote (--ff-only)
I assume this is git pull origin master --ff-only or perhaps just git pull --ff-only.
Remove stale remote tracking branches
I'll assume for now that this is git fetch --prune. If you are doing something different, you should include that in your question.
Also remove their local tracking branches
If I understand what you mean, this requires a script. Note that this is somewhat dangerous: suppose you have your own branch X on which you are doing development. This X is not related to anyone else's X. Then someone creates their own X—using the same name—and sends it to the machine from which you git fetch. You now have origin/X. Then they delete their X (because they're done with it) and delete origin/X. If you now have your script delete your X, because origin/X went away, that would probably be bad.
If you only delete your X when it explicitly has origin/X set as its upstream, this particular case won't occur—but if someone accidentally deletes your origin/X thinking it was their origin/X, the same problem crops up again, and this time that particular protection does not work.
Anyway, with all that aside, let's look at the variant I suggested above.
git fetch -p
This updates all your origin/* names,1 including origin/master, without affecting any files in your working tree. The -p is short for --prune, so it deletes any origin/* names that no longer have a corresponding branch in the Git over at the URL stored under the name origin.
1I assume here that you have only one remote, which is named origin. If you have more than one remote, use git fetch origin -p to make sure you're fetching specifically from the one named origin. I also assume you have not configured your Git to be a single-branch clone.
git fetch . refs/remotes/origin/master:refs/heads/master
This rather magic-looking command tells your Git to call itself up. That is, the special name . refers to your own Git repository. We are using this to trick your Git into fast-forwarding your master branch based on your updated origin/master. The final argument is what does this: we say to your Git: OK, my Git, when you talk to that other Git, find out what commit its refs/remotes/origin/master identifies. Then, if that's a fast-forward operation, update my refs/heads/master to match.
Of course, the "other Git" your Git is talking to is itself—so this means fast-forward my master from my origin/master.2 It's roughly equivalent to:
git checkout master && git merge --ff-only origin/master && git checkout -
except that no actual checking-out occurs: no files in your work-tree change.
2You might wonder why some of these use origin/master and some use refs/remotes/origin/master. The longer one is just the full spelling of the name. When using git fetch, it's wise to use the full spellings. In fact, in general, in scripts, you might want to use full spellings more often, but specifically git fetch can become confused if the other Git you talk to accidentally has both a branch and a tag with the same name, for instance. So I'm illustrating the full names with git fetch. You'll use it to talk to your own Git, so if you don't mix up your tags and branch names or otherwise create ambiguity, you won't actually need the full names. But it's a good habit with git fetch.
The above fails if you're on your master
The git fetch command will refuse to fetch into whatever branch name you have checked out. So if you are on master, this git fetch . trick will fail.
In a way, this is OK! If you are on your master, what you should do instead is run:
git merge --ff-only origin/master
or anything equivalent. This is what your git pull --ff-only does: first it runs git fetch (without the -p and limited to fetching only the other Git's master); then it runs git merge --ff-only.
A more complete version
A more complete version of this sequence, then, is to first check: Which branch am I on? To do that, you can use either of two Git commands:
git rev-parse --abbrev-ref HEAD
or:
git symbolic-ref --short HEAD
Both of these will print master if you are currently on your own master branch. The difference between them is what they do if you're on no-branch-at-all: e.g., in the middle of a rebase, when you are in "detached HEAD" state. In that case, the second command—the git symbolic-ref one—errors out, while the first one just prints HEAD.
If you'd like to avoid doing any of this when in such a state, use the second command and check for failure. Otherwise, use the first one. I'll illustrate just the first one here:
if test $(git rev-parse --abbrev-rev HEAD) = master; then
# already on master - use alternative strategy
git fetch -p && git merge --ff-only refs/remotes/origin/master
else
# not currently on master: use fancy tricks to update
git fetch -p &&
git fetch . refs/remotes/origin/master:refs/heads/master &&
git checkout master
fi
The above, while untested, should be suitable as a shell script. If you have Git installed, you have the ability to run shell scripts—or you can turn the above into a very long Git alias, using ! and the appropriate set of semicolons.

How to show all the files that have been changed?

I am working on a feature branch that branched off a develop branch. Now that I am ready to do a PR I just want to check which files have been changed. What git command will list all the files changed against the develop branch?
Git's diff command with the --stat option will show you a list of changed files without the detailed contents.
Use it like git diff --stat origin/develop feature_branch
If you want really basic results then you can instead use the --name-only option to just see the filenames and nothing else.
If you just want to see the file names, you can do
git diff --name-only develop
git diff develop
Often the PR tool will show you the differences too.
For example if Microsoft's Dev Ops (previously known as VSTS) when creating a pull request you can see the changes (and commits) at the bottom.

Programmatically overwrite a specific local file with remote file on every git pull

I have an XML file that we consider binary in git. This file is externally modified and committed.
I don't care about who edited it and what's new in the file. I just want to have the latest file version at every pull. At this time, at every git pull I have a merge conflict.
I just want that this file is overwritten on every git pull, without manually doing stuff like git fetch/checkout/reset every time I have to sync my repo.
Careful: I want to overwrite just that file, not every file.
Thanks
I thought you could use Git Hooks, but I don't see one running before a pull...
A possible workaround would be to make a script to delete this file and chain with the needed git pull...
This answer shows how to always select the local version for conflicted merges on a specific file. However, midway through the answer, the author describes also how to always use the remote version.
Essentially, you have to use git attributes to specify a specific merge driver for that specific file, with:
echo binaryfile.xml merge=keepTheirs > dir/with/binary/file/.gitattributes
git config merge.keepTheirs.name "always keep their file during merge"
git config merge.keepTheirs.driver "keepTheirs.sh %O %A %B"
git add -A
git commit -m "commit file for git attributes"
and then create keepTheirs.sh in your $PATH:
cp -f "$3" "$2"
exit 0
Please refer to that answer for a detailed explanation.
If the changes to your files are not actual changes, you should not submit them. This will clutter your version history and cause numerous problems.
From your statement I’m not quite sure which is the case, but there are 2 possibilities:
The file in question is a local storage file, the contents of which are not relevant for your actual sourcecode. In this case the file should be part of your .gitignore.
This file is actually part of your source and will thus have relevant changes in the future. By setting up the merge settings like you are planning to do, you will cause trouble once this file actually changes. Because merges will then be destructive.
In this case the solution is a little bit more complicated (apart from getting a fix for the crappy tool that changes stuff it doesn’t actually change …). What you are probably looking for is the assume unchanged functionality of git. You can access it with this command:
git update-index --assume-unchanged <file>
git docu (git help update-index):
You can set "assume unchanged" bit to
paths you have not changed to cause git not to do this check. Note that setting this bit on a path does not mean git will check the
contents of the file to see if it has changed — it makes git to omit any checking and assume it has not changed. When you make changes
to working tree files, you have to explicitly tell git about it by dropping "assume unchanged" bit, either before or after you modify
them.

Resources