[System] You are a helpful assistant.

[User]
How can I revert a single file to a previous version? [duplicate]
This question already has answers here:

How can I reset or revert a file to a specific revision?

                                (37 answers)

Closed 10 years ago.
The community reviewed whether to reopen this question 7 months ago and left it closed:

Original close reason(s) were not resolved

Is there a way to go through different commits on a file.
Say I modified a file 5 times and I want to go back to change 2, after I already committed and pushed to a repository.
In my understanding the only way is to keep many branches, have I got that right?
If I'm right I'm gonna have hundreds of branches in a few days, so I'm probably not understanding it really.
Could anyone clear that up please?

[Assistant]
Let's start with a qualitative description of what we want to do (much of this is said in Ben Straub's answer). We've made some number of commits, five of which changed a given file, and we want to revert the file to one of the previous versions. First of all, git doesn't keep version numbers for individual files. It just tracks content - a commit is essentially a snapshot of the work tree, along with some metadata (e.g. commit message). So, we have to know which commit has the version of the file we want. Once we know that, we'll need to make a new commit reverting the file to that state. (We can't just muck around with history, because we've already pushed this content, and editing history messes with everyone else.)
So let's start with finding the right commit. You can see the commits which have made modifications to given file(s) very easily:
git log path/to/file

If your commit messages aren't good enough, and you need to see what was done to the file in each commit, use the -p/--patch option:
git log -p path/to/file

Or, if you prefer the graphical view of gitk
gitk path/to/file

You can also do this once you've started gitk through the view menu; one of the options for a view is a list of paths to include.
Either way, you'll be able to find the SHA1 (hash) of the commit with the version of the file you want. Now, all you have to do is this:
# get the version of the file from the given commit
git checkout <commit> path/to/file
# and commit this modification
git commit

(The checkout command first reads the file into the index, then copies it into the work tree, so there's no need to use git add to add it to the index in preparation for committing.)
If your file may not have a simple history (e.g. renames and copies), see VonC's excellent comment. git can be directed to search more carefully for such things, at the expense of speed. If you're confident the history's simple, you needn't bother.


[System] You are a helpful assistant.

[User]
Is there a command to undo git init?
I just Git init'ed a repos with a wrong user, and want to undo it.  Is there any command for this?  Do I actually have to go in and edit the .git directory?

[Assistant]
You can just delete .git.  Typically:
rm -rf .git

Then, recreate as the right user.


[System] You are a helpful assistant.

[User]
Why is .gitignore not ignoring .DS_Store? [duplicate]
This question already has answers here:

How do I make Git forget about a file that was tracked, but is now in .gitignore?

                                (35 answers)

Closed 6 years ago.

In this case I want to ignore the files iOS uses, and in particular this file
.DS_Store

I created a .gitignore file as such
touch .gitignore

and put in a  single line
/.DS_Store

I push to a bare repo which has a hook to checkout to a full repo.
The file keeps showing up in my full repo.

[Assistant] You can also remove committed .DS_Store files like this: git rm --cached .DS_Store


[System] You are a helpful assistant.

[User] git-show - Show various types of objects  --show-signature

[Assistant]
Check the validity of a signed commit object by passing the signature
to gpg --verify and show the output.


[System] You are a helpful assistant.

[User] git-log - Show commit logs  %<|( <M> )

[Assistant]
make the next placeholder take at least until Mth
display column, padding spaces on the right if necessary.
Use negative M values for column positions measured
from the right hand edge of the terminal window.


[System] You are a helpful assistant.

[User]
GIT vs. Perforce- Two VCS will enter... one will leave [closed]
Closed. This question needs to be more focused. It is not currently accepting answers.

Closed 10 years ago.

Locked. This question and its answers are locked because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.

So I'm in the process of getting GIT sold at work. First thing I need is to convince everyone that GIT is better at what they're already used to doing. We currently use Perforce. Anybody else go through a similar sale? Any good links/advice?
One of the big wins is that we can work with it disconnected from the network. Another win IMO is the way adds/checkouts are handled. More points are welcome! Also we have about 10-20 devs total.

[Assistant]
I use Perforce at work. I also use Git because I would still like some form of version control when I'm working on code and can't connect to the server. No, reconcile offline work just is not the same. Here is where I've found git to be a great benefit:

Branching speed - git takes a few seconds at most.
Conflicts - P4Merge's auto resolve destroyed a week's worth of work once. Ever since then I would rather resolve by hand when merging. When Git prompts me about a conflict, it is actually a conflict. The rest of the time, git resolves stuff correctly and I save heaps of time.
Keeping track of merges - If you have one branch that is continuously receiving merges from two other branches, you know what a headache this can be with perforce. With git, the headache is minimized because the result of a merge in git is actually a new commit which knows who its ancestors are.
Permissions - I have lost track of the number of times I've tried to work on a file but couldn't because it was not checked out in Perforce. If you worked with XCode (or any editor that does not have a solid Perforce SCM plugin) offline, you know how irritating this can get. I don't have to worry about that with Git. I make my changes. Git does not stop me and tracks them in the background.
Keeping the main tree tidy - With git, I can sort my commits and tidy the code up so that the history looks nice and tidy. None of that "checking in this file because it was supposed to be part of the previous checkin" rubbish. I squash commits like that, because they help nobody.
Stashing - Your perforce server needs to be version 2010.1 or newer to use the p4 shelve command.
Creating patches - Easy to do in git. Don't know if it is possible in Perforce without using the command line.
Mailing patches from the GUI - again, git wins here.
Disk space - With perforce, every branch is a copy. That means if your source tree is huge, your disk space gets eaten up fast. This is not even counting the additional space once you start building. Why even have a link between branches and disk space? With git, you can have 100 branches and only one branch at a time ever exists. If you specifically want to work on two versions simultaneously you can clone, do your work and then get rid of one clone if you want, without losing anything.
If you're on XCode4, perforce support has been dropped and git support is now built in. If you do cross platform work like I do, this matters a lot. With Visual Studio, you can use git extensions. With perforce, it's equally yuck on both OSes. Well, maybe a little more on mac now with XCode4 on the scene.
Finding the faulty checkin (or, git bisect rules) - Ever tried to do a binary search with perforce to figure out where a bug was introduced? Quite a hassle, yes? Even more of a hassle when there have been integrates from other branches in the middle. Why? Because there is no automation for such tasks. You need to write your own tool to talk to perforce and you usually don't have the time. With git, you give it the starting points (the "good" point and the "bad" point) and it automates the search for you. Even better, if you have a script that can automate the build and test process, you can hook git up to the script and the whole process of finding the checkin is automated. That is how it should be.
Tracking changes across refactors - Try splitting BigClass into SmallClass1 and SmallClass2. To Perforce, BigClass has now ceased to exist and two new classes (SmallClass1 and SmallClass2 have joined the source tree). To Perforce, there is no relation between BigClass and SmallClass1 and SmallClass2. Git, on the other hand, is smart enough to know that x% of BigClass is now in SmallClass1 and y% of BigClass is in SmallClass2 and that BigClass has ceased to exist. Now, from the point of view of someone who is reviewing changes across multiple branches, you tell me which approach you'd find more useful - Git's or Perforce's. Personally, I prefer Git's approach because it more accurately reflects the actual change in the code. Git is able to do this because it tracks content within the file and not the file itself.
Centralized or decentralized: Git is a DVCS system while perforce is centralized. A centralized VCS cannot be decentralized later, but a DVCS (especially git) can be centralized. There are several products that add very fine grained access control to git, if that is something the business needs. Personally, I would go with a system that gives me greater flexibility in the long term.
Branch mappings: If you want to do branching right in Perforce, you need to create a branch mapping. There are reasons for this, but they are tied to how Perforce conceptualizes a branch. As a developer, or a team, this simply means one more step in the work flow, which I do not consider efficient at all.
Sharing work between teams: With Perforce, you cannot break up a submission. Team A is working on feature A. Team B on feature B. Team C works on bug fixes. Now, Teams A & B have to fix a bunch of bugs in order to implement their features. The only thing is, they weren't so disciplined when committing their changes (probably because they're rushing to a deadline) and so their "bug fixes" are parts of larger submissions that also contain new stuff as far as version control on their branches are concerned. However, Team C is now doing a point release and would like to get the bug fixes from the other teams. If they were using Git, Team C could cherry pick the other teams' relevant changes, split them up and only take what they needed without worrying about introducing any partially implemented features. With Perforce, Team C can get the affected files, but would have to separate the relevant changes using a much more manual process.
Changing platform - If, for whatever reason in the future, you
 decide to change your platform of choice, with Perforce, you're at
 the mercy of Perforce.com and the availability of the tools for the
 platform of your choosing.
Changing to future amazing source control engine X - If you decide
 to change what you use for source control, extracting your source
 control history from Perforce and moving it to new system X is
 going to be a nightmare, because it is closed source and the best you
 can do is guess - just Google for Perforce to Git migration to get
 a sense of what I'm talking about. At least with Git, its open
 source, so it eliminates a lot of the guesswork involved.

Well, that's my 2 cents. In Perforce's defense, I gotta say their customer support rules and so does their Time Lapse View tool. I do not know how to get a time lapse view with git. But for the convenience and time saved, I'd go with git any day.


[System] You are a helpful assistant.

[User] git-config - Get and set repository or global options  format.pretty

[Assistant]
The default pretty format for log/show/whatchanged command.
See git-log , git-show , git-whatchanged .


[System] You are a helpful assistant.

[User] git-difftool - Show changes using common diff tools  --rotate-to=<file>

[Assistant]
Start showing the diff for the given path,
the paths before it will move to the end and output.


[System] You are a helpful assistant.

[User] git-update-ref - Update the object name stored in a ref safely  start

[Assistant]
Start a transaction. In contrast to a non-transactional session, a
transaction will automatically abort if the session ends without an
explicit commit. This command may create a new empty transaction when
the current one has been committed or aborted already.


[System] You are a helpful assistant.

[User] git-config - Get and set repository or global options  merge.autoStash

[Assistant]
When set to true, automatically create a temporary stash entry
before the operation begins, and apply it after the operation
ends.  This means that you can run merge on a dirty worktree.
However, use with care: the final stash application after a
successful merge might result in non-trivial conflicts.
This option can be overridden by the --no-autostash and --autostash options of git-merge .
Defaults to false.


[System] You are a helpful assistant.

[User] git-fetch - Download objects and refs from another repository  fetch.all

[Assistant]
If true, fetch will attempt to update all available remotes.
This behavior can be overridden by passing --no-all or by
explicitly specifying one or more remote(s) to fetch from.
Defaults to false.


[System] You are a helpful assistant.

[User] git-show - Show various types of objects  -c

[Assistant]
Produce combined diff output for merge commits.
Shortcut for --diff-merges=combined -p .


[System] You are a helpful assistant.

[User] git-config - Get and set repository or global options  bundle.version

[Assistant]
This integer value advertises the version of the bundle list format
used by the bundle list. Currently, the only accepted value is 1 .


[System] You are a helpful assistant.

[User]
warning: remote HEAD refers to nonexistent ref, unable to checkout
This seems like a popular error for different causes.
I've got a simple bare git repo called "kiflea.git", I clone it like this:
git clone git://kipdola.be/kiflea.git

Then git tells me: warning: remote HEAD refers to nonexistent ref, unable to checkout.
And yes, there are no versioned files in the map, except for the .git directory.
Anyway, the only thing I need to do is:
cd kiflea
git checkout master

And it works, all the files are there.
But I thought cloning a repo automatically checks out the master, so what is going on exactly, and how do I fix it?
I have noticed that, after I do the git checkout master bit, this gets added to my local .git config file:
[branch "master"]
    remote = origin
    merge = refs/heads/master

It's probably interesting to know that this git repository used to be an svn repository in a distant past.
Ps: when browsing the bare repository using gitweb, there clearly is a master branch there: http://kipdola.be/gitweb/?p=kiflea.git;a=summary

[Assistant]
The warning: remote HEAD refers to nonexistent ref, unable to checkout. means that the remote (bare) repository contains branch reference in the file called HEAD with a value that does not match any published branch in the same repository. In practice, that file defines which branch should be checked out by default after cloning the repository.
Note that the warning only means that git didn't do checkout. The cloned repository is otherwise just fine. Just do git branch -a to see possible branches and git checkout the-branch-you-want to workaround the issue.
This usually happens because the default contents for that file (.git/HEAD or plain HEAD for bare repositories) is literal string ref: refs/heads/master which says that if somebody is going to clone this repository, they should by default clone the branch refs/heads/master. By default Git will create local branch without the refs/heads/ prefix (that is, master by default). Try git help symbolic-ref for more information.
The problem with this situation is that Git does not provide a method for modifying remote symbolic refs so either you use something the Git hosting provider has implemented (e.g. Settings - Default branch in GitHub if you have admin rights) or you have to use branch name master as the default branch (because that's the default content for the file HEAD and if you cannot modify that file, you'll be stuck with master forever).
If you have a shell access to your remote git repo, you can simply open a shell on the remote matchine and execute cd path/to/git/repo; git symbolic-ref HEAD refs/heads/XYZ where XYZ is the branch name you want to use by default.
One way to hit this issue is to create a new remote bare repo with no commits and then do git push name-of-the-remote my-special-branch-name which will result in bare repository containing a single branch my-special-branch-name but the HEAD symbolic ref still contains the default value pointing to master. As a result, you'll get the aforementioned warning. If you cannot modify the remote HEAD file, you can publish your branch using syntax git push name-of-the-remote my-special-branch-name:master meaning that your local branch called my-special-branch-name should be published as branch master on the remote.


[System] You are a helpful assistant.

[User]
How to trigger Jenkins Multibranch Pipeline with Gitlab Webhook

I currently set up a Jenkins Multibranch Pipeline job that is based on a Git repository hosted on our GitLab server. Jenkins can read the branches in the repository and creates a job for every branch in the repository. But I can't figure out how to trigger the jobs with webhooks in GitLab.
My questions are:

How can I trigger the creation of a new branch job in Jenkins from our GitLab server? I can't see a webhook for a new branch being pushed.

How do I trigger the actual build job for a single branch? I can only add a webhook for push events but then I would have to add the branch name which I don't know how to do.

How can I make sure that GitLab always triggers the "creation of the branch job" before a push to a branch triggers the build job itself.

What I tried so far is triggering the multi-branch job, but this has no effect and following this post does not work at all.

[Assistant]
You need to install the GitLab Plugin on Jenkins.
This will add a /project endpoint on Jenkins. (See it in Jenkins => Manage Jenkins => Configure System => GitLab)
Now add a webhook to your GitLab project => Settings => Integrations. (or in older GitLab versions: GitLab project => Wheel icon => Integrations, it seems you need to be owner of the project in this case)
Set the URL to http://*yourjenkins.com*/**project**(/*foldername*)?/*yourprojectname* then click "Add webhook".
When you click "Test" on your webhook it should trigger your Jenkins pipeline build (you should get a 200 HTTP response).
It works without authentication in the GitLab plugin, configuration with authentication are welcome.


[System] You are a helpful assistant.

[User] git-diff - Show changes between commits, commit and working tree, etc  --check

[Assistant]
Warn if changes introduce conflict markers or whitespace errors.
What are considered whitespace errors is controlled by core.whitespace configuration.  By default, trailing whitespaces (including
lines that consist solely of whitespaces) and a space character
that is immediately followed by a tab character inside the
initial indent of the line are considered whitespace errors.
Exits with non-zero status if problems are found. Not compatible
with --exit-code.


[System] You are a helpful assistant.

[User]
What is 'gitlab/gitlab-runner-helper' docker image used for?

My overall goal is to install a self-hosted gitlab-runner that is restricted to use prepared docker images from my own docker registry only.
For that I have a system.d configuration that looks like:
/etc/systemd/system/docker.service.d/allow-private-registry-only.conf
BLOCK_REGISTRY='--block-registry=all'
ADD_REGISTRY='--add-registry=my.private.registry:8080'

By this, docker pull is allowed to pull images from my.private.registry/ only.
After I had managed to get this working, I wanted to clean up my local registry and remove old docker images. It was during that process when I stumbled over a docker image named gitlab/gitlab-runner-helper which presumably is some component used by the gitlab-runner itself and presumably has been pulled from docker.io.
Now I'm wondering if it is even possible/advisable to block images from docker.io when using a gitlab-runner?
Any hints are appreciated!

[Assistant]
I feel my sovereign duty to extend the accepted answer (it is great btw), because the word 'handle' basically tells us not so much, it is too abstract. Let me explain the whole flow in far more details:

When the build is about to begin, gitlab-runner creates a docker volume (you can observe it with docker volume ls if you want). This volume will server as a storage for caches and artifacts that you are using during the build.

The second thing - You will have at least 2 containers involved in each stage: gitlab-runner-helper, container and the container created from the image you specified (in .gitlab-ci.yml or in config.toml). What gitlab-runner-helper container does it, essentially, just cloning the remote git repository (that you are building) in the aforementioned docker volume along with caches and artifacts.

It can do it becuase within gitlab-runner-helper image itself are 2 important utilities: git (obviously - to clone the repo) and gitlab-runner-helper binary (this utility can pull and push artifacts, caches)

The gitlab-runner-helper container starts before each stage for a couple of seconds, to pull artifacts and caches, and then terminates. After that the container, created from image that you specified will be launched, ant it will also have this volume (from step 1) attached - this is how it receives artifacts btw.

The rest of the details about the registry from where gitlab-runner-helper get pulled are described by @Nicolas pretty well. I append this comment just for someone, who, perhaps, want to know what exactly means this sneaky 'handle' word.
Hope it helps, have a nice day, my friend!


[System] You are a helpful assistant.

[User] git-diff-index - Compare a tree to the working tree or index  --cached

[Assistant] Do not consider the on-disk file at all.


[System] You are a helpful assistant.

[User]
git-checkout older revision of a file under a new name
I have the file "main.cpp" open in my editor.
I want to see the previous revision of "main.cpp" in the editor too.
The way I do it now is like this.
close "main.cpp" in the editor

prompt> mv main.cpp tmp
prompt> git checkout HEAD^ main.cpp
prompt> mv main.cpp old_main.cpp
prompt> mv tmp main.cpp
prompt>

open "main.cpp" and "old_main.cpp" in the editor

Can it be simplified, so I don't have to close "main.cpp" in the editor?
What I'm hoping for is a variant of git-checkout that can do this.

UPDATE: im using git on mac osx 10.5.7
prompt> git --version
git version 1.6.0.4
prompt>

UPDATE2: Jakub Narębski answer is:
prompt> git show HEAD^:dir1/dir2/dir3/main.cpp > old_main.cpp
prompt>

UPDATE3: Karmi's answer, for a specific revision:
prompt> git show 4c274dd91dc:higgs/Higgs.xcodeproj/project.pbxproj > old_project.pbxproj
prompt>

[Assistant]
You can use git show for that:
git show HEAD^:main.cpp > old_main.cpp

(Note that there is colon [:] character between HEAD^ and main.cpp.)  The <revision>:<path> syntax is described in git rev-parse manpage, next to last point in the "Specifying revisions" section:

<rev>:<path>, e.g. HEAD:README, :README, master:./README
A suffix : followed by a path names the blob or tree at the given path in the tree-ish
object named by the part before the colon.  :path (with an empty part before the colon)
is a special case of the syntax described next: content recorded in the index at the
given path. A path starting with ./ or ../ is relative to the current working directory.
The given path will be converted to be relative to the working tree’s root directory.
This is most useful to address a blob or tree from a commit or tree that has the same
tree structure as the working tree.

Note that <path> here is FULL path relative to the top directory of your project, i.e. the directory with .git/ directory. (Or, to be more exact, to "<revision>", which in general can be any <tree-ish>, i.e. something that represents tree.)
If you want to use path relative to the current directory, you need to use ./<path> syntax (or ../path to go up from current directory).
Edit 2015-01-15: added information about relative path syntax

You can get in most cases the same output using low-level (plumbing) git cat-file command:
git cat-file blob HEAD^:main.cpp > old_main.cpp


[System] You are a helpful assistant.

[User]
Creating a SSH key with ssh-keygen does not create the .ssh folder
I am trying to create my public/private rsa key pair with msysgit
I run this command:
ssh-keygen -C "[email protected]" -t rsa

Everything looks fine, I have the message
Enter file in which to save the key (/c/Users/user/.ssh/id_rsa)

Then I have the confirmation:
Your public key has been saved in project.pub

But I can't access the folder! It does not exist, it is not even an hidden folder. I don't understand why it does not generate. I am using Windows 7 Ultimate.

[Assistant]
I had the same problem and I realized I was trying to enter a file name when it asks for the following "Enter file in which to save the key (c/users/user.name/.ssh/id_rsa)"
Rather just enter nothing and press Enter key to use the default and you will move on.


[System] You are a helpful assistant.

[User]
View the change history of a file using github.com

I've found this post about using the command line, but is it possible to view the file change history of a single file in a repository on github.com?
An in-browser solution would help me to better illustrate changes to team members while in meetings.

[Assistant]
You can view the change history of a file by clicking on the history button, or by adding commits to the URL of the file. Here is what it looks like for a file at the Homebrew repository on GitHub:
https://github.com/mxcl/homebrew/commits/master/SUPPORTERS.md
To get a line-by-line history, simply add the SHA-1 string of the commit for which you want to see the diff to the URL after the word commit, and then anchor it with the filename you are interested in. For the same file above:
https://github.com/mxcl/homebrew/commit/288f001e924d5365b79c279e4478f372a04011ae#SUPPORTERS.md
To see all commits for a single branch use a URL like this
https://github.com/mxcl/homebrew/commits/master
To see all commits for all branches use a URL like this
https://github.com/mxcl/homebrew/commits
There is no button or link in the web UI for these URLs, but you can bookmark them easily.


[System] You are a helpful assistant.

[User]
Configuring GitLab to use SAML OmniAuth with an Active Directory IdP

I am in the process of altering an existing GitLab installation to use SAML rather than LDAP for authentication.
At this point, users can successfully sign into the Web application using the 'Sign in with Saml' button. I am unclear, however, about what seems to be a difference between the LDAP and SAML approaches: users with accounts created via an LDAP sign-in can then access Git repositories (e.g. using clone, push, ...) using their LDAP usernames and passwords, but users with accounts created via a SAML sign-in cannot.
Through experimentation, I’ve found that users can access the Git repositories if they use the GitLab UI to set a separate GitLab account password on the account that is created during the initial SAML interaction. I was pointed in this direction by a GitLab message that appeared after creating a project under one of the new user accounts: 'You won't be able to pull or push project code via HTTPS until you set a password on your account'.
It seems possible that this separate password configuration is only necessary because I’ve misconfigured the SAML integration somehow. So, my question is whether I am wrong to expect that authenticating access to the GitLab-hosted Git repositories would work the same regardless of whether SAML or LDAP is used? If not, does anyone know of relevant SAML configuration settings that I should review?
In case it’s of interest: I have posted a similar question to the GitLab Google group, but I have not received any responses there yet.

[Assistant]
This is an old question, but I'm responding anyway in hopes it helps someone else who stumbles upon this question.
An important distinction between LDAP and SAML is that SAML is a web-based single sign on technology. Part of the SAML sign in process happens between the user's client (browser) and the SAML server directly and then GitLab verifies that information on the backend. In contrast, when given a user's LDAP password GitLab can connect directly to the LDAP server and verify the identity.
Many GitLab users utilize a combination of LDAP and SAML. SAML provides seamless single sign-on for the web side while LDAP allows Git over HTTPS to accept passwords and also opens the door to advanced features like LDAP Group Sync in Enterprise Edition.


[System] You are a helpful assistant.

[User]
Git, error: remote unpack failed: unable to create temporary object directory - By creating new Branch
I'm trying to create a new branch in my repo.
I did this:
git branch events

git Checkout events

That worked. So I changed some files and did:
git Status
git add --all
git commit -m "Commit"

That worked well but I tried to push it and that didn't work:
git push -u origin events

This is the error:
Enumerating objects: 9, done.
Counting objects: 100% (9/9), done.
Delta compression using up to 4 threads.
Compressing objects: 100% (5/5), done.
Writing objects: 100% (5/5), 716 bytes | 716.00 KiB/s, done.
Total 5 (delta 4), reused 0 (delta 0)
error: remote unpack failed: unable to create temporary object directory
To http://git.int.censoredlink/scm/freeb/freebrep.git
 ! [remote rejected] events -> events (unpacker error)
error: failed to push some refs to 'http://[email protected]/scm/freeb/freebrep.git'

I don't know why it does not work.
I have Admin rights on the Repo. I censored the link to the repo because its an internal Repo with private link.

[Assistant]
This error message:

error: remote unpack failed: unable to create temporary object directory

indicates that the Git repository at the server (not your Git) is out of space, or running into similar server problems,1 or installed incorrectly.  That is, given:

To: http://git.int.censoredlink/scm/freeb/freebrep.git

you will have to log in to the machine that serves HTTP traffic at git.int.censoredlink, walk down to the scm/freeb/freebrep.git directory, and correct the installation there.  It's most likely a permissions issue: the receiving Git must be able to create, in the objects area, a directory named incoming-XXXXXX with the Xs replaced by a unique identifier, and then create within that directory a pack subdirectory.
All incoming objects and pack files are placed in these directories, in a sort of quarantine procedure, until the server-side Git hooks are satisfied with the reference name update requests.  If the push fails, the quarantine directory is simply removed.  If the push succeeds, the quarantined objects and/or pack files are migrated (and thin packs adjusted) into the normal object storage area.  Note that the migration can fail even if the quarantine process succeeds; but if it does so, you get a different error reported to the client.  (This error must also be corrected on the server.)
Note: it's rather unusual to push to http:// rather than https:// or ssh:// URLs.  Inspect your server configuration to see who will own the various files thus created, and what permissions the web server will have.

1If a hard drive fails, Linux will sometimes mark the drive and/or its file systems read only.  Or, even if you have disk space, you can run out of inodes.  A number of different root causes will all lead to the same observed behavior on your client end.  If you are a Linux admin checking on a server, look for system log messages, and consider both df and df -i output.


[System] You are a helpful assistant.

[User]
How do I ignore an error on 'git pull' about my local changes would be overwritten by merge?
How do I ignore the following error message on Git pull?

Your local changes to the following files would be overwritten by merge

What if I want to overwrite them?
I've tried things like git pull -f, but nothing works.
To be clear, I only want to overwrite specific changes, not everything.

[Assistant]
If you want remove all local changes - including files that are untracked by git - from your working copy, simply stash them:
git stash push --include-untracked

If you don't need them anymore, you now can drop that stash:
git stash drop

If you don't want to stash changes that you already staged - e.g. with git add - then add the option --keep-index. Note however, that this will still prevent merging if those staged changes collide with the ones from upstream.

If you want to overwrite only specific parts of your local changes, there are two possibilities:

Commit everything you don't want to overwrite and use the method above for the rest.
Use git checkout path/to/file/to/revert for the changes you wish to overwrite. Make sure that file is not staged via git reset HEAD path/to/file/to/revert.


[System] You are a helpful assistant.

[User] git-stash - Stash the changes in a dirty working directory away  --only-untracked

[Assistant] This option is only valid for the show command. Show only the untracked files in the stash entry as part of the diff.


[System] You are a helpful assistant.

[User]
Run gitlab-ci.yml only when merge request to master made

I am currently having my project in GitLab and Heroku. What I wanna do is as soon as I ask for merge request with my feature branch (let's call it crud-on-spaghetti), I want to automatically run the tests on this branch (npm test basically, using Mocha/Chai), and after they succeed, merge this crud-on-spaghetti with master, commit it and push it to origin/master (which is remote on GitLab) and after git push heroku master (basically, push it to the master branch in Heroku, where my app is stored). I have read several articles on GitLab CI and I think this is more suitable for me (rather than Heroku CI, because I do not have DEV and PROD instances).
So, as of now, I do this manually. And this is my .gitlab-ci.yml file now (which is not committed/pushed yet):
stages:
  - test
  - deploy

test_for_illegal_bugs:
  stage: test
  script:
    - npm test

deploy_to_dev:
  stage: deploy
  only:
    - origin master
  script:
    - git commit
    - git push origin master
    - git pull heroku master --rebase
    - git push heroku master

Hence, my questions is: What do I exactly need to write in .gitlab-ci.yml in order to automate all these "manipulations" (above)?
PS. And another (theoretical) follow-up question: how is GitLab-CI Runner triggered? For instance, if I want it to trigger upon merge request with master, do I do that using only: ... in .gitlab-ci.yml?

[Assistant]
As of 2023 the keywords only and except have been deprecated in favor of rules (see docs).
In newer versions
Using rules: to restrict the execution of a job to a merge request to the target branch:
  rules:
    - if: '$CI_PIPELINE_SOURCE == "merge_request_event" && $CI_MERGE_REQUEST_TARGET_BRANCH_NAME == "master"'

For older versions
Restrict stages to Merge Requests:
To have your test stage only being executed when a Merge Request (MR) is opened, use:
   only:
     - merge_requests

According to the Gitlab docs, you can further restrict this to only being executed for MRs with a certain target branch, e.g. only MRs for master
   only:
     - merge_requests
   except:
     variables:
       - $CI_MERGE_REQUEST_TARGET_BRANCH_NAME != "master"

This adds an exception for all target branches that are not master.
Restrict stages to Branches:
As already mentioned by @marcolz, this is achieved by
   only:
     - master

to only execute the stage for pushes to the master branch.


[System] You are a helpful assistant.

[User]
GitLab: Is it possible to run pipeline on a specific runner?

Is it possible to run a pipeline on a specific runner? (not using tags)
Is it feasible to use environments, or even gitlab runner exec maybe?

Scenario:
Have an existing project with multiple runners already attached to it (specific project token used to register the runner) and has it's own associated tags (so can't change these either).
I'm adding a new runner, however need to test it first to ensure it works, but I need to force the pipeline to build on this machine, without changing any tags, or specific project of the runner.

[Assistant]
You have two mechanisms by which you can attempt to isolate a new runner for testing:

use tags and private runner attachment (already called out)
use the gitlab-runner exec verb directly on the runner
canary the runner for a single build only

Option 1
use tags and private runner attachment (already called out).
To further expand on this... even in a draconian setup where you can't alter tags and whatnot -- you can always FORK the project.
In your new private fork, you can go to Settings >> CI/CD and override the .gitlab-ci.yml file in the Custom CI Configuration Path under the General Pipelines Settings.  This allows you to git cp .gitlab-ci.yml .mycustomgitlab-ci.yml and then simply git add/git commit/git push and you're in business.
Opinion: If you cannot use the mechanisms in place to adjust the tags on the questionable runner and isolate a new forked project, this isn't a technical problem, it is a political problem.
Option 2
Gitlab-runner exec....
Assuming you're using a shell gitlab runner...

SSH to the questionable gitlab runner box you're trying to test
Clone the repo for the project in question to ... say ... /tmp/myrepo
Execute Gitlab-Runner: /path/to/gitlab-runner exec shell {.gitlab-ci.yml target}

See https://docs.gitlab.com/runner/commands/#gitlab-runner-exec and a blog about it at https://substrakt.com/how-to-debug-gitlab-ci-builds-locally/
Option 3
Canary the gitlab-runner for a single build.
You can spin up the gitlab-runner process to do N number of builds and then go back offline.  See: https://docs.gitlab.com/runner/commands/#gitlab-runner-run-single
... This is not zero-impact, but will definitely limit the blast radius of any problems.


[System] You are a helpful assistant.

[User] git-format-patch - Prepare patches for e-mail submission  --suffix=.<sfx>

[Assistant]
Instead of using .patch as the suffix for generated
filenames, use specified suffix.  A common alternative is --suffix=.txt .  Leaving this empty will remove the .patch suffix. Note that the leading character does not have to be a dot; for example,
you can use --suffix=-patch to get 0001-description-of-my-change-patch .


[System] You are a helpful assistant.

[User]
Should I ignore the launchSettings.json file from being committed in Git?
I find this relatively known GitHub repository, where they considered launchSettings.json file (which is used by Visual Studio 2017 for .Net Core projects) is to be ignored.
https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
Why should it be ignored? I used always in the company I work in to commit it, I am curious to know if there is any reason to ignore it.

[Assistant]
launchSettings.json should not be ignored. That repository has since been updated to not ignore it: https://github.com/github/gitignore/pull/2705

Reasons for making this change:
Ignoring launchSettings.json does not make much sense. Now .NET CLI even considers this file when running with dotnet run, as you can read here.
This settings will be useful if shared among project members, so it should be commited to the repo.
Links to documentation supporting these rule changes:
https://learn.microsoft.com/en-us/dotnet/core/tools/dotnet-run?tabs=netcore2x


[System] You are a helpful assistant.

[User]
Git is not working after macOS update ("xcrun: error: invalid active developer path (/Library/Developer/CommandLineTools")
I updated to the latest OS, and/or restarted my computer (this happens on every major update, but this time all I did was restart my computer on 2022-09-13).
This morning I navigated to my work's codebase in the command line on my MacBook Pro, typed in "git status" in the repository and received an error:
(In 9/2022, this error was much different, but I didn't capture it)

xcrun: error: invalid active developer path (/Library/Developer/CommandLineTools), missing xcrun at: /Library/Developer/CommandLineTools/usr/bin/xcrun

Git will not work!
How do I fix Git, and the command-line tools?

[Assistant]
The problem is that Xcode Command-line Tools needs to be updated due to a MacOs update.

Did not run into this on Sonoma.

Maybe Apple fixed the process?

Updated for Ventura

After opening the terminal after restarting, I tried to go to my code, and do a git status, and I got an error and prompt for command line software agreement:
So press space until you get to the [agree, print, cancel] option, so careful hit space to scroll down to the end, if you blow past It you have to run a command to get it back. Use sudo xcodebuild -license to get to it again.
Just be careful on scrolling down and enter agree and press return and it will launch into an update.

Then I tried to use git after the install, and it prompted me to install Xcode tools again.
I followed my own advice from previous years (see below), and went to https://developer.apple.com/download/all and downloaded
"Command Line Tools for Xcode 14" (You have to log in with your Apple ID and enter MFA code, so have all the devices you need for that handy. Then select "Command Line Tools for Xcode 14", or if you want to get into the alphas or betas, that's up to you. But stable releases are probably the best choice for software developers.

You have to either download the tools from CLI or the developer page and before you can use git, you need to reboot!!! Or you will get stuck in a loop of prompt & downloading
Rebooting will break the loop and complete the installation of your CLI tools including git so that you can get back to work
Solutions for previous years, these may or may not be valid these days as the downloads page has changed significantly:
PREVIOUS YEARS SOLUTIONS, probably #2 is most helpful.
*** Solution #1:
Go back to your terminal and enter:
xcode-select --install

You'll then receive the following output:
xcode-select: note: install requested for command line developer tools

You will then be prompted in a window to update Xcode Command Line tools. (which could take a while)
Open a new terminal window and your development tools should be returned.
Addition: With any major or semi-major update you'll need to update the command line tools in order to get them functioning properly again. Check Xcode with any update. This goes beyond Mojave...
After that restart your terminal
Alternatively, IF that fails, and it might.... you'll get a pop-up box saying "Software not found on server", proceed to solution 2.
*** Solution #2: (Preferred method)
If you hit xcode-select --install and it doesn't find the software, log into Apple Developer, and install it via webpage.
Log in or sign up here:
https://developer.apple.com/download/more/
Look for: "Command Line Tools for Xcode 14.x" in the list of downloads
Then click the dmg and download. (See previous image above) either way, you will probably wind up at an apple downloads webpage.


[System] You are a helpful assistant.

[User]
How do you revert a git file to its staging area version?
Let's say I have a file named a.txt. I add it to the staging area, and then I modify it. How could I return it to the way it was when I added it?

[Assistant]
Prior to Git 2.23: git checkout a.txt
Starting from Git 2.23: git restore a.txt

Git tells you this if you type git status.
Prior to Git 2.23:
# On branch master
# Changes to be committed:
#   (use "git reset HEAD <file>..." to unstage)
#
# modified:   a
#
# Changed but not updated:
#   (use "git add <file>..." to update what will be committed)
#   (use "git checkout -- <file>..." to discard changes in working directory)
#
# modified:   a
#

Starting from Git 2.23:
On branch master
Changes to be committed:
  (use "git restore --staged <file>..." to unstage)
        modified:   a

Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git restore <file>..." to discard changes in working directory)
        modified:   a


[System] You are a helpful assistant.

[User]
Is there a way in git to obtain a push date for a given commit?
I am wondering if there is a way to view a push date associated with each commit in the git log.  If that is not possible, is there a way to see all the commits under a certain push.
I writing a program that needs to keep track of the commits as they are pushed.  Because the git log is ordered by the commit date, not the push date, I am not able to see the most recent commits that are pushed. For example, if a user commits to his local repository 2 days before he pushes to the master, that commit will be placed behind 2 days of other commits in the master repository log.

[Assistant]
It took me an insanely long time to gather scattered information and finally find the very best answer to this question, but now I know I have it. In just two lines, no code and no hooks:
# required for a bare repo
git config core.logAllRefUpdates true

git reflog --date=local master

Simple at last.
Warning: you probably want to override the default values of gc.reflogExpire and gc.reflogExpireUnreachable. Check git help reflog for details and to understand how and why this works.
The two commands above must be run inside the clone you push to. If that is not possible then an approximation is to run in another, permanent clone:
git fetch               origin        # often and *regularly*
git reflog --date=local origin/master

Never delete this permanent clone or you will lose the dates.


[System] You are a helpful assistant.

[User] git-log - Show commit logs  <limit>

[Assistant]
An integer parameter specifies a cut-off percent (3% by default).
Directories contributing less than this percentage of the changes
are not shown in the output.


[System] You are a helpful assistant.

[User]
What are your pros and cons of git after having used it? [closed]
Closed. This question is opinion-based. It is not currently accepting answers.

Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.

Closed 10 years ago.

                        Improve this question

I'm using SVN right now, and I've used CVS and VSS in the past. SVN is the current favourite in my books, but I've been hearing a lot about git. Of the people that have used git, what are the pros and cons from your experience?

[Assistant]
I don't have a lot of experience with git, but:
Pros:

It's really quick
Local commits rock
Quick to start a new repository (no configuration etc)
github is easy to use

(I haven't really "needed" the distributed side of things yet, beyond being able to have a local repository and push to a public one.)
Cons:

Windows support is still lagging behind, I believe - and you can't just use it from a normal command prompt
Lack of IDE and Explorer integration
It took me a while to find a good introductory text along the lines of the redbean book.
The fact that "adding" a changed file only adds the contents at that point of time (so it can show up as staged for commit and still have modifications which require another git add) took a while to grasp


[System] You are a helpful assistant.

[User] git-config - Get and set repository or global options  gitcvs.dbTableNamePrefix

[Assistant]
Database table name prefix.  Prepended to the names of any
database tables used, allowing a single database to be used
for several repositories.  Supports variable substitution (see git-cvsserver for details).  Any non-alphabetic
characters will be replaced with underscores.


[System] You are a helpful assistant.

[User] git-config - Get and set repository or global options  guitool.<name>.revPrompt

[Assistant]
Request a single valid revision from the user, and set the REVISION environment variable. In other aspects this option
is similar to argPrompt , and can be used together with it.


[System] You are a helpful assistant.

[User] git-log - Show commit logs  %(trailers[:<options>])

[Assistant]
display the trailers of the body as interpreted by git-interpret-trailers . The trailers string may be followed by
a colon and zero or more comma-separated options. If any option is provided
multiple times, the last occurrence wins. key=<key> : only show trailers with specified <key>. Matching is done
case-insensitively and trailing colon is optional. If option is
given multiple times trailer lines matching any of the keys are
shown. This option automatically enables the only option so that
non-trailer lines in the trailer block are hidden. If that is not
desired it can be disabled with only=false .  E.g., %(trailers:key=Reviewed-by) shows trailer lines with key Reviewed-by . only[=<bool>] : select whether non-trailer lines from the trailer
block should be included. separator=<sep> : specify the separator inserted between trailer
lines. Defaults to a line feed character. The string <sep> may contain
the literal formatting codes described above. To use comma as
separator one must use %x2C as it would otherwise be parsed as
next option. E.g., %(trailers:key=Ticket,separator=%x2C ) shows all trailer lines whose key is "Ticket" separated by a comma
and a space. unfold[=<bool>] : make it behave as if interpret-trailer’s --unfold option was given. E.g., %(trailers:only,unfold=true) unfolds and shows all trailer lines. keyonly[=<bool>] : only show the key part of the trailer. valueonly[=<bool>] : only show the value part of the trailer. key_value_separator=<sep> : specify the separator inserted between
the key and value of each trailer. Defaults to ": ". Otherwise it
shares the same semantics as separator=<sep> above.


[System] You are a helpful assistant.

[User] git - the stupid content tracker  git-gc

[Assistant] Cleanup unnecessary files and optimize the local repository


[System] You are a helpful assistant.

[User]
Git log tabular formatting
I have a simple alias to display few last commits:
log --pretty=format:'%h %an %s' -10

How can I make the results to be displayed in columns, like this:
898e8789 Author1             Commit message here
803e8759 Other Author name   Commit message here

[Assistant]
In Git 1.8.3 and later, there is native support for this in the pretty format, using the %<(N) syntax to format the next placeholder as N columns wide:
$ git log --pretty=format:'%h %<(20)%an %s' -10

For versions before 1.8.3, the previous version of this answer, retained below, should work.
Here's a solution in Bash using read to parse the log lines back apart, and printf to print them out, with a fixed width field for the authors name so the columns will stay lined up. It assumes that | will never appear in the author's name; you can choose another delimiter if you think that might be a problem.
git log --pretty=format:'%h|%an|%s' -10 |
  while IFS='|' read hash author message
  do
    printf '%s %-20s %s\n' "$hash" "$author" "$message"
  done

You can create this as an alias using:
[alias]
    mylog = "!git log --pretty=format:'%h|%an|%s' -10 | while IFS='|' read hash author message; do printf '%s %-20s %s\n' \"$hash\" \"$author\" \"$message\"; done"

I'm sure you could do this in fewer characters using awk but as the saying goes,

Whenever faced with a problem, some people say “Lets use AWK.” Now, they have two problems.

Of course, having said that, I had to figure out how to do it in awk which is a bit shorter:
git ... | awk -F '|' '{ printf "%s %-20s %s\n", $1, $2, $3 }'


[System] You are a helpful assistant.

[User]
Git: list all commits on all remote branches?
I would like to list all commits on all remote branches in my repository.
I just want the SHA1 for each commit.

[Assistant]
Try this:
git log --branches="*"


[System] You are a helpful assistant.

[User]
Local git config not overriding global user for project

I have a global git user configured, but want to use a different user for a single git project.
Within that project, I've used git config --local user.name "localuser" and git config --local user.email "[email protected]" to set the local project's user and email.
However, when I try to push to my remote on github, I get this error:
remote: Permission to localuser/repo.git denied to globaluser.
fatal: unable to access 'https://github.com/localuser/repo.git/': The requested URL returned error: 403

Here's some output that might help with diagnosis:
git remote -v:
github  https://github.com/localuser/repo.git (fetch)
github  https://github.com/localuser/repo.git (push)

git config --list:
user.name=globaluser
[email protected]
...

git config --local --list:
user.name=localuser
[email protected]
...

git config user.name:
localuser

[Assistant]
I had committed my changes and received a permission denied with my global user. Subsequently setting the local user did nothing, though git config user.name reported the correct local user.
What worked was (courtesy of this google groups thread):
git commit --amend --reset-author
I presume the committed changes had the original author attached.


[System] You are a helpful assistant.

[User]
Can you set Gitlab CI stage so other stages don't wait for it to finish?

Let's say I have these stages defined in .gitlab-ci.yml:
stages:
    - build
    - analysis
    - tests
    - deploy
    - post-deploy

Since analysis takes a lot of time and I don't really care about the result (I also have allow_failure: true set) - is it possible to somehow define to start analysis and then immediately launch the next stage tests?
I didn't find any reference to similar topic on official docs.
EDIT:
The main idea is that all other stages can be run as if the analysis didn't even exist. If i put analysis to same stage as tests, then both analysis and tests will run at the same time, however deploy won't be launched until both of them finish. This is no good. I want tests to finish and then launch deploy, after deploy finishes I want to launch post-deploy. I really don't care about analysis result, I simply want to trigger it and continue with the deployment.

[Assistant] Since v12.8, you can use needs: [] to start jobs start immediately. Docs: https://docs.gitlab.com/ee/ci/yaml/#needs


[System] You are a helpful assistant.

[User] git-add - Add file contents to the index  -f  --force

[Assistant] Allow adding otherwise ignored files.


[System] You are a helpful assistant.

[User]
Can Git restructure my folders without losing history?
I have a git repo, and currently I'm the only one using it.
I want to take all the files and folders under the root folder, and put them inside a new folder.
Current structure:

main ->
  src
  res

New structure:

main ->
  app1
    src
    res

Is there a way I can do that so that the files don't lose their git history?

[Assistant]
TL;DR
Go ahead: move your files and directories around. Just make sure you don't make any edits to files in the same commit as your directory restructuring.
Why It Works
Git is a content tracker, not a file tracker. If you move/rename files, but make no other changes to the content of those files, then Git just rewrites the tree objects. The file blobs are not changed by directory operations; directory location information is stored separately in tree objects.
Actual rename detection is handled by diffing the blobs and trees, and looking for a configurable percentage of similarity between files. This means that Git doesn't really store moves or renames directly; it computes them from differences between commits.
The upshot of all this is that your history is not tied to a particular filename or directory structure. This works really well for most use cases, but stands in contrast to systems like Bazaar that track renames as first-class operations.


[System] You are a helpful assistant.

[User] git - the stupid content tracker  git-help

[Assistant] Display help information about Git


[System] You are a helpful assistant.

[User]
How to make a simple revert work on Git / EGit?
Ok. Simple things should be simple, so I hope it is. :)
I have changed a file, now I want to revert back to the latest version in the git repo because my changes are crap and I want to start fresh again changing the file.
As far as I am concerned you should do this:
git checkout -- <NAME OF FILE>
First question: How to do this inside eclipse with EGit? There is no checkout option under team. :( :( :(
Now let's suppose I have multiple files modified in multiple directors. How do I revert all of them to start fresh again?

[Assistant]
In my version "Replace With..." -> "HEAD Revision" seems to be doing just that...
It's not in the "Team" submenu, which is a bit confusing, I admit..
Also, this might help : Eclipse git checkout (aka, revert)


[System] You are a helpful assistant.

[User] git-show - Show various types of objects  %x00

[Assistant]
%x followed by two hexadecimal digits is replaced with a
byte with the hexadecimal digits' value (we will call this
"literal formatting code" in the rest of this document).


[System] You are a helpful assistant.

[User] git-pull - Fetch from and integrate with another repository or a local branch  recursive

[Assistant]
This can only resolve two heads using a 3-way merge
algorithm.  When there is more than one common
ancestor that can be used for 3-way merge, it creates a
merged tree of the common ancestors and uses that as
the reference tree for the 3-way merge.  This has been
reported to result in fewer merge conflicts without
causing mismerges by tests done on actual merge commits
taken from Linux 2.6 kernel development history.
Additionally this can detect and handle merges involving
renames.  It does not make use of detected copies.  This was
the default strategy for resolving two heads from Git v0.99.9k
until v2.33.0. The recursive strategy takes the same options as ort .  However,
there are three additional options that ort ignores (not documented
above) that are potentially useful with the recursive strategy: patience Deprecated synonym for diff-algorithm=patience . diff-algorithm=[patience|minimal|histogram|myers] Use a different diff algorithm while merging, which can help
avoid mismerges that occur due to unimportant matching lines
(such as braces from distinct functions).  See also git-diff --diff-algorithm .  Note that ort specifically uses diff-algorithm=histogram , while recursive defaults to the diff.algorithm config setting. no-renames Turn off rename detection. This overrides the merge.renames configuration variable.
See also git-diff --no-renames .


[System] You are a helpful assistant.

[User] git-log - Show commit logs  -I<regex>  --ignore-matching-lines=<regex>

[Assistant]
Ignore changes whose all lines match <regex>.  This option may
be specified more than once.


[System] You are a helpful assistant.

[User]
Force git to run post-receive hook, even if everything is "up-to-date"
How do I force git to run a post-receive hook on a server even if I don't have a new commit to push?
Background
I use git to automatically deploy a website to a server. I have a bare repo in a protected area of the server and a post-receive hook that checks out the contents and systematically copies over certain files into a public_html folder. (Inspired by this tutorial)
I got tired of modifying the post-receive hook manually on the server, so my post-receive hook now actually copies over a new version of itself from the repo:
#!/bin/sh

rm -rf ~/../protected/*
GIT_WORK_TREE=~/../protected git checkout -f

# Rewrite over this file with any updates from the post-receive file
cp ~/../protected/post-receive hooks/post-receive

# Delete public_html
# Copy stuff public_html

The problem, of course, is that the new post-receive hook never gets run. A seemingly simple solution would be merely to push again, but now  everything is already up to date. This is annoying, because it requires me to fake a new commit every time I update the post-receive hook. Is there a way to invoke the post-receive hook without faking a commit or sshing in?
What I tried
git push
git push -f

[Assistant]
Use '--allow-empty'
After the initial push replacing the script, you can do this :
git commit --allow-empty -m 'push to execute post-receive'

The --allow-empty flag overrides git's default behavior of preventing you from making a commit when there are no changes.
Use an alias and make your life even easier
Add the following to ~/.gitconfig
[alias]
    pushpr = "!f() { git push origin master;git commit --allow-empty -m 'push to execute post-receive';git push origin master; }; f"

Now Just do git pushpr
git pushpr

This will push any changes to master, which in your case will trigger your post receive replacement script, then it will push again (using the --allow-empty flag) which will then execute your updated post-receive script.


[System] You are a helpful assistant.

[User]
How to list all commits that changed a specific file?
Is there a way to list all commits that changed a specific file?

[Assistant]
The --follow works for a particular file
git log --follow -- filename

Difference to other solutions given
Note that other solutions include git log path (without the --follow). That approach is handy if you want to track e.g. changes in a directory, but stumbles when files were renamed (thus use --follow filename).


[System] You are a helpful assistant.

[User]
How to determine the URL that a local Git repository was originally cloned from
I pulled a project with several forks on GitHub, but forgot which fork it was. How do I determine which fork I pulled?

[Assistant]
To obtain only the remote URL:
git config --get remote.origin.url

If you require full output, and you are on a network that can reach the remote repo where the origin resides:
git remote show origin

When using git clone (from GitHub, or any source repository for that matter) the default name for the source of the clone is "origin". Using git remote show will display the information about this remote name. The first few lines should show:
C:\Users\jaredpar\VsVim> git remote show origin
* remote origin
  Fetch URL: [email protected]:jaredpar/VsVim.git
  Push  URL: [email protected]:jaredpar/VsVim.git
  HEAD branch: master
  Remote branches:

If you want to use the value in a script, you would use the first command listed in this answer.


[System] You are a helpful assistant.

[User]
Want to change my master to an older commit, how can I do this?
I want to rollback to a previous commit, and then publish that code, then go back to the latest commit.
i.e. so my master is pointing to an older commit version just so I can pulish that version, then I want to go back to the latest commit I was one initially.
How can I do this?

[Assistant]
If you want to do this and revert the master to the previous commit:
git checkout master~1            # Checkout previous commit on master
git checkout -b new_master       # Create branch for new master
git branch -D master             # Delete old master
git branch -mv new_master master # Make new_master master

Alternatively:
git reset --hard master~1        # Reset current branch to one commit ago on master


[System] You are a helpful assistant.

[User] git-log - Show commit logs  git log --follow builtin/rev-list.c

[Assistant]
Shows the commits that changed builtin/rev-list.c , including
those commits that occurred before the file was given its
present name.


[System] You are a helpful assistant.

[User]
Git: Recover deleted (remote) branch
I need to recover two Git branches that I somehow deleted during a push.
These two branches were created on a different system and then pushed to my "shared" (github) repository.
On my system, I (apparently) retrieved the branches during a fetch:
~/myfolder> git fetch
remote: Counting objects: 105, done.
remote: Compressing objects: 100% (58/58), done.
remote: Total 62 (delta 29), reused 0 (delta 0)
Unpacking objects: 100% (62/62), done.
From github.com:mygiturl
 * [new branch]      contact_page -> origin/contact_page
   731d1bb..e8b68cc  homepage   -> origin/homepage
 * [new branch]      new_pictures -> origin/new_pictures

Right after that I did a push to send my local changes up to the central repo. For some reason, these branches were deleted from both my local system and the central repo:
~/myfolder> git push
Counting objects: 71, done.
Delta compression using up to 2 threads.
Compressing objects: 100% (43/43), done.
Writing objects: 100% (49/49), 4.99 KiB, done.
Total 49 (delta 33), reused 0 (delta 0)
To [email protected]:mygiturl.git
 - [deleted]         contact_page
 + e8b68cc...731d1bb homepage -> homepage (forced update)
   bb7e9f2..e0d061c  master -> master
 - [deleted]         new_pictures
   e38ac2e..bb7e9f2  origin/HEAD -> origin/HEAD
   731d1bb..e8b68cc  origin/homepage -> origin/homepage
   e38ac2e..bb7e9f2  origin/master -> origin/master
 * [new branch]      origin/contact_page -> origin/contact_page
 * [new branch]      origin/new_pictures -> origin/new_pictures

It's not terribly easy to get the branches off of their birthplace machine, so I'd like to try and recover them from my local if possible.
All of the git "undo" information I've googled has to with recovering lost commits. I don't think that applies here, since I don't have commit UIDs for these branches.
I'd like to know how I can get these back. I'd also like to know how they were deleted in the first place and how I can avoid this in the future.
EDIT: by request, here's my repo configuration
user.name=Craig Walker
[email protected]
alias.unadd=reset HEAD
core.repositoryformatversion=0
core.filemode=true
core.bare=false
core.logallrefupdates=true
core.ignorecase=true
remote.origin.fetch=+refs/heads/*:refs/remotes/origin/*
[email protected]:MyGitURL.git
remote.origin.mirror=true
branch.master.remote=origin
branch.master.merge=refs/heads/master
alias.undo=reset --hard
alias.test=push -f ci HEAD:master
alias.st=status
alias.ci=commit
alias.br=branch
alias.co=checkout
alias.ch=checkout
alias.df=diff
alias.lg=log -p
alias.who=shortlog -s --
remote.ci.url=ContinuousIntegrationGitURL
remote.ci.fetch=+refs/heads/*:refs/remotes/ci/*
branch.photo.remote=origin
branch.photo.merge=refs/heads/photos
remote.foo.url=FooGitURL
remote.foo.fetch=+refs/heads/*:refs/remotes/cynthia/*
branch.homepage.remote=origin
branch.homepage.merge=refs/heads/homepage

[Assistant]
I'm not an expert. But you can try
git fsck --full --no-reflogs | grep commit

to find the HEAD commit of deleted branch and get them back.


[System] You are a helpful assistant.

[User]
How do you `git cherry-pick --continue` with `--no-verify`?
How do you git cherry-pick --continue with --no-verify since --no-verify is not a valid option.  git cherry-pick --no-commit --continue does not work since those two parameters are mutually exclusive.

[Assistant]
If your cherry-pick (without --no-commit) had merge conflicts and you want to --continue after solving them, you can temporarily disable git hooks for the current repo with:
$ git config core.hooksPath # Print current setting
$ git config core.hooksPath '/dev/null/'

After you're done, depending on whether core.hooksPath was set before, you can either restore the previous setting:
$ git config core.hooksPath '/some/previous/path'

or unset it again:
$ git config --unset core.hooksPath


[System] You are a helpful assistant.

[User]
Remove .pyc files from Git remote repository
Accidentally, I have pushed the .pyc files to the master repository. Now I want to delete them but I can´t do it. Is there any way to remove them directly from the Bitbucket site?

[Assistant]
Remove .pyc files using git rm *.pyc. If this not work use git rm -f *.pyc
Commit git commit -a -m 'all pyc files removed'
Push git push
In future commits you can ignore .pyc files by creating a .gitignore file


[System] You are a helpful assistant.

[User] git-pull - Fetch from and integrate with another repository or a local branch  subtree[=<path>]

[Assistant]
This option is a more advanced form of subtree strategy, where
the strategy makes a guess on how two trees must be shifted to
match with each other when merging.  Instead, the specified path
is prefixed (or stripped from the beginning) to make the shape of
two trees to match.


[System] You are a helpful assistant.

[User] git-config - Get and set repository or global options  remote.<name>.skipFetchAll

[Assistant]
If true, this remote will be skipped by default when updating
using git-fetch or the update subcommand of git-remote .


[System] You are a helpful assistant.

[User] git-archive - Create an archive of files from a named tree  export-ignore

[Assistant]
Files and directories with the attribute export-ignore won’t be
added to archive files.  See gitattributes for details.


[System] You are a helpful assistant.

[User]
Can I use my existing git repo with openshift?
Is it necessary to have git repo on openshift only? I already have bitbucket / github git repo and would prefer to push there only. Can I simply hook into it so that openshift gets intimation ?
Or for simplification, I push only at github, but when I want to deploy, I do something with openshift?
I did check this but it confused me:  it's talking about merging exiting and new (openshift) git ?

[Assistant]
I have the impression that you're not used to use git enough yet. I'd advise you to get into git to fully understand how to push your code to openshift. Nevertheless let me try to explain you the steps involved:
As you'd do with git in general, the approach to choose here is to clone your other git repo (ex. on bitbucket) to your local machine:
git clone <bitbucket-repo-url>
Your local clone has then your other repo (bitbucket etc.) as remote repo. Your remote repo is stored with the alias "origin" (the default alias used by git if you clone). You then add the openshift repo as remote to your clone. You do that while explicitly using an alias for the remote repo you add - I'm using "openshift" as alias here:
git remote add openshift -f <openshift-git-repo-url>
In order to then be able to push the code from your local git repo to openshift you first have to merge your openshift repo with your local bitbucket clone. You do that by issuing locally:
git merge openshift/master -s recursive -X ours
With this command you tell git to merge the master branch in the openshift git repo with your local git repo. You tell it to merge using the recursive merging strategy and to choose your ("ours") version when there are conflicts.
Once the merge is executed you're ready to push your git repo to openshift. You do that by doing:
git push openshift HEAD
You tell git to push your local code to the HEAD branch on the remote repo called "openshift" (the alias we stored the openshift git repo at, some paragraphs further up).
btw. I wrote a jboss tools blog which was demonstrating how to use the openshift-java-client some months ago: https://community.jboss.org/wiki/Enable-openshift-ciFullExampleUsingOpenshift-java-client . You'll spot the above steps in the last paragraph "We're almost there".


[System] You are a helpful assistant.

[User] git-cherry-pick - Apply the changes introduced by some existing commits  --ff

[Assistant]
If the current HEAD is the same as the parent of the
cherry-pick’ed commit, then a fast forward to this commit will
be performed.


[System] You are a helpful assistant.

[User]
git add multiple files at once
I had this project with a lot .c files in source directory,then I make the project, there is  .o files inside of the project, I also want to push these files to repository,so instead of add each .o which is possible but...,how to add .o files easily?

[Assistant]
How to add multiple files with different extensions to git all at one time...
You can add to git by explicitly listing each file with spaces as delimiters.
$ git add file-name-1.php file-name-2.js file-name-3.html …

The accepted answer is perfect for the OP’s specific case. But I got here—via Google—needing to add multiple files with different extensions. Posting here in case you miss this similar answer to a similar question.
Don't forget about interactive staging
Git interactive staging can also work wonders. To enter interactive staging (aka: adding, removing files):
 $ git add -i


[System] You are a helpful assistant.

[User]
Saving the entire git diff between two commits in a text file
is there a way where I could save the entire difference between two diff in a text file?
Suppose I wanted all the changes between A1 and A10 on master branch.
--A11-A10-A9-A8-A7-A6-A5-A4-A3-A2-A1-master

Or, is there a way where I could get the entire diff in Terminal which I could copy+paste?

[Assistant]
Sure:
git diff A10..A1 > my.diff


[System] You are a helpful assistant.

[User]
How to tag an older commit in Git?
We are new to Git, and I want to set a tag at the beginning of our repository.
Our production code is the same as the beginning repository, but we've made commits since then.
A tag at the beginning would allow us to "roll back" production to a known, stable state.
So how to add a tag to an arbitrary, older commit?

[Assistant]
Example:
git tag -a v1.2 9fceb02 -m "Message here"

Where 9fceb02 is the beginning part of the commit id.
You can then push the tag using git push origin v1.2.
You can do git log to show all the commit id's in your current branch.
There is also a good chapter on tagging in the Pro Git book.
Warning: This creates tags with the current date (and that value is what will show on a GitHub releases page, for example).  If you want the tag to be dated with the commit date, please look at another answer.


[System] You are a helpful assistant.

[User] git-fast-import - Backend for fast Git data importers  blob

[Assistant]
Convert raw file data into a blob, for future use in a commit command.  This command is optional and is not
needed to perform an import.


[System] You are a helpful assistant.

[User] git-rebase - Reapply commits on top of another base tip  -n  --no-stat

[Assistant] Do not show a diffstat as part of the rebase process.


[System] You are a helpful assistant.

[User] git-stash - Stash the changes in a dirty working directory away  --index

[Assistant]
This option is only valid for pop and apply commands. Tries to reinstate not only the working tree’s changes, but also
the index’s ones. However, this can fail, when you have conflicts
(which are stored in the index, where you therefore can no longer
apply the changes as they were originally).


[System] You are a helpful assistant.

[User] git-cherry-pick - Apply the changes introduced by some existing commits  -m <parent-number>  --mainline <parent-number>

[Assistant]
Usually you cannot cherry-pick a merge because you do not know which
side of the merge should be considered the mainline.  This
option specifies the parent number (starting from 1) of
the mainline and allows cherry-pick to replay the change
relative to the specified parent.


[System] You are a helpful assistant.

[User] git-pull - Fetch from and integrate with another repository or a local branch  subtree

[Assistant]
This is a modified ort strategy. When merging trees A and
B, if B corresponds to a subtree of A, B is first adjusted to
match the tree structure of A, instead of reading the trees at
the same level. This adjustment is also done to the common
ancestor tree.


[System] You are a helpful assistant.

[User] git-reset - Reset current HEAD to the specified state  Undo a merge or pull

[Assistant]
$ git pull (1) Auto-merging nitfol
CONFLICT (content): Merge conflict in nitfol
Automatic merge failed; fix conflicts and then commit the result.
$ git reset --hard (2) $ git pull . topic/branch (3) Updating from 41223... to 13134...
Fast-forward
$ git reset --hard ORIG_HEAD (4) Try to update from the upstream resulted in a lot of
conflicts; you were not ready to spend a lot of time merging
right now, so you decide to do that later. "pull" has not made merge commit, so git reset --hard which is a synonym for git reset --hard HEAD clears the mess
from the index file and the working tree. Merge a topic branch into the current branch, which resulted
in a fast-forward. But you decided that the topic branch is not ready for public
consumption yet.  "pull" or "merge" always leaves the original
tip of the current branch in ORIG_HEAD , so resetting hard to it
brings your index file and the working tree back to that state,
and resets the tip of the branch to that commit.


[System] You are a helpful assistant.

[User]
How to remove origin from git repository
Basic question: How do I disassociate a git repo from the origin from which it was cloned?
git branch -a shows:
* master
  remotes/origin/HEAD -> origin/master

and I want to remove all knowledge of origin, and the associated revisions.
Longer question: I want to take an existing subversion repo and make a number of smaller git repos from it. Each of the new git repos should have the full history of just the relevant branch. I can prune the repo to just the wanted subtree using:
git filter-branch --subdirectory-filter path/to/subtree HEAD

but the resulting repo still contains all the revisions of the now-discarded subtrees under the origin/master branch.
I realise that I could use the -T flag to git-svn to clone the relevant subtree of the subversion repo in the first place. I'm not sure if that would be more efficient than later running multiple instantiations of git filter-branch --subdirectory-filter on copies of the git repo but, in any case, I would still like to break the link with the origin.

[Assistant]
Fairly straightforward:
git remote rm origin

As for the filter-branch question - just add --prune-empty to your filter branch command and it'll remove any revision that doesn't actually contain any changes in your resulting repo:
git filter-branch --prune-empty --subdirectory-filter path/to/subtree HEAD


[System] You are a helpful assistant.

[User] git - the stupid content tracker  GIT_ASKPASS

[Assistant]
If this environment variable is set, then Git commands which need to
acquire passwords or passphrases (e.g. for HTTP or IMAP authentication)
will call this program with a suitable prompt as command-line argument
and read the password from its STDOUT. See also the core.askPass option in git-config .


[System] You are a helpful assistant.

[User] git - the stupid content tracker  git-imap-send

[Assistant] Send a collection of patches from stdin to an IMAP folder


[System] You are a helpful assistant.

[User] git-log - Show commit logs  --compact-summary

[Assistant]
Output a condensed summary of extended header information such
as file creations or deletions ("new" or "gone", optionally "+l"
if it’s a symlink) and mode changes ("+x" or "-x" for adding
or removing executable bit respectively) in diffstat. The
information is put between the filename part and the graph
part. Implies --stat .


[System] You are a helpful assistant.

[User]
Why use 'git rm' to remove a file instead of 'rm'?
On SVN, removing something from the filesystem directly (rather than using svn) created a load of headaches.
I haven't found this to be an issue when using git, but I notice that git has its own rm implementation (git rm).
What is the difference between rm and git rm?

[Assistant]
If you just use rm, you will need to follow it up with git add <fileRemoved>.  git rm does this in one step.
You can also use git rm --cached which will remove the file from the index (staging it for deletion on the next commit), but keep your copy in the local file system.


[System] You are a helpful assistant.

[User] git-log - Show commit logs  --pretty[=<format>]  --format=<format>

[Assistant]
Pretty-print the contents of the commit logs in a given format,
where <format> can be one of oneline , short , medium , full , fuller , reference , email , raw , format:<string> and tformat:<string> .  When <format> is none of the above,
and has %placeholder in it, it acts as if --pretty=tformat:<format> were given. See the "PRETTY FORMATS" section for some additional details for each
format.  When =<format> part is omitted, it defaults to medium . Note: you can specify the default pretty format in the repository
configuration (see git-config ).


[System] You are a helpful assistant.

[User]
Git command to display HEAD commit id?
What command can I use to print out the commit id of HEAD?
This is what I'm doing by hand:
$ cat .git/HEAD
ref: refs/heads/v3.3
$ cat .git/refs/heads/v3.3
6050732e725c68b83c35c873ff8808dff1c406e1

But I need a script that can reliably pipe the output of some command to a text file such that the text file contains exactly the commit id of HEAD (nothing more or less, and not just a ref).  Can anyone help?

[Assistant]
Use the command:
git rev-parse HEAD

For the short version:
git rev-parse --short HEAD


[System] You are a helpful assistant.

[User] git-diff-index - Compare a tree to the working tree or index  --[no-]rename-empty

[Assistant] Whether to use empty blobs as rename source.


[System] You are a helpful assistant.

[User]
Merging 2 branches together in Git
I've only just started to use Git and think it is wonderful, however I'm a little confused over what the merge command does.
Let us say we have a working project in the branch "A".
I go home and make changes to this branch and save it as "B".
Another programmer makes changes to "A" and saves it as "C".
Is there a way to merge the two branches "B" and "C" together, then commit the changes as a new branch, say "D"?
Or am missing the point of 'merge'?

[Assistant]
merge is used to bring two (or more) branches together.
A little example:
$ # on branch A:
$ # create new branch B
$ git checkout -b B
$ # hack hack
$ git commit -am "commit on branch B"

$ # create new branch C from A
$ git checkout -b C A
$ # hack hack
$ git commit -am "commit on branch C"

$ # go back to branch A
$ git checkout A
$ # hack hack
$ git commit -am "commit on branch A"

So now there are three separate branches (namely A B and C) with different heads.
To get the changes from B and C back to A, checkout A (already done in this example) and then use the merge command:
$ # create an octopus merge
$ git merge B C

Your history will then look something like this:
…-o-o-x-------A
      |\     /|
      | B---/ |
       \     /
        C---/

If you want to merge across repository/computer borders, have a look at git pull command, e.g. from the PC with branch A (this example will create two new commits):
$ # pull branch B
$ git pull ssh://host/… B
$ # pull branch C
$ git pull ssh://host/… C


[System] You are a helpful assistant.

[User] git-show - Show various types of objects  --remerge-diff

[Assistant]
Produce remerge-diff output for merge commits.
Shortcut for --diff-merges=remerge -p .


[System] You are a helpful assistant.

[User]
What is github 'compare & pull request'
I am working on a MeteorIntegration (feature) branch that is published. I did a git push assuming the push was going to the checked-out branch MeteorIntegration:
And now I see the following on both master and MeteorIntegration branches.

I read github documentation: Closing a pull request and Tidying up Pull Requests but that didn't help, possibly because I am not dealing with a pull request here?
How do I get rid of this compare & pull request?

[Assistant]
You don't actually have a pull request; GitHub just sees that you've pushed a branch, and is offering to create a pull request for it if you want.
If you don't care about that, just ignore it.  It's completely harmless and will go away as soon as GitHub doesn't think the branch is "recent".


[System] You are a helpful assistant.

[User] git-config - Get and set repository or global options  diff.wordRegex

[Assistant]
A POSIX Extended Regular Expression used to determine what is a "word"
when performing word-by-word difference calculations.  Character
sequences that match the regular expression are "words", all other
characters are ignorable whitespace.


[System] You are a helpful assistant.

[User]
markdown link to header

I'm using GitLab to write a read.me file.
I tried to create a link to a header. According to the wiki an id should be automatically created:
see here
I created a header using:
### 1. This is my Header

and tried to create a link to it:
[link](#1--this-is-my-header)

but it is not working.
What am I doing wrong?

[Assistant]
In the Documentation you link to we learn that...

The IDs are generated from the content of the header according to the
  following rules:

All text is converted to lowercase.
All non-word text (e.g., punctuation, HTML) is removed.
All spaces are converted to hyphens.
Two or more hyphens in a row are converted to one.
If a header with the same ID has already been generated, a unique incrementing number is appended, starting at 1.

Note rule 4: "Two or more hyphens in a row are converted to one." However, the example you tried has two hyphens in a row (after the 1). Remove one of them and you should have it.
[link](#1-this-is-my-header)

From time to time I have encountered a unique header which is converted into an ID in some non-obvious way. A quick way to work out the ID is to use your browser's view source and/or inspect tools to view the HTML source code. For example, you might find the following HTML for your example:

1. This is my Header

Then just use the contents of the id attribute with a hash to link to that header: #1-this-is-my-header.


[System] You are a helpful assistant.

[User]
Inline code syntax highlighting in GitHub markdown?

GitHub-flavored markdown supports syntax highlighting in codeblocks. This is done by adding the name of the language next to the triple-grave codeblock markers:
```ruby
require 'redcarpet'
markdown = Redcarpet.new("Hello World!")
puts markdown.to_html
```

Standard markdown also supports inline codeblocks by wrapping text in `single graves`. Is there any way to add syntax highlighting to these inline codeblocks?

[Assistant]
GitHub comments, wikis, README.md etc. use GFM, essentially CommonMark with some extensions, where it's not possible to add syntax highlighting. (Follow the link to see whether anything has changed, but don't hold your breath because nothing has in the last decade.)
However, GitHub Pages uses Jekyll and by extension kramdown where you can use:
`x = 4`{:.ruby}

P.S. If you happen to use pandoc, the syntax is:
`x = 4`{.ruby}


[System] You are a helpful assistant.

[User]
gitignore not ignoring file
No matter what I put in .gitignore I can not get git to ignore the UserInterfaceState.xcuserstate file below:
$ git status
On branch master
Your branch is up-to-date with 'origin/master'.

Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

    modified:   .gitignore
    modified:  CalFoo.xcodeproj/project.xcworkspace/xcuserdata/wcochran.xcuserdatad/UserInterfaceState.xcuserstate

I am using/editing the .gitignore file listed on this post.
I tried everything to match the pattern including the exact pathname: CalFoo.xcodeproj/project.xcworkspace/xcuserdata/wcochran.xcuserdatad/UserInterfaceState.xcuserstate to no avail.
This particular problem arises from the workflow where Xcode is used to create the initial git repo and the .gitignore file from here is added afterwards. A more general answer to ignoring previously tracked files in git can be found from this question (I guess I never found this post in my search since it didn't have "gitignore" in the title).

[Assistant]
You can only ignore unversioned files but that file is already known to git.
If you want git to track that file, there is no need to tell git to ignore it.
If you don't want git to track that file use git rm and your ignore rule will start working.
Caution: git rm will remove the file. Use git rm --cached to remove from the repo but not from the disk.


[System] You are a helpful assistant.

[User] git-rev-list - Lists commit objects in reverse chronological order  %C(…)

[Assistant]
color specification, as described under Values in the
"CONFIGURATION FILE" section of git-config .  By
default, colors are shown only when enabled for log output
(by color.diff , color.ui , or --color , and respecting
the auto settings of the former if we are going to a
terminal). %C(auto,...) is accepted as a historical
synonym for the default (e.g., %C(auto,red) ). Specifying %C(always,...) will show the colors even when color is
not otherwise enabled (though consider just using --color=always to enable color for the whole output,
including this format and anything else git might color). auto alone (i.e. %C(auto) ) will turn on auto coloring
on the next placeholders until the color is switched
again.


[System] You are a helpful assistant.

[User] git-log - Show commit logs  %N

[Assistant] commit notes


[System] You are a helpful assistant.

[User] git-grep - Print lines matching a pattern  git grep -e '#define' --and \( -e MAX_PATH -e PATH_MAX \)

[Assistant] Looks for a line that has #define and either MAX_PATH or PATH_MAX .


[System] You are a helpful assistant.

[User]
Why does Git use a cryptographic hash function?
Why does Git use SHA-1, a cryptographic hash function, instead of a faster non-cryptographic hash function?
Related question:
Stack Overflow question Why does Git use SHA-1 as version numbers? asks why Git uses SHA-1 as opposed to sequential numbers for commits.

[Assistant]
TLDR;

from 2005 up to 2018/Git 2.18: SHA-1 (see below)
2019, will switch at some point to SHA-256

You can check that from Linus Torvalds himself, when he presented Git to Google back in 2007:
(emphasis mine)

We check checksums that is considered cryptographically secure. Nobody has been able to break SHA-1, but the point is, SHA-1 as far as git is concerned, isn't even a security feature. It's purely a consistency check.
   The security parts are elsewhere. A lot of people assume since git uses SHA-1 and SHA-1 is used for cryptographically secure stuff, they think that it's a huge security feature. It has nothing at all to do with security, it's just the best hash you can get.
Having a good hash is good for being able to trust your data, it happens to have some other good features, too, it means when we hash objects, we know the hash is well distributed and we do not have to worry about certain distribution issues.
Internally it means from the implementation standpoint, we can trust that the hash is so good that we can use hashing algorithms and know there are no bad cases.
So there are some reasons to like the cryptographic side too, but it's really about the ability to trust your data.
  I guarantee you, if you put your data in git, you can trust the fact that five years later, after it is converted from your harddisc to DVD to whatever new technology and you copied it along, five years later you can verify the data you get back out is the exact same data you put in. And that is something you really should look for in a source code management system.

Update Dec. 2017 with Git 2.16 (Q1 2018): this effort to support an alternative SHA is underway: see "Why doesn't Git use more modern SHA?".

I mentioned in "How would git handle a SHA-1 collision on a blob?" that you could engineer a commit with a particular SHA1 prefix (still an extremely costly endeavor).
But the point remains, as Eric Sink  mentions in "Git: Cryptographic Hashes" (Version Control by Example (2011) book:

It is rather important that the DVCS never encounter two different pieces of data which have the same digest. Fortunately, good cryptographic hash functions are designed to make such collisions extremely unlikely.

It is harder to find good non-cryptographic hash with low collision rate, unless you consider research like "Finding State-of-the-Art Non-cryptographic Hashes with Genetic Programming".
You can also read "Consider use of non-cryptographic hash algorithm for hashing speed-up", which mentions for instance "xxhash", an extremely fast non-cryptographic Hash algorithm, working at speeds close to RAM limits.

Discussions around changing the hash in Git are not new:

either to optimize it (August 2009), but you have to take license issue:

(Linus Torvalds)

There's not really anything remaining of the mozilla code, but hey, I started from it. In retrospect I probably should have started from the PPC asm code that already did the blocking sanely - but that's a "20/20 hindsight" kind of thing.
Plus hey, the mozilla code being a horrid pile of crud was why I was so convinced that I could improve on things. So that's a kind of source for  it, even if it's more about the motivational side than any actual remaining code ;)

And you need to be careful about how to measure the actual optimization gain
(Linus Torvalds)

I pretty much can guarantee you that it improves things only because it makes gcc generate crap code, which then hides some of the P4 issues.

or to change it altogether (January 2010)
(for instance to SHA-3, but that would apply to any other hash):

(John Tapsell - johnflux)

The engineering cost for upgrading git from SHA-1 to a new algorithm is much higher. I'm not sure how it can be done well.
First of all we probably need to deploy a version of git (let's call it version 2 for this conversation) which allows there to be a slot for a new hash value even though it doesn't read or use that space -- it just uses the SHA-1 hash value which is in the other slot.
That way once we eventually deploy yet a newer version of git, let's call it version 3, which produces SHA-3 hashes in addition to SHA-1 hashes, people using git version 2 will be able to continue to inter-operate.
  (Although, per this discussion, they may be vulnerable and people who rely on their SHA-1-only patches may be vulnerable.)

In short, switching to any hash is not easy.

Update February 2017: yes, it is in theory possible to compute a colliding SHA1: shattered.io

How is GIT affected?
GIT strongly relies on SHA-1 for the identification and integrity checking of all file objects and commits.
  It is essentially possible to create two GIT repositories with the same head commit hash and different contents, say a benign source code and a backdoored one.
  An attacker could potentially selectively serve either repository to targeted users. This will require attackers to compute their own collision.

But:

This attack required over 9,223,372,036,854,775,808 SHA1 computations. This took the equivalent processing power as 6,500 years of single-CPU computations and 110 years of single-GPU computations.

So let's not panic just yet.
See more at "How would Git handle a SHA-1 collision on a blob?".


[System] You are a helpful assistant.

[User] git - the stupid content tracker  --noglob-pathspecs

[Assistant]
Add "literal" magic to all pathspec. This is equivalent to setting
the GIT_NOGLOB_PATHSPECS environment variable to 1 . Enabling
globbing on individual pathspecs can be done using pathspec
magic ":(glob)"


[System] You are a helpful assistant.

[User] git-log - Show commit logs  --left-right

[Assistant]
Mark which side of a symmetric difference a commit is reachable from.
Commits from the left side are prefixed with < and those from
the right with > .  If combined with --boundary , those
commits are prefixed with - . For example, if you have this topology: y---b---b  branch B
	    / \ /
	   /   .
	  /   / \
	 o---x---a---a  branch A you would get an output like this: $ git rev-list --left-right --boundary --pretty=oneline A...B

	>bbbbbbb... 3rd on b
	>bbbbbbb... 2nd on b
	<aaaaaaa... 3rd on a
	<aaaaaaa... 2nd on a
	-yyyyyyy... 1st on b
	-xxxxxxx... 1st on a


[System] You are a helpful assistant.

[User]
git ignore all files except one extension and folder structure
What I want is to ignore all kind of files except the .php ones, but with this .gitignore I'm also ignoring folders...
#ignore all kind of files
*
#except php files
!*.php

Is there a way to tell git to accept my project folder structure while keeping the track only of the .php files?
It seems like now I can't add folders to my repo:
vivo@vivoPC:~/workspace/motor$ git add my_folder/
The following paths are ignored by one of your .gitignore files:
my_folder
Use -f if you really want to add them.
fatal: no files added

[Assistant]
This is simple, just add another entry !my_folder in your .gitignore
#ignore all kind of files
*
#except php files
!*.php
!my_folder

The last line will take special care of my_folder, and will not ignore any php files within it; but files within other folders will still be ignored because of the first pattern of *.
EDIT
I think I misread your question. If you want to ignore all files except .php files, you can use
#ignore all kind of files
*.*
#except php files
!*.php

This will not ignore any file which doesn't have an extension (example: if you have README and not README.txt ), and will ignore any folder with a . in its name (example: directory named module.1).
FWIW, git doesn't track directories, and hence there is no way to specify ignore rules for directory vs file


[System] You are a helpful assistant.

[User]
List all changed files with change status between Git commits (added, modified, deleted) [duplicate]
This question already has answers here:

How to list only the names of files that changed between two commits

                                (15 answers)

Closed 9 years ago.

I regularly use the following command to list files changed between two commits:
git diff --name-only SHA1 SHA2

It gives a list of files somewhat like this:

/src/example/file1
/src/example/file2
/src/example/file3

There is almost no end to how useful this is.
I'd really like to be able also to show alongside each file a brief reference to the change status, indicating whether a file was added, modified or deleted.
Here's an example to demonstrate the concept:
git diff --name-only --and-how-me-the-change-status SHA1 SHA2

A /src/example/file1
M /src/example/file2
D /src/example/file3

The change status (A, M, D) is shown as an example only, I don't mind what this is so long as it is unambiguous.
I'm aware that I can use the --diff-filter option to list only added files, or only modified files or only deleted files. Using this option means I have to run three commands to get three lists of filenames. This is nice but could be nicer.
Is there a single command I can run to give me the above example output?

[Assistant]
Use --name-status, it's the same as --name-only plus the status of changed files:
git diff --name-status SHA1 SHA2