[System] You are a helpful assistant.

[User]
What are Insertions & Deletions in Git?
When I run git commands like git commit or git log --shortstat part of the output looks like:
2 files changed, 3 insertions(+), 11 deletions(-)

What is the meaning of an insertion or a deletion?

[Assistant]
It is just number of lines inserted and number of lines deleted in that particular commit. Note that a modified line maybe treated as an insert and a delete.
Git log manual:

--shortstat
Output only the last line of the --stat format containing total
number of modified files, as well as number of added and deleted
lines.


[System] You are a helpful assistant.

[User] git-config - Get and set repository or global options  false

[Assistant]
Boolean false literals are no , off , false , 0 and the empty string. When converting a value to its canonical form using the --type=bool type
specifier, git config will ensure that the output is "true" or
"false" (spelled in lowercase).


[System] You are a helpful assistant.

[User] git-count-objects - Count unpacked number of objects and their disk consumption  -H  --human-readable

[Assistant] Print sizes in human readable format


[System] You are a helpful assistant.

[User]
Create a tag in a GitHub repository

I have a GitHub repository and I need to tag it.
I created a tag in a shell using the following command:
git tag 2.0
git tag
>>> 2.0

The tag does exist locally, but does not appear on GitHub.
How do I push this tag to GitHub?

[Assistant]
You can create tags for GitHub by either using:

the Git command line, or
GitHub's web interface.

Creating tags from the command line
To create a tag on your current branch, run this:
git tag <tagname>

If you want to include a description with your tag, add -a to create an annotated tag:
git tag <tagname> -a

This will create a local tag with the current state of the branch you are on. When pushing to your remote repo, tags are NOT included by default. You will need to explicitly say that you want to push your tags to your remote repo:
git push origin --tags

From the official Linux Kernel Git documentation for git push:

--tags

All refs under refs/tags are pushed, in addition to refspecs explicitly listed on the command line.

Or if you just want to push a single tag:
git push origin <tag>

See also my answer to How do you push a tag to a remote repository using Git? for more details about that syntax above.
Creating tags through GitHub's web interface
You can find GitHub's instructions for this at their Creating Releases help page. Here is a summary:

Click the releases link on our repository page,

Click on Create a new release or Draft a new release,

Fill out the form fields, then click Publish release at the bottom,

After you create your tag on GitHub, you might want to fetch it into your local repository too:
git fetch

Now next time, you may want to create one more tag within the same release from website. For that follow these steps:
Go to release tab

Click on edit button for the release
Provide name of the new tag ABC_DEF_V_5_3_T_2 and hit tab
After hitting tab, UI will show this message: Excellent! This tag will be created from the target when you publish this release. Also UI will provide an option to select the branch/commit
Select branch or commit
Check "This is a pre-release" checkbox for qa tag and uncheck it if the tag is created for Prod tag.
After that click on "Update Release"
This will create a new Tag within the existing Release.


[System] You are a helpful assistant.

[User] gittutorial - A tutorial introduction to Git

[Assistant]
Importing a new project Assume you have a tarball project.tar.gz with your initial work.  You
can place it under Git revision control as follows. $ tar xzf project.tar.gz
$ cd project
$ git init Git will reply Initialized empty Git repository in .git/ You’ve now initialized the working directory—you may notice a new
directory created, named .git . Next, tell Git to take a snapshot of the contents of all files under the
current directory (note the . ), with git add : $ git add . This snapshot is now stored in a temporary staging area which Git calls
the "index".  You can permanently store the contents of the index in the
repository with git commit : $ git commit This will prompt you for a commit message.  You’ve now stored the first
version of your project in Git.


[System] You are a helpful assistant.

[User] gitfaq - Frequently asked questions about using Git  How do I know if I want to do a fetch or a pull?

[Assistant]
A fetch stores a copy of the latest changes from the remote
repository, without modifying the working tree or current branch.
You can then at your leisure inspect, merge, rebase on top of, or
ignore the upstream changes.  A pull consists of a fetch followed
immediately by either a merge or rebase.  See git-pull .


[System] You are a helpful assistant.

[User]
Go to a particular revision
I cloned a Git repository of a certain project. Can I turn the files to the initial state and when I review the files go to revision 2, 3, 4 ... most recent? I'd like to have an overview of how the project was evolving.

[Assistant]
Before executing this command, keep in mind that it will leave you in a detached head status.
Use git checkout <sha1> to check out a particular commit.
Where <sha1> is the commit unique number (SHA-1 hash value) that you can obtain with git log.
Here are some options after you are in the detached head status:

Copy the files or make the changes that you need to a folder outside your Git folder, check out the branch where you need them git checkout <existingBranch> and replace files
Create a new local branch git checkout -b <new_branch_name> <sha1>

Note: to "undo" (return from) the detached head state, simply use:
git checkout <branch> (where <branch> is e.g. master).


[System] You are a helpful assistant.

[User]
Undo git pull, how to bring repos to old state
Is there any way to revert or undo git pull so that my source/repos will come to old state that was before doing git pull ?
I want to do this because it merged some files which I didn't want to do so, but only merge other remaining files. So, I want to get those files back, is that possible?
EDIT: I want to undo git merge for clarification.
After seeing some answers, I did this
git reflog
bb3139b... HEAD@{0}: pull : Fast forward
01b34fa... HEAD@{1}: clone: from ...name...

Now, what should I do ? Doing git reset --hard  is OK ? I don't want to screw it again, so asking for detailed steps ?

[Assistant]
Running git pull performs the following tasks, in order:

git fetch
git merge

The merge step combines branches that have been setup to be merged in your config. You want to undo the merge step, but probably not the fetch (doesn't make a lot of sense and shouldn't be necessary).
To undo the merge, use git reset --hard to reset the local repository to a previous state; use git-reflog to find the SHA-1 of the previous state and then reset to it.
Warning
The commands listed in this section remove all uncommitted changes, potentially leading to a loss of work:
git reset --hard

Alternatively, reset to a particular point in time, such as:
git reset --hard master@{"10 minutes ago"}


[System] You are a helpful assistant.

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

[Assistant]
Set a custom directory to store the resulting files instead of the
current working directory. All directory components will be created.


[System] You are a helpful assistant.

[User]
Post Commit Hook Not Running
My post commit hook is not running after git.  I have verified that the hook does work if I just run it from the terminal.  The code in the hook is:
#!/bin/sh
#.git/hooks/post-commit
# An example hook script that is called after a successful
# commit is made.
#
# To enable this hook, rename this file to "post-commit".

perl -pi -e 's/([a-f0-9]+)$/'$( git rev-parse HEAD )/ ../../config/commit.git

I did rename the file to post-commit in ./.git/hooks/ and the permissions are -rwxr-x-r-x so I am not sure why it doesn't work.

[Assistant]
I'll leave this here as an answer because I stumbled upon my own answer for when my post-commit hook wasn't running:
chmod +x .git/hooks/post-commit
Probably applies to any kind of hook.
In fact, probably applies to any kind of script.


[System] You are a helpful assistant.

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

[Assistant]
This is the default merge strategy when pulling or merging one
branch.  This strategy 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 strategy can detect
and handle merges involving renames.  It does not make use of
detected copies.  The name for this algorithm is an acronym
("Ostensibly Recursive’s Twin") and came from the fact that it
was written as a replacement for the previous default
algorithm, recursive . The ort strategy can take the following options: ours This option forces conflicting hunks to be auto-resolved cleanly by
favoring our version.  Changes from the other tree that do not
conflict with our side are reflected in the merge result.
For a binary file, the entire contents are taken from our side. This should not be confused with the ours merge strategy, which does not
even look at what the other tree contains at all.  It discards everything
the other tree did, declaring our history contains all that happened in it. theirs This is the opposite of ours ; note that, unlike ours , there is
no theirs merge strategy to confuse this merge option with. ignore-space-change ignore-all-space ignore-space-at-eol ignore-cr-at-eol Treats lines with the indicated type of whitespace change as
unchanged for the sake of a three-way merge.  Whitespace
changes mixed with other changes to a line are not ignored.
See also git-diff -b , -w , --ignore-space-at-eol , and --ignore-cr-at-eol . If their version only introduces whitespace changes to a line, our version is used; If our version introduces whitespace changes but their version includes a substantial change, their version is used; Otherwise, the merge proceeds in the usual way. renormalize This runs a virtual check-out and check-in of all three stages
of a file when resolving a three-way merge.  This option is
meant to be used when merging branches with different clean
filters or end-of-line normalization rules.  See "Merging
branches with differing checkin/checkout attributes" in gitattributes for details. no-renormalize Disables the renormalize option.  This overrides the merge.renormalize configuration variable. find-renames[=<n>] Turn on rename detection, optionally setting the similarity
threshold.  This is the default. This overrides the merge.renames configuration variable.
See also git-diff --find-renames . rename-threshold=<n> Deprecated synonym for find-renames=<n> . subtree[=<path>] 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  gc.rerereUnresolved

[Assistant]
Records of conflicted merge you have not resolved are
kept for this many days when git rerere gc is run.
You can also use more human-readable "1.month.ago", etc.
The default is 15 days.  See git-rerere .


[System] You are a helpful assistant.

[User] git - the stupid content tracker  --list-cmds=<group>[,<group>…]

[Assistant]
List commands by group. This is an internal/experimental
option and may change or be removed in the future. Supported
groups are: builtins, parseopt (builtin commands that use
parse-options), main (all commands in libexec directory),
others (all other commands in $PATH that have git- prefix),
list-<category> (see categories in command-list.txt),
nohelpers (exclude helper commands), alias and config
(retrieve command list from config variable completion.commands)


[System] You are a helpful assistant.

[User]
How do I force a subtree push to overwrite remote changes?
We use a subtree deployment a lá this Gist to deploy a subdirectory of our Yeoman project. In our case, the branch is called production, not gh-pages.
This worked perfectly until yesterday when the Git server rejected the command git subtree push --prefix dist origin production, saying
 ! [rejected]        9fe1683aa574eae33ee6754aad702488e0bd37df -> production (non-fast-forward)
error: failed to push some refs to '[email protected]:web-and-new-media/graduation2015.git'
hint: Updates were rejected because a pushed branch tip is behind its remote
hint: counterpart.

If I switch to the production branch locally (which is clean), git pull returns Your branch is up-to-date with 'origin/production'. even if I use the --rebase option.
I can see the contents of the production branch on the server through our web UI and there's nothing there that shouldn't be, just the compiled output of our dist directory like I'd expect.
To that end, it seems like I should safely be able to force an overwrite of these files, but how? git subtree push doesn't have a --force option.

[Assistant]
The trick was to chain the subtree split into a forced push:
git push origin `git subtree split --prefix dist master`:production --force

I got this from the Addendum of http://clontz.org/blog/2014/05/08/git-subtree-push-for-deployment/, who actually references this answer on Stack Overflow. I had skimmed this one earlier but Steve Clontz's post made it click for me.


[System] You are a helpful assistant.

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

[Assistant]
This is the standard date format as described by RFC 2822. An example value is “Tue Feb 6 11:22:18 2007 -0500”.  The Git
parser is accurate, but a little on the lenient side.  It is the
same parser used by git am when applying patches
received from email. Some malformed strings may be accepted as valid dates.  In some of
these cases Git will still be able to obtain the correct date from
the malformed string.  There are also some types of malformed
strings which Git will parse wrong, and yet consider valid.
Seriously malformed strings will be rejected. Unlike the raw format above, the time zone/UTC offset information
contained in an RFC 2822 date string is used to adjust the date
value to UTC prior to storage.  Therefore it is important that
this information be as accurate as possible. If the source material uses RFC 2822 style dates,
the frontend should let fast-import handle the parsing and conversion
(rather than attempting to do it itself) as the Git parser has
been well tested in the wild. Frontends should prefer the raw format if the source material
already uses UNIX-epoch format, can be coaxed to give dates in that
format, or its format is easily convertible to it, as there is no
ambiguity in parsing.


[System] You are a helpful assistant.

[User]
Atlassian / BitBucket Sourcetree SSH Public Key Denied
I'm working on a project in a private repository on https://www.bitbucket.com.
I'm coding it locally, then staging, commiting and pushing the update via BitBucket's / Atlassian's Windows Git client, Sourcetree.
After that, I'm pulling the files from a remote shared server, which requires SSH authentication.
I've tried the following in order to connect the git repo with the BitBucket account:

Launched the embedded Sourcetree SSH agent (Pageant)
Added my .ppk (PuTTY Private Key) to Pageant using my passphrase
Opened the SourceTree Terminal in the location of my project, let's call it C:/Project.
Used git init to initialize the repository.
Used git push -u origin --all in order to push the repo from my computer to BitBucket.
Got this error: Permission denied (publickey).
Tried to see if I can get some more verbose output by doing ssh -Tv [email protected] - Still, Permission denied.

I'm trying to figure out what exactly went wrong - did Sourcetee find my SSH key at all? Is the key not loaded in some specific place, causing this behavior?
Note: I have loaded the public key in my profile on BitBucket.

[Assistant]
To whom may have the same issue on Mac with new Sierra. Solution would be to add private key to SSH agent via:
ssh-add -K ~/.ssh/id_rsa

It looks like that identity[id_rsa] doesn't persist by SSH agent.
Note this is not a permanent solution .. You would need to do that each time you clone a new repository.At least then no need to provide private key for each push to remote.
-------- Update 28.Sep.2017 --------
Permanent solution ( On Sierra):
Steps:
1- Be sure that you have a running ssh-agent in background before doing anything.
To check if ssh-agent is running by:
pgrep 'ssh-agent'

That command returns PID (ProcessID) of that process if it's running.
If you see a value.. Go to Step#2. if not, so you need to run that agent in background by:
eval "$(ssh-agent -s)"

2- Edit ~/.ssh/config (Create if it doesn't exist as su ):
Host *
 AddKeysToAgent yes
 UseKeychain yes
 IdentityFile ~/.ssh/id_rsa

3- Then add that key agent ( that would be once ):
ssh-add -K ~/.ssh/id_rsa

That's it.
Actually Step#2 is the crucial one. I just want to provide a complete guide.
I hope that may help you.'.


[System] You are a helpful assistant.

[User]
Is it possible to set a git commit to have a timestamp prior to 1970?
Unix timestamps are signed 32 bit integers (64 bit on some systems today, or so I understand). On some software products this allows you to use dates going back as far as 1903 or so.
However, when I try the following:
git commit -m "this is a test commit" --date="1960-04-07 18:00:00"

I receive an "fatal: invalid date format" error.
This isn't very practical (I'm not a time-traveler), but I've been wondering about using git for historical purposes. Can this be forced with a git plumbing command? On a related note: does git always use a 32 bit timestamp, or does this depend on the environment it's built on?

[Assistant]
As far back as commit c64b9b8 (git 0.99, May 2005), time has always been referred as
<date>

Date in 'seconds since epoch'

commit 6eb8ae0  defines date as an unsigned long since April 2005.
TLDR;
date before unix epoch can be stored, but cannot be sure to be correctly represented.
But that has evolved since 2014 (see at the end)

Trying to represent a date before has been attempted before: see this thread

The date I'm trying to set is October 4, 1958, that is around timestamp -354808800.
First technique, using the commit --date flags with ISO 8601: it says
  "invalid date".
Second technique, described in the git ml archive, not using the porcelain:

git commit
git cat-file -p HEAD > tmp.txt
# at this point, edit the file to replace the timestamp

git hash-object -t commit -w tmp.txt
#=> 2ee8fcc02658e23219143f5bcfe6f9a4615745f9
git update-ref -m 'commit: foo' refs/heads/master \
    2ee8fcc02658e23219143f5bcfe6f9a4615745f9

Commit date is effectively updated, but git show clamps the date to zero (Jan 1 1970). tig(1) displays 55 years ago so the actual commit date is properly stored.
Last issue: when trying to push this commit to a remote repository:

#=> remote: error: object 2ee8fcc02658e23219143f5bcfe6f9a4615745f9:invalid
#       author/committer line - bad date
#=> remote: fatal: Error in object
#=> error: unpack failed: index-pack abnormal exit

Finally, when running test-date from git sources:

./test-date show -354808800
#=> -354808800 -> in the future

The discussion at the time mentioned:

I am not sure there isn't some unportability at the lowest level.
  We freely interchange between time_t and unsigned long in the low-level date code. It probably happens to work because casting the bits back and forth between signed and unsigned types generally works, as long as you end up with the type that you want.
  But it isn't necessarily portable, and there can be subtle bugs. See, for example, my recent 9ba0f033.
The good news that this is purely a code problem. The data format is fine. It would just take somebody going through the code and switching all "unsigned long" to "long long" (or time_t, or even "gittime_t" if we want to abstract it).
and fixing the parser algorithm at least in tm_to_time_t()
It is not just "sed s/unsigned long/long long", but rather checking every change to make sure that you aren't introducing new bugs, and that the code correctly handles signed
  types.
  Which is why nobody has done it. ;)

As I mentioned in 2017, in "Use future date while making git commits", Git has started to adopt a different and dedicated timestamp_t type.
As illustrated in Legilibre/Archeo-Lex issue 47:

Dates are now using the timestamp_t type, defined as typedef uintmax_t timestamp_t;, in place of unsigned long type, in order to fix some issues on 32bits platforms... and Windows 64 bits ^^.

The project archeo-lex.fr (which depends on older dates) is using git hash-object, combined with the Git repo viewer Legilibre/Archeo-Lex-web.
This is now (Feb. 2019) done, as commented by Seb35


[System] You are a helpful assistant.

[User]
use image from gitlab Registry in CI

Could you tell me if I do it in correct way:

I have create Docker image with all stuff which is need for running my tests in gitlab CI
I push it to gitlab registry
I can see on gitlab page in section Registry my image - gitlablogin/projectname
I want to use this image for CI, so in .gitlab-ci.yml I add image: gitlablogin/projectname

Before I had had in .gitlab-ci.yml
same_task:
  stage: deploy
  image: python:3
  script:
    - python -V

Now I have:
pep8:
  stage: deploy
  image: gitlablogin/projectname
  script:
    - python -V

and after this change job failed:
Running with gitlab-runner 11.4.2 (cf91d5e1)
  on docker-auto-scale 72989761
Using Docker executor with image gitlablogin/projectname ...
Pulling docker image gitlablogin/projectname ...
ERROR: Job failed: Error response from daemon: pull access denied for gitlablogin/projectname, repository does not exist or may require 'docker login' (executor_docker.go:168:0s)

Is my usage of docker in context of gitlab CI and gitlab registry is correct? I also want to keep my docker file on same repo and build new image when samething change in Dockerfile, what will be the best way to do it?

[Assistant]
Right now it is possible to use images from your gitlab registry without any special steps. Just build and push an image to your gitlab project container registry
docker build -t registry.gitlab.com/gitlabProject/projectName:build .
docker push registry.gitlab.com/gitlabProject/projectName:build

and then just specify this image in your pipeline settings:
image: registry.gitlab.com/gitlabProject/projectName:build

Gitlab is able to pull this image using it's credentials:
Preparing the "docker+machine" executor
00:46
 Using Docker executor with image registry.gitlab.com/gitlabProject/projectName:build ...
 Authenticating with credentials from job payload (GitLab Registry)
 Pulling docker image registry.gitlab.com/gitlabProject/projectName:build ...
 Using docker image sha256:e7e0f4f5fa8cff8a93b1f37ffd7dd0505946648246aa921dd457c06a1607304b for registry.gitlab.com/gitlabProject/projectName:build ...

More: https://docs.gitlab.com/runner/configuration/advanced-configuration.html#support-for-gitlab-integrated-registry


[System] You are a helpful assistant.

[User]
How do I call git diff on the same file between 2 different local branches?
Is there a way to check the difference between the working directory in my current branch against the working directory of another branch in a specific file? For example, if I'm working in branch A on file 1, I want to compare the difference with file 1 on branch B.

[Assistant]
Use the git diff branch branch filename syntax:
git diff branchA branchB -- file.cs

put the two names of your branches and optionally use the -- filename option to specify one file! Good luck, let me know if you have issues.


[System] You are a helpful assistant.

[User] git-rev-parse - Pick out and massage parameters  --exclude=<glob-pattern>

[Assistant]
Do not include refs matching <glob-pattern> that the next --all , --branches , --tags , --remotes , or --glob would otherwise
consider. Repetitions of this option accumulate exclusion patterns
up to the next --all , --branches , --tags , --remotes , or --glob option (other options or arguments do not clear
accumulated patterns). The patterns given should not begin with refs/heads , refs/tags , or refs/remotes when applied to --branches , --tags , or --remotes ,
respectively, and they must begin with refs/ when applied to --glob or --all . If a trailing /* is intended, it must be given
explicitly.


[System] You are a helpful assistant.

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

[Assistant] Apply a series of patches from a mailbox


[System] You are a helpful assistant.

[User] git-show - Show various types of objects  --[no-]rename-empty

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


[System] You are a helpful assistant.

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

[Assistant] Show commit logs


[System] You are a helpful assistant.

[User]
Remove a file from a Git repository without deleting it from the local filesystem
I want to remove a file from my repository.
git rm file_to_remove.txt

will remove the file from the repository, but it will also remove the file from the local file system. How do I remove this file from the repo without deleting my local copy of the file?

[Assistant]
The git rm documentation states:

When --cached is given, the staged content has to match either the tip of the branch or the file on disk, allowing the file to be removed from just the index.

So, for a single file:
git rm --cached file_to_remove.txt

and for a single directory:
git rm --cached -r directory_to_remove


[System] You are a helpful assistant.

[User]
How to continue job even when script fails

I have a job in my pipeline that has a script with two very important steps:

mvn test to run JUnit tests against my code
junit2html to convert the XML result of the tests to a HTML format (only possible way to see the results as my pipelines aren't done through MRs) that is uploaded to GitLab as an artifact
docker rm to destroy a container created earlier in the pipeline

My problem is that when my tests fail, the script stops immediately at mvn test, so the junit2html step is never reached, meaning the test results are never uploaded in the event of failure, and docker rm is never executed either, so the container remains and messes up subsequent pipelines as a result.
What I want is to be able to keep a job going till the end even if the script fails at some point. Basically, the job should still count as failed in GitLab CI / CD, but its entire script should be executed. How can I configure this?

[Assistant]
In each step that you need to continue even if the step fails, you can add a flag to your .gitlab-ci.yml file in that step. For example:
...
Unit Tests:
  stage: tests
  only:
    - branches
  allow_failure: true
  script:
    - ...

It's that allow_failure: true flag that will continue the pipeline even if that specific step fails. Gitlab CI Documentation about allow_failure is here: https://docs.gitlab.com/ee/ci/yaml/#allow_failure
Update from comments:
If you need the step to keep going after a failure, and be aware that something failed, this has worked well for me:
./script_that_fails.sh || FAILED=true

if [ $FAILED ]
    then ./do_something.sh
fi


[System] You are a helpful assistant.

[User]
List submodules in a Git repository
I have a Git repository that has several submodules in it. How do I list the names of all the submodules after git submodule init has been run?
The git submodule foreach command could echo the names of the submodule, but that only works once they have been checked out which has not happened after the init step. There are more steps in the chain that need to happen before they can be checked out, and I don't want to have to hard-wire names of submodules into the script.
So is there a Git command to get the names of all currently registered, but not yet checked out submodules?

[Assistant]
You could use the same mechanism as git submodule init uses itself, namely, look at .gitmodules. This files enumerates each submodule path and the URL it refers to.
For example, from root of repository, cat .gitmodules will print contents to the screen (assuming you have cat).
Because .gitmodule files have the Git configuration format, you can use git config to parse those files:
git config --file .gitmodules --name-only --get-regexp path

Would show you all submodule entries, and with
git config --file .gitmodules --get-regexp path | awk '{ print $2 }'

you would only get the submodule path itself.


[System] You are a helpful assistant.

[User]
How to duplicate a git repository on gitlab/github without forking?

I've an existing repository on Gitlab / Github. I want a duplicate of that under the same group with a different repo name.
Note: Thought the answers might be similar to another question, I was not able to find the said another question by googling, I'm guessing other users might be unable to do so either.

[Assistant]
In gitlab there is functionality out of the box:

Go to Settings -> General of existing project
Last expanded panel Advanced contains Export button. Click it and then on the top of this page you can see info message Project export started. A download link will be sent by email.
Check email. There is following message:

Project NAME_OF_YOUR_EXISTING_PROJECT was exported successfully.
The project export can be downloaded from: SOME_LINK
The download link will expire in 24 hours.

Click SOME_LINK and then check the Downloads folder
In the UI, click the + button at the top of the left sidebar and select `New project/repository
Click the Import project box
Click the button Gitlab export
Click Choose file and select previously downloaded file *.tar.gz
Click the button Import project
Then you will see Import in progress label.
DEAL


[System] You are a helpful assistant.

[User] gitrevisions - Specifying revisions and ranges for Git  @

[Assistant] @ alone is a shortcut for HEAD .


[System] You are a helpful assistant.

[User] git-revert - Revert some existing commits  --abort

[Assistant] Cancel the operation and return to the pre-sequence state.


[System] You are a helpful assistant.

[User] git-rev-list - Lists commit objects in reverse chronological order  --reverse

[Assistant]
Output the commits chosen to be shown (see Commit Limiting
section above) in reverse order. Cannot be combined with --walk-reflogs .


[System] You are a helpful assistant.

[User] git-log - Show commit logs  -i  --regexp-ignore-case

[Assistant]
Match the regular expression limiting patterns without regard to letter
case.


[System] You are a helpful assistant.

[User]
How can I reset or revert a file to a specific revision?
How can I revert a modified file to its previous revision at a specific commit hash (which I determined via git log and git diff)?

[Assistant]
Assuming the hash of the commit you want is c5f567:
git checkout c5f567 -- file1/to/restore file2/to/restore

The git checkout man page gives more information.
If you want to revert to the commit before c5f567, append ~1 (where 1 is the number of commits you want to go back, it can be anything):
git checkout c5f567~1 -- file1/to/restore file2/to/restore

As a side note, I've always been uncomfortable with this command because it's used for both ordinary things (changing between branches) and unusual, destructive things (discarding changes in the working directory).
For the meaning of -- in the command, refer to In Git, what does -- (dash dash) mean?

There is also a new git restore command that is specifically designed for restoring working copy files that have been modified. If your git is new enough you can use this command, but the documentation comes with a warning:

THIS COMMAND IS EXPERIMENTAL. THE BEHAVIOR MAY CHANGE.

Because git restore is experimental, it should not yet be promoted as the primary answer to this question. When the command is no longer marked as "experimental", then this answer can be amended to promote the use of git restore. [At the time of writing, the git restore command has been marked as "experimental" for at least four years.]


[System] You are a helpful assistant.

[User]
Closing gitlab merge request

We are using Gitlab (the gitlab.com free version).  My colleague is creating merge requests and we are merging from one branch (development) into another (master).  When my colleague merges into master the MR is shown as Merged.  I am then running some tests on the merged branch (not done automatically through GL currently) and when happy with the merge I am wanting to close the merge request.  However I do  not have any option to close it - I do not have a close button and if I type /close in the comments it does not do anything.
Neither my colleague or myself are able to close the MRs.  We both have Master status and have tried changing various MR project settings but to no avail.
PLease can anyone help?

[Assistant]
In Gitlab, the merged status means the relevant commits have been merged and no action is needed.
A closed merge request is one that has been put aside or considered irrelevant. It is therefore not merged into the code base.
Therefore, you only merge MRs when you're happy with the changes and close them if you think the changes are not worthy of being integrated into the code base ever.
A typical workflow would be the following:

User A works on a new feature in a feature branch and pushes their work to that branch.
They can open a merge request to merge their feature branch into master.
User B pulls the feature branch, eventually rebasing it onto master, and runs the tests they want.
If User B is happy with the changes/new feature, they can merge the MR  into master (or whatever branch you merge into)
The merge request will be shown as merged

Of course it's better if the tests run automatically in a CI.


[System] You are a helpful assistant.

[User]
Git: Show all of the various changes to a single line in a specified file over the entire git history
I've looked around, and am not sure if this is possible, but here goes:
I have a (javascript) file (say /lib/client.js) in which I have a unique identifier assigned to a variable, like so:
   var identifier = "SOME_IDENTIFIER";
You can think of the identifier like a version number:  Periodically, we'll change this variable to a new identifier.
What I'd like to do is find all of the unique identifiers we've ever used.  How can I do this with git?
I imagine there might be a way to search through the git history, and print the line matching "var identifier =".  I could de-dupe this list manually.
Anyway, I'd appreciate any insight here.  Thanks.

[Assistant]
Since Git 1.8.4, there is a more direct way to answer your question.
Assuming that line 110 is the line saying var identifier = "SOME_IDENTIFIER";, then do this:
git log -L110,110:/lib/client.js

This will return every commit which touched that line of code.
See git-log's documentation for the -L command line parameter.


[System] You are a helpful assistant.

[User] gittutorial - A tutorial introduction to Git

[Assistant]
Making changes Modify some files, then add their updated contents to the index: $ git add file1 file2 file3 You are now ready to commit.  You can see what is about to be committed
using git diff with the --cached option: $ git diff --cached (Without --cached , git diff will show you any changes that
you’ve made but not yet added to the index.)  You can also get a brief
summary of the situation with git status : $ git status
On branch master
Changes to be committed:
  (use "git restore --staged <file>..." to unstage)

	modified:   file1
	modified:   file2
	modified:   file3 If you need to make any further adjustments, do so now, and then add any
newly modified content to the index.  Finally, commit your changes with: $ git commit This will again prompt you for a message describing the change, and then
record a new version of the project. Alternatively, instead of running git add beforehand, you can use $ git commit -a which will automatically notice any modified (but not new) files, add
them to the index, and commit, all in one step. A note on commit messages: Though not required, it’s a good idea to
begin the commit message with a single short (no more than 50
characters) line summarizing the change, followed by a blank line and
then a more thorough description. The text up to the first blank line in
a commit message is treated as the commit title, and that title is used
throughout Git.  For example, git-format-patch turns a
commit into email, and it uses the title on the Subject line and the
rest of the commit in the body.


[System] You are a helpful assistant.

[User]
How to run a specific job in gitlab CI

We are facing a problem where we need to run one specific job in gitlab CI. We currently not know how to solve this problem. We have multitple jobs defined in our .gitlab-ci.yml but we only need to run a single job within our pipelines. How could we just run one job e.g. job1 or job2? We can't use tags or branches as a software switch in our environment.
.gitlab-ci.yml:
before_script:
  - docker info

job1:
  script:
    - do something

job2:
  script:
    - do something

[Assistant]
You can use a gitlab variable expression with only/except like below and then pass the variable into the pipeline execution as needed.
This example defaults to running both jobs, but if passed 'true' for "firstJobOnly" it only runs the first job.
Old Approach -- (still valid as of gitlab 13.8) - only/except
variables:
  firstJobOnly: 'false'

before_script:
  - docker info

job1:
  script:
    - do something

job2:
  script:
    - do something
  except:
    variables:
      - $firstJobOnly =~ /true/i

Updated Approach - rules
While the above still works, the best way to accomplish this now would be using the rules syntax. A simple example similar to my original reply is below.
If you explore the options in the rules syntax, depending on the specific project constraints there are many ways this could be achieved.
variables:
  firstJobOnly: 'false'

job1:
  script:
    - do something

job2:
  script:
    - do something
  rules:
    - if: '$firstJobOnly == "true"'
      when: never
    - when: always


[System] You are a helpful assistant.

[User]
Changed GitHub password, no longer able to push back to the remote
After I changed my GitHub password, I am unable to push to the remote:
$ git push origin master
remote: Invalid username or password.

Is there only re clone the repository?

[Assistant]
If you had your remote's password changed only, not the username, then try the following command to check remote's info:-

git remote show origin

This will ask for your password for the given git user, fill that in correctly, and now try:-

git pull

or,

git push

It should work unless you have to change other things like username or remote URL, you can take a look at the following Git documentation:-

https://help.github.com/articles/setting-your-username-in-git/
https://help.github.com/articles/changing-a-remote-s-url/


[System] You are a helpful assistant.

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

[Assistant] author date, human style (like the --date=human option of git-rev-list )


[System] You are a helpful assistant.

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

[Assistant] The basic greedy diff algorithm. Currently, this is the default.


[System] You are a helpful assistant.

[User]
Git Ignore everything in a directory except subfolders
This is my folder structure:
data/
    .gitignore
    uploads/
        .gitignore

I would like to commit the folders but not the files inside them.
So I add a .gitignore files in every folder with the following content:
# Ignore everything in this directory
*
# Except this file
!.gitignore

The problem is that * matches also on directories so git tracks only data/.gitignore

[Assistant]
Please don't misuse .gitignore files. Better stick to default ways to go on this, so later developers can quickly get into your project.

Add an empty .gitkeep file in the folders that you want to commit without the files
Exclude the folders, but not the .gitkeep from your main .gitignore file.
folder/*
!folder/.gitkeep

This ignores all files in a folder, but not the .gitkeep file. Now the folder will be commited with only the .gitkeep file as content.


[System] You are a helpful assistant.

[User]
How do I ignore PyCharm configuration files in a git repository?
I don't want to commit my PyCharm config files (e.g. .idea/codeStyleSettings.xml) to my git repository, so I added the following to my .gitignore file:
.idea/
mydjangosite/.idea/

However, every time I try to make a commit within PyCharm (command k), it still wants to commit these files. How do I get PyCharm to recognize my .gitignore file and not commit these files?

[Assistant] If PyCharm offers you to commit the files, it means that you have already added them to Git. You need to remove them using 'git rm --cached' and commit the change. After that, they will be ignored by the integration according to your .gitignore settings.


[System] You are a helpful assistant.

[User]
update package.json version automatically
Before I do a small release and tag it, I'd like to update the package.json to reflect the new version of the program.
Is there a way to edit the file package.json automatically?
Would using a git pre-release hook help?

[Assistant]
Right answer
To do so, just npm version patch =)
My old answer
There is no pre-release hook originally in git. At least, man githooks does not show it.
If you're using git-extra (https://github.com/visionmedia/git-extras), for instance, you can use a pre-release hook which is implemented by it, as you can see at https://github.com/visionmedia/git-extras/blob/master/bin/git-release. It is needed only a .git/hook/pre-release.sh executable file which edits your package.json file. Committing, pushing and tagging will be done by the git release command.
If you're not using any extension for git, you can write a shell script (I'll name it git-release.sh) and than you can alias it to git release with something like:
git config --global alias.release '!sh path/to/pre-release.sh $1'
You can, than, use git release 0.4 which will execute path/to/pre-release.sh 0.4. Your script can edit package.json, create the tag and push it to the server.


[System] You are a helpful assistant.

[User]
When does Git refresh the list of remote branches?

Using git branch --all shows all remote and local branches. When does Git refresh this list?
On pull/push? And how do I refresh it using Git Bash?

[Assistant]
To update the local list of remote branches:
git remote update origin --prune

To show all local and remote branches that (local) Git knows about:
git branch -a


[System] You are a helpful assistant.

[User] git-config - Get and set repository or global options  updateSparsePath

[Assistant]
Shown when either git-add or git-rm is asked to update index entries outside the current sparse
checkout.


[System] You are a helpful assistant.

[User]
Git: Clear local and remote repo and start over
I accidentally got a repo in a bad state when trying to move a project from using ant to maven. Now, I would like to clear the repo and startover from scratch. Being new to git, I am a little cautious and not sure if I could just checkout then delete all files and folders locally then push to the remote repo or if that was actually a very bad idea. For some reason I'm having a hard time asking the correct questions in google. :D

[Assistant]
Simply remove local .git directory, remove repo from server (if it is github - do Repo -> setiings -> remove).
Then create new repository on server, and locally do:
git init
git remote add origin [email protected]:user/project.git
git add .
git commit -m "Initial commit"
git push -u origin master


[System] You are a helpful assistant.

[User]
Git refs merge vs head in pull request

The refs/pull/*/head refers to head of the PR but what about the refs/pull/*/merge, I am not finding any git commits which are shown as part of /merge in commit history. What does this /merge exactly mean for a PR and when PR has multiple commits to it, when PR is open,  When PR is closed etc
$ git ls-remote
From git@<repo url>
01c8cd97857c21cfc5d413bd64e3c0e8cc8fd03d        HEAD
37b88346a9edb426f676d080be502a1d4349c499        refs/heads/PR1
6fda26f078c00adf518ec620e94f54daa85bb894        refs/heads/PR1-1
bd88e471db4127f066b3b2f1d699b8296ca62f6d        refs/heads/PR5
25b5eec47ca186a778c93439cd81e8a4125b5d6f        refs/heads/PR6
58a82cf11218991f8f544a14ef6c57d3963690ee        refs/heads/PR7
a5831973e1a4561527551a8bc8a9d5f9436f004b        refs/heads/Pr2
01c8cd97857c21cfc5d413bd64e3c0e8cc8fd03d        refs/heads/develop
442c0bc7f8b3872660d48cbd42690be677314b94        refs/heads/master
37b88346a9edb426f676d080be502a1d4349c499        refs/pull/1/head
2db24e8a6a53ce006694c4c5db1886df44620372        refs/pull/1/merge
a5831973e1a4561527551a8bc8a9d5f9436f004b        refs/pull/2/head
4ea1814dda65e2ca8572fbbc5da9cc8141391ab8        refs/pull/2/merge
6fda26f078c00adf518ec620e94f54daa85bb894        refs/pull/3/head
b6cde57523fc73ce08dd7e588eeb606c3f047136        refs/pull/3/merge
442c0bc7f8b3872660d48cbd42690be677314b94        refs/pull/4/head
58a82cf11218991f8f544a14ef6c57d3963690ee        refs/pull/5/head
e4a82d455b8b8e81b70dfbf4f6d79a1fb5158cbb        refs/pull/5/merge
bd88e471db4127f066b3b2f1d699b8296ca62f6d        refs/pull/6/head
e8825e286aa9c36c04046c5d4ac85c9d7a4ebf5c        refs/pull/6/merge
25b5eec47ca186a778c93439cd81e8a4125b5d6f        refs/pull/7/head
ed262d8c4766b037207f3113b634c777b3a0af37        refs/pull/7/merge

for ex.
25b5eec47ca186a778c93439cd81e8a4125b5d6f        refs/pull/7/head
ed262d8c4766b037207f3113b634c777b3a0af37        refs/pull/7/merge/

what is the significance of ed262d8c4766b037207f3113b634c777b3a0af37        refs/pull/7/merge/
and this commit id ed262d8c4766b037207f3113b634c777b3a0af37         is not found anywhere

[Assistant]
The refs/pull/<number>/merge is a reference created by GitHub to keep track of what would happen if a pull request was merged. It references the merge commit between refs/pull/<number>/head and the destination branch (e.g. master).
You can think of it as a "future" commit. GitHub (as well as other Git-based collaboration platforms) use this technique to determine whether the pull request would successfully merge with all the checks passing and no merge conflicts.
Atlassian has a good explanation of the reasoning behind this server-side implementation detail here:

When you view a pull request, you’re seeing what the resultant merge commit will actually look like. We do this by actually creating a merge commit behind the scenes, and showing you the difference between it and the tip of the target branch.

They're obviously talking about Bitbucket, but the same applies to GitHub.


[System] You are a helpful assistant.

[User]
Git with large files

Situation
I have two servers, Production and Development. On Production server, there are two applications and multiple (6) databases (MySQL) which I need to distribute to developers for testing. All source codes are stored in GitLab on Development server and developers are working only with this server and don't have access to production server. When we release an application, master logs into production and pulls new version from Git. The databases are large (over 500M each and counting) and I need to distribute them as easy as possible to developers for testing.
Possible solutions

After a backup script which dumps databases, each to a single file, execute a script which pushes each database to its own branch. A developer pulls one of these branches if he wants to update his local copy.
This one was found non working.
Cron on production server saves binary logs every day and pushes them into the branch of that database. So, in the branch, there are files with daily changes and developer pulls the files he doesn't have. The current SQL dump will be sent to the developer another way. And when the size of the repository becomes too large, we will send full dump to the developers and flush all data in the repository and start from the beginning.

Questions

Is the solution possible?
If git is pushing/pulling to/from repository, does it upload/download whole files, or just changes in them (i.e. adds new lines or edits the current ones)?
Can Git manage so large files? No.
How to set how many revisions are preserved in a repository? Doesn't matter with the new solution.
Is there any better solution? I don't want to force the developers to download such large files over FTP or anything similar.

[Assistant]
Update 2017:
Microsoft is contributing to Microsoft/GVFS: a Git Virtual File System which allows Git to handle "the largest repo on the planet"
(ie: the Windows code base, which is approximately 3.5M files and, when checked in to a Git repo, results in a repo of about 300GB, and produces 1,760 daily “lab builds” across 440 branches in addition to thousands of pull request validation builds)

GVFS virtualizes the file system beneath your git repo so that git and all tools see what appears to be a normal repo, but GVFS only downloads objects as they are needed.

Some parts of GVFS might be contributed upstream (to Git itself).
But in the meantime, all new Windows development is now (August 2017) on Git.

Update April 2015: GitHub proposes: Announcing Git Large File Storage (LFS)
Using git-lfs (see git-lfs.github.com) and a server supporting it: lfs-test-server, you can store metadata only in the git repo, and the large file elsewhere. Maximum of 2 Gb per commit.

See git-lfs/wiki/Tutorial:
git lfs track '*.bin'
git add .gitattributes "*.bin"
git commit -m "Track .bin files"

Original answer:
Regarding what the git limitations with large files are, you can consider bup (presented in details in GitMinutes #24)
The design of bup highlights the three issues that limits a git repo:

huge files (the xdelta for packfile is in memory only, which isn't good with large files)
huge number of file, which means, one file per blob, and slow git gc to generate one packfile at a time.
huge packfiles, with a packfile index inefficient to retrieve data from the (huge) packfile.

Handling huge files and xdelta

The primary reason git can't handle huge files is that it runs them through xdelta, which generally means it tries to load the entire contents of a file into memory at once.
If it didn't do this, it would have to store the entire contents of every single revision of every single file, even if you only changed a few bytes of that file.
That would be a terribly inefficient use of disk space, and git is well known for its amazingly efficient repository format.

Unfortunately, xdelta works great for small files and gets amazingly slow and memory-hungry for large files.
For git's main purpose, ie. managing your source code, this isn't a problem.

What bup does instead of xdelta is what we call "hashsplitting."
We wanted a general-purpose way to efficiently back up any large file that might change in small ways, without storing the entire file every time.
We read through the file one byte at a time, calculating a rolling checksum of the last 128
bytes.

rollsum seems to do pretty well at its job. You can find it in bupsplit.c.
Basically, it converts the last 128 bytes read into a 32-bit integer. What we then do is take the lowest 13 bits of the rollsum, and if they're all 1's, we consider that to be the end of a chunk.
This happens on average once every 2^13 = 8192 bytes, so the average chunk size is 8192 bytes.
We're dividing up those files into chunks based on the rolling checksum.
Then we store each chunk separately (indexed by its sha1sum) as a git blob.

With hashsplitting, no matter how much data you add, modify, or remove in the middle of the file, all the chunks before and after the affected chunk are absolutely the same.
All that matters to the hashsplitting algorithm is the 32-byte "separator" sequence, and a single change can only affect, at most, one separator sequence or the bytes between two separator sequences.
Like magic, the hashsplit chunking algorithm will chunk your file the same way every time, even without knowing how it had chunked it previously.

The next problem is less obvious: after you store your series of chunks as git blobs, how do you store their sequence?  Each blob has a 20-byte sha1 identifier, which means the simple list of blobs is going to be 20/8192 = 0.25% of the file length.
For a 200GB file, that's 488 megs of just sequence data.

We extend the hashsplit algorithm a little further using what we call "fanout." Instead of checking just the last 13 bits of the checksum, we use additional checksum bits to produce additional splits.
What you end up with is an actual tree of blobs - which git 'tree' objects are ideal to represent.

Handling huge numbers of files and git gc

git is designed for handling reasonably-sized repositories that change relatively infrequently.  You might think you change your source code "frequently" and that git handles much more frequent changes than, say, svn can handle.
But that's not the same kind of "frequently" we're talking about.

The #1 killer is the way it adds new objects to the repository: it creates one file per blob.  Then you later run 'git gc' and combine those files into a single file (using highly efficient xdelta compression, and ignoring any files that are no longer relevant).

'git gc' is slow, but for source code repositories, the resulting super-efficient storage (and associated really fast access to the stored files) is worth it.

bup doesn't do that.  It just writes packfiles directly.
Luckily, these packfiles are still git-formatted, so git can happily access them once
they're written.

Handling huge repository (meaning huge numbers of huge packfiles)

Git isn't actually designed to handle super-huge repositories.
Most git repositories are small enough that it's reasonable to merge them all into a single packfile, which 'git gc' usually does eventually.

The problematic part of large packfiles isn't the packfiles themselves - git is designed to expect the total size of all packs to be larger than available memory, and once it can handle that, it can handle virtually any amount of data about equally efficiently.
The problem is the packfile indexes (.idx) files.

each packfile (*.pack) in git has an associated idx (*.idx) that's a sorted list of git object hashes and file offsets.
If you're looking for a particular object based on its sha1, you open the idx, binary search it to find the right hash, then take the associated file offset, seek to that offset in the packfile, and read the object contents.

The performance of the binary search is about O(log n) with the number of hashes in the pack, with an optimized first step (you can read about it elsewhere) that somewhat improves it to O(log(n)-7).
Unfortunately, this breaks down a bit when you have lots of packs.

To improve performance of this sort of operation, bup introduces midx (pronounced "midix" and short for "multi-idx") files.
As the name implies, they index multiple packs at a time.


[System] You are a helpful assistant.

[User] git-shortlog - Summarize git log output  -F  --fixed-strings

[Assistant]
Consider the limiting patterns to be fixed strings (don’t interpret
pattern as a regular expression).


[System] You are a helpful assistant.

[User] git-fast-import - Backend for fast Git data importers  --import-marks-if-exists=<file>

[Assistant]
Like --import-marks but instead of erroring out, silently
skips the file if it does not exist.


[System] You are a helpful assistant.

[User] git-branch - List, create, or delete branches  --no-track

[Assistant]
Do not set up "upstream" configuration, even if the
branch.autoSetupMerge configuration variable is set.


[System] You are a helpful assistant.

[User] git-am - Apply a series of patches from a mailbox  --no-message-id

[Assistant] Do not add the Message-ID header to the commit message. no-message-id is useful to override am.messageid .


[System] You are a helpful assistant.

[User]
git log --follow, the gitpython way
I am trying to access the commit history of a single file as in:
git log --follow -- <filename>

I have to use gitpython, so what I am doing now is:
import git
g = git.Git('repo_dir')
hexshas = g.log('--pretty=%H','--follow','--',filename).split('\n')

then I build commit objects:
repo = git.Repo('repo_dir')
commits = [repo.rev_parse(c) for c in r]

Is there a way to do it in a more gitpython-ic way?
I tried both commit.iter_parents() and commit.iter_items(), but they both rely on git-rev-list, so they don't have a --follow option.

[Assistant]
For example,
With range time:
g = git.Git("C:/path/to/your/repo")
loginfo = g.log('--since=2013-09-01','--author=KIM BASINGER','--pretty=tformat:','--numstat')
print loginfo

Output:
3       2       path/in/your/solutions/some_file.cs

You can see the added lines, removed lines and the file with these changes.


[System] You are a helpful assistant.

[User] git-config - Get and set repository or global options  fsck.skipList

[Assistant]
The path to a list of object names (i.e. one unabbreviated SHA-1 per
line) that are known to be broken in a non-fatal way and should
be ignored. On versions of Git 2.20 and later, comments ( # ), empty
lines, and any leading and trailing whitespace are ignored. Everything
but a SHA-1 per line will error out on older versions. This feature is useful when an established project should be accepted
despite early commits containing errors that can be safely ignored,
such as invalid committer email addresses.  Note: corrupt objects
cannot be skipped with this setting. Like fsck.<msg-id> this variable has corresponding receive.fsck.skipList and fetch.fsck.skipList variants. Unlike variables like color.ui and core.editor the receive.fsck.skipList and fetch.fsck.skipList variables will not
fall back on the fsck.skipList configuration if they aren’t set. To
uniformly configure the same fsck settings in different circumstances,
all three of them must be set to the same values. Older versions of Git (before 2.20) documented that the object names
list should be sorted. This was never a requirement; the object names
could appear in any order, but when reading the list we tracked whether
the list was sorted for the purposes of an internal binary search
implementation, which could save itself some work with an already sorted
list. Unless you had a humongous list there was no reason to go out of
your way to pre-sort the list. After Git version 2.20 a hash implementation
is used instead, so there’s now no reason to pre-sort the list.


[System] You are a helpful assistant.

[User]
Git on Windows: How do you set up a mergetool?
I've tried msysGit and Git on Cygwin. Both work just fine in and of themselves and both run gitk and git-gui perfectly.
Now how the heck do I configure a mergetool? (Vimdiff works on Cygwin, but preferably I would like something a little more user-friendly for some of our  Windows-loving coworkers.)

[Assistant]
To follow-up on Charles Bailey's answer, here's my git setup that's using p4merge (free cross-platform 3way merge tool); tested on msys Git (Windows) install:
git config --global merge.tool p4merge
git config --global mergetool.p4merge.cmd 'p4merge.exe \"$BASE\" \"$LOCAL\" \"$REMOTE\" \"$MERGED\"'

or, from a windows cmd.exe shell, the second line becomes :
git config --global mergetool.p4merge.cmd "p4merge.exe \"$BASE\" \"$LOCAL\" \"$REMOTE\" \"$MERGED\""

The changes (relative to Charles Bailey):

added to global git config, i.e. valid for all git projects not just the current one
the custom tool config value resides in "mergetool.[tool].cmd", not "merge.[tool].cmd" (silly me, spent an hour troubleshooting why git kept complaining about non-existing tool)
added double quotes for all file names so that files with spaces can still be found by the merge tool (I tested this in msys Git from Powershell)
note that by default Perforce will add its installation dir to PATH, thus no need to specify full path to p4merge in the command

Download: http://www.perforce.com/product/components/perforce-visual-merge-and-diff-tools

EDIT (Feb 2014)
As pointed out by @Gregory Pakosz, latest msys git now "natively" supports p4merge (tested on 1.8.5.2.msysgit.0).
You can display list of supported tools by running:
git mergetool --tool-help

You should see p4merge in either available or valid list. If not, please update your git.
If p4merge was listed as available, it is in your PATH and you only have to set merge.tool:
git config --global merge.tool p4merge

If it was listed as valid, you have to define mergetool.p4merge.path in addition to merge.tool:
git config --global mergetool.p4merge.path c:/Users/my-login/AppData/Local/Perforce/p4merge.exe

The above is an example path when p4merge was installed for the current user, not system-wide (does not need admin rights or UAC elevation)
Although ~ should expand to current user's home directory (so in theory the path should be ~/AppData/Local/Perforce/p4merge.exe), this did not work for me
Even better would have been to take advantage of an environment variable (e.g. $LOCALAPPDATA/Perforce/p4merge.exe), git does not seem to be expanding environment variables for paths (if you know how to get this working, please let me know or update this answer)


[System] You are a helpful assistant.

[User]
Squash to only one "proper" commit for github pull request

I have a repo on github which someone else (Bob, for the sake of argument) has issued a pull request for. His code's not perfect, so we go through a few rounds of markups. As I understand it, he commits and pushes to his pull-request for each set of marked up changes.
So my repository now looks like this:
master: ---o A (Chowlett
           |
           |
pull-req:  o---o---o---o
               B   C   D (all Bob)

Commit SHAs and msgs are as follows:
A:
123456 Good commit <chowlett>

B:
777ccc Fix the widget bug <bob>

C:
888ddd Review markups <bob>

D:
999eee Further markups <bob>

I'm now happy to accept this pull request; but I'd rather the pre-markup versions weren't in my repo. Can I achieve all of the following; and how?

Merge B, C & D into my repo as a single commit
Generate the "Merge pull request #99 into ..." commit as well
Have github automatically close the pull request

[Assistant]
Note that Bob doesn't have to squash his commits when he is making a GitHub PR.
Since March 2016, you can leave that operation to the maintainer (you) accepting your PR.
See "Squash your commits" and its new documentation

This is a new option which lets you force commit squashing on all pull requests merged via the merge button.


[System] You are a helpful assistant.

[User]
What's the difference between working directory and local repository?

I've created a new GitHub repository.
I'm quite confused by working directory and local repository.
When working on my own, my stuff all resides on working directory.
But when work with repo, I should check my stuff there.
But are they the same thing? or should they be separate.
Then how to commit my stuff in working directory to my local repo.
How to commit my local repo to remote repo.
How to do this by Git Bash?
Thanks!

[Assistant]
Working directory is the directory with your source files under git control (in the root of all dirs under control .git file is present).
Git is tracking the difference between your working directory and local repository, and between your local repository and (one of) remote repositories.
To see what was changed, use  $ git status.
To commit your changes (edits and/or new files) to the local repository, use $ git add and then $ git commit.
To see what was committed use $ git log.
Then, if you want to commit your changed to the remote repository, use $ git push.
Pay attention to what git commands are printing, it often contain advice what to do.
If you are working with GitHub, their help is also useful: pushing to a remote.
Good basic information is also in atlassian site.

FOR EXAMPLE:
Suppose, you initiated your git repository with $ git init in JavaRepo dir and checkouted there the project with $ git pull or $ git clone. Then JavaRepo should contain .git file (among others git dotted files) - you can check it with $ ls -a. These files itself are the local git repository, and there is no need to distinguish 'working directory' and 'local repository' directory.
So, start working with files in JavaRepo: say you changed file example.java and created new file example2.java. Execute  $ git status in JavaRepo (or in any its subdirs). It should show: 'modified: example.java', 'Untracked files: example2.java'.
Add your files to the staging area with $ git add example.java and $ git add example2.java commands from the directory with these files. (Notice that $ git add is both for changed and new files.)
And finally commit your files by $ git commit -m "example changes" (-m stays for message - comments to the commit).
$ git log should show this commit.


[System] You are a helpful assistant.

[User] git-config - Get and set repository or global options  sequencerInUse

[Assistant] Shown when a sequencer command is already in progress.


[System] You are a helpful assistant.

[User]
Git in Visual studio code says file is modified even when there is no change
I am using the Visual Studio Code for my salesforce development. I have some issues with Git as a repository. When I right-click on the package.xml and say Retrieve Source From Org, it is getting all the files from Org.
The problem is git extension is showing file is modified on the server even though I have a sample file in my local. I don't want to push all the files again and again to my git repo even when there is no change.

Any idea why this is happening and how to avoid it?
Update: I did git diff and it provides correct output. It only shows file changes that are modified. In this case only five.

[Assistant]
If we change the permission using then I also encountered that behavior. In order to overcome from this issue you can use the below commands.
git config core.filemode false

In case you want to apply for the global.
git config --global core.filemode false

See also: What are the consequences of git config core.filemode false?


[System] You are a helpful assistant.

[User]
Can I view the reflog of a remote (not remote ref)?
Is it possible to view the reflog of a remote? That is, I want to know what the output of git reflog is on another remote machine.
Note that I am not asking for the reflog of remote-tracking branches (such as origin/master); I am asking for what reflog says on the other machine.

[Assistant]
On the off chance that the remote machine is a github repository,

First use Github’s Events API to retrieve the commit SHA.
curl https://api.github.com/repos/<owner>/<repo>/events

Identify the SHA of the orphan commit-id that no longer exists in any branch.

Next, use Github’s Refs API to create a new branch pointing to the orphan commit.
curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X POST -d '{"ref":"refs/heads/D-commit", "sha":"<orphan-commit-id>"}' https://api.github.com/repos/<owner>/<repo>/git/refs

Replace <orphan-commit-id> in the above command with the SHA identified in step 2.

Finally git fetch the newly created branch into your local repository.
From there you can cherry-pick or merge the commit(s) back into your work.

Write requests (step 3) require an Authentication header – but you can also use the corresponding api client feature of the GitHub CLI tool, e.g.: gh api repos/<owner>/<repo>/git/refs -X POST -F ref=refs/heads/D-commit -F sha=<orphan-commit-id>
Check out this article for an actual example.


[System] You are a helpful assistant.

[User]
Why call git branch --unset-upstream to fixup?
I'm more of a novice when it comes to advanced operations in git. I maintain my blog using the blogging framework Octopress. Though Octopress is not under any development since 2011, it serves my purpose well and so I haven't thought of changing anything so far.
FYI, my blog is hosted on Github Pages.
Today, while working on a new post, git status showed the following message:
On branch source
Your branch is based on 'origin/master', but the upstream is gone.
  (use "git branch --unset-upstream" to fixup)

The same message repeated for all the subsequent commands such as git add ., git commit -m 'message' and git push origin source.

What does the message mean?
Is something broken?
If yes, what?
Do I need to fix it?

If possible, please point me to a pdf/web article where I can read up on this and understand it for future.
More details:
bash-3.2$ git branch -a
* source
  remotes/octopress/2.1
  remotes/octopress/HEAD -> octopress/master
  remotes/octopress/gh-pages
  remotes/octopress/linklog
  remotes/octopress/master
  remotes/octopress/refactor_with_tests
  remotes/octopress/rubygemcli
  remotes/octopress/site
  remotes/origin/source

Please let me know if more information is needed. Thanks.

[Assistant]
TL;DR version: remote-tracking branch origin/master used to exist, but does not now, so local branch source is tracking something that does not exist, which is suspicious at best—it means a different Git feature is unable to do anything for you—and Git is warning you about it.  You have been getting along just fine without having the "upstream tracking" feature work as intended, so it's up to you whether to change anything.
For another take on upstream settings, see Why do I have to "git push --set-upstream origin <branch>"?

This warning is a new thing in Git, appearing first in Git 1.8.5.  The release notes contain just one short bullet-item about it:

"git branch -v -v" (and "git status") did not distinguish among a
  branch that is not based on any other branch, a branch that is in
  sync with its upstream branch, and a branch that is configured with an
  upstream branch that no longer exists.

To describe what it means, you first need to know about "remotes", "remote-tracking branches", and how Git handles "tracking an upstream".  (Remote-tracking branches is a terribly flawed term—I've started using remote-tracking names instead, which I think is a slight improvement.  Below, though, I'll use "remote-tracking branch" for consistency with Git documentation.)
Each "remote" is simply a name, like origin or octopress in this case.  Their purpose is to record things like the full URL of the places from which you git fetch or git pull updates.  When you use git fetch remote,1 Git goes to that remote (using the saved URL) and brings over the appropriate set of updates.  It also records the updates, using "remote-tracking branches".
A "remote-tracking branch" (or remote-tracking name) is simply a recording of a branch name as-last-seen on some "remote".  Each remote is itself a Git repository, so it has branches.  The branches on remote "origin" are recorded in your local repository under remotes/origin/.  The text you showed says that there's a branch named source on origin, and branches named 2.1, linklog, and so on on octopress.
(A "normal" or "local" branch, of course, is just a branch-name that you have created in your own repository.)
Last, you can set up a (local) branch to "track" a "remote-tracking branch".  Once local branch L is set to track remote-tracking branch R, Git will call R its "upstream" and tell you whether you're "ahead" and/or "behind" the upstream (in terms of commits).  It's normal (even recommend-able) for the local branch and remote-tracking branches to use the same name (except for the remote prefix part), like source and origin/source, but that's not actually necessary.
And in this case, that's not happening.  You have a local branch source tracking a remote-tracking branch origin/master.
You're not supposed to need to know the exact mechanics of how Git sets up a local branch to track a remote one, but they are relevant below, so I'll show how this works.  We start with your local branch name, source.  There are two configuration entries using this name, spelled branch.source.remote and branch.source.merge.  From the output you showed, it's clear that these are both set, so that you'd see the following if you ran the given commands:
$ git config --get branch.source.remote
origin
$ git config --get branch.source.merge
refs/heads/master

Putting these together,2 this tells Git that your branch source tracks your "remote-tracking branch", origin/master.
But now look at the output of git branch -a, which shows all the local and remote-tracking branch names in your repository.  The remote-tracking names are listed under remotes/ ... and there is no remotes/origin/master.  Presumably there was, at one time, but it's gone now.
Git is telling you that you can remove the tracking information with --unset-upstream.  This will clear out both branch.source.origin and branch.source.merge, and stop the warning.
It seems fairly likely that what you want, though, is to switch from tracking origin/master, to tracking something else: probably origin/source, but maybe one of the octopress/ names.
You can do this with git branch --set-upstream-to,3 e.g.:
$ git branch --set-upstream-to=origin/source

(assuming you're still on branch "source", and that origin/source is the upstream you want—there is no way for me to tell which one, if any, you actually want, though).
(See also How do you make an existing Git branch track a remote branch?)
I think the way you got here is that when you first did a git clone, the thing you cloned-from had a branch master.  You also had a branch master, which was set to track origin/master (this is a normal, standard setup for git).  This meant you had branch.master.remote and branch.master.merge set, to origin and refs/heads/master.  But then your origin remote changed its name from master to source.  To match, I believe you also changed your local name from master to source.  This changed the names of your settings, from branch.master.remote to branch.source.remote and from branch.master.merge to branch.source.merge ... but it left the old values, so branch.source.merge was now wrong.
It was at this point that the "upstream" linkage broke, but in Git versions older than 1.8.5, Git never noticed the broken setting.  Now that you have 1.8.5, it's pointing this out.

That covers most of the questions, but not the "do I need to fix it" one.  It's likely that you have been working around the broken-ness for years now, by doing git pull remote branch (e.g., git pull origin source).  If you keep doing that, it will keep working around the problem—so, no, you don't need to fix it.  If you like, you can use --unset-upstream to remove the upstream and stop the complaints, and not have local branch source marked as having any upstream at all.
The point of having an upstream is to make various operations more convenient.  For instance, git fetch followed by git merge will generally "do the right thing" if the upstream is set correctly, and git status after git fetch will tell you whether your repo matches the upstream one, for that branch.
If you want the convenience, re-set the upstream.

1git pull uses git fetch, and as of Git 1.8.4, this (finally!) also updates the "remote-tracking branch" information.  In older versions of Git, the updates did not get recorded in remote-tracking branches with git pull, only with git fetch.  Since your Git must be at least version 1.8.5 this is not an issue for you.
2Well, this plus a configuration line I'm deliberately ignoring that is found under remote.origin.fetch.  Git has to map the "merge" name to figure out that the full local name for the remote-branch is refs/remotes/origin/master.  The mapping almost always works just like this, though, so it's predictable that master goes to origin/master.
3Or, with git config.  If you just want to set the upstream to origin/source the only part that has to change is branch.source.merge, and git config branch.source.merge refs/heads/source
would do it.  But --set-upstream-to says what you want done, rather than making you go do it yourself manually, so that's a "better way".


[System] You are a helpful assistant.

[User]
I'm getting a "No podspec found" message when doing "pod install" against a private gitlab pod/project container

I'm in the middle of some CocoaPods project trying to build my own private Pod, reachable via "pod install" from my main project.
It's a Swift project, and everything seemed to be working, reading the appropriate tutorials, etc...
I have to say I've been using cocoapods for some time, but I'm kind of new building my own pods and storing them in my private gitlab space.
And that seems to be my problem: Apparently I don't know how to properly store my recently created pod on my gitlab space. Additionaly, running "pod install" can't fetch my podspec file.
What I have now is a main project, with a Podfile. In this project I have the next simple definition for my pods (2 public (SpkinKit and MBProgressHUD) and 1 private, 'commons'):
My Podfile is this one:
# Uncomment this line to define a global platform for your project
platform :ios, '8.0'

target 'MyBaseApp' do
  # Comment this line if you're not using Swift and don't want to use dynamic frameworks
  use_frameworks!

  # Pods for MyBaseApp

  pod 'SpinKit'
  pod 'MBProgressHUD'
  pod 'commons', :path => 'ssh://git@internal_ip_numeric_address_of_my_gitlab_machine:2222/myusername/ios_commons_pod.git'

end

If I type "pod install --verbose" I get the following output:
Fetching external sources
-> Fetching podspec for `commons` from `ssh://git@internal_ip_numeric_address_of_my_gitlab_machine:2222/myusername/ios_commons_pod.git`
[!] No podspec found for `commons` in `ssh://git@internal_ip_numeric_address_of_my_gitlab_machine:2222/myusername/ios_commons_pod.git`

This crash doesn't allow the pod to get downloaded, and the process stops here.
What seems to be wrong? As far as I understand I DO have a podspec file in that gitlab path route.
Look at this screenshot:

The URL scheme I'm using is the SSH flavoured one, that is the one appearing on the root of my gitlab project homepage (not the HTTP/HTTPS one).
This is a limitation of the project, so I can't use the HTTP one.
OTOH I think my SSH credentials (and key setup) are stored ok on my machine. Why? because I try using a ssh shell against that URL, from the command line, and I can see "Welcome myusername" on screen without specifying any username and password (Then the gitlab machine logouts that shell for security reasons, but that's another theme. That's expected behaviour).
Whatever, I'm still not sure what exact URL format/path should I use in my base app Podfile.
Inside gitlab I have my files and podspec file stored with the structure shown in the last screenshot, but I'm still not 100% sure if I've setup everything ok.
The contents of my commons.podspec file are these:
Pod::Spec.new do |s|

  # 1
  s.platform = :ios
  s.ios.deployment_target = '8.0'
  s.name = "commons"
  s.summary = "commons test fw via pod."
  s.requires_arc = true

  # 2
  s.version = "0.1.0"

  # 3
  s.license = { :type => "MIT", :file => "LICENSE" }

  # 4 - Replace with your name and e-mail address
  s.author = { "Me" => "[email protected]" }

  # 5 - Replace this URL with your own Github page's URL (from the address bar)
  s.homepage = "http://internal_ip_numeric_address_of_my_gitlab_machine:8888/myusername"

  # 6 - Replace this URL with your own Git URL from "Quick Setup"
  s.source = { :git => "http://internal_ip_numeric_address_of_my_gitlab_machine:8888/myusername/ios_commons_pod.git", :tag => "#{s.version}"}

  # 7
  s.framework = "UIKit"
  s.dependency 'RNCryptor'

  # 8
  s.source_files = "commons/**/*.{swift}"

  # 9
  s.resources = "commons/**/*.{png,jpeg,jpg,xib,storyboard}"
end

Any hint?
Thanks.

[Assistant] The only thing you need to do is change :path => to :git => and it should download the pod from your repo.


[System] You are a helpful assistant.

[User]
How to show the first commit by 'git log'?
I have a Git project which has a long history. I want to show the first commit.
How do I do this?

[Assistant]
I found that:
git log --reverse

shows commits from start.


[System] You are a helpful assistant.

[User]
How to make git ignore a directory while merging
As interesting and useful as the answer to How to setup a git driver to ignore a folder on merge was, it did not answer the original question which still has me stumped.
Unlike the question linked to above, I have two branches with the same set of directories and for merging one into the other I need git to ignore one directory completely.
I tried it with my own merge driver as described in How do I tell git to always select my local version for conflicted merges on a specific file? but the problem with this approach is that this driver is only invoked when there is an actual conflicting file in these two branches. Whenever the changes of a file are only on one branch, git merges them without calling my merge driver.
This leads to changes in files in the directory that I do not want. Any idea how I could make git ignore each and every file in that directory all the time - whether it was touched or not?

[Assistant]
I don't actually use Git, but I think this would work for your case:
Use something like what's specified here: https://gist.github.com/564416
git checkout master
git merge --no-commit --no-ff development
git reset -- /path/to/folder # revert updates from path
git commit

Again, I don't use git, I am just deferring to how I think things work based on my experience with TryGit.

checkout master
merge, but don't commit, no fast forward.
merges are now staged, so reset that entire directory tree
commit


[System] You are a helpful assistant.

[User]
Complex Git branch name broke all Git commands
I was trying to create a branch from master with the following command,
git branch SSLOC-201_Implement___str__()_of_ProductSearchQuery

when Git suddenly stopped responding. I suspect the unescaped () are to blame, somehow. Now, whenever I try to run any Git command, I get the same error:
git:176: command not found: _of_ProductSearchQuery

with the number after git increasing every time I type a command.
Can anyone explain what happened? And how do I get back to normal? I'd like to delete that branch, but how can I do that?

[Assistant]
Problem

Can anyone explain what happened? [...] I'd love to be able to delete that branch, but Git won't work for me.

By running
git branch SSLOC-201_Implement___str__()_of_ProductSearchQuery

in zsh, you did not create any branch. Instead, you accidentally defined three shell functions, called git, branch, and SSLOC-201_Implement___str__, which ignore their parameters (if any) and whose body is _of_ProductSearchQuery. You can check for yourself that this is indeed what happened, by invoking the builtin zsh command called functions, which lists all existing shell functions:
$ functions
SSLOC-201_Implement___str__ () {
    _of_ProductSearchQuery
}
branch () {
    _of_ProductSearchQuery
}
git () {
    _of_ProductSearchQuery
}

Unfortunately, although the other two shell functions are not problematic, the shell function called "git" now shadows the bona fide git command!
$ which git
git () {
    _of_ProductSearchQuery
}
# but the real "git" is a binary file that lives in /usr/local/bin/git (or some similar path)

Therefore, you will subsequently get the error
command not found: _of_ProductSearchQuery

whenever you attempt to run a Git command, e.g. git log, git status, etc. (assuming, of course, that no command called _of_ProductSearchQuery exists).
Side note

[...] I get the same error:
git:176: command not found: _of_ProductSearchQuery

(with the number after git increasing every time I type a command)

That number simply corresponds to the value of HISTCMD, an environment variable that holds

[t]he current history event number in an interactive shell, in other words the event number for the command that caused $HISTCMD to be read.

See the zsh manual for more details.
Solution

And how do I get back to normal?

Simply delete the problematic shell function (and the other two you created by accident, while you're at it):
unset -f git
unset -f branch SSLOC-201_Implement___str__

Then everything should be fine.
What if unset is shadowed also?!
Good question! I refer you to Wumpus W. Wumbley's excellent comment below.

Branch-naming tips
Avoid any special shell characters
Yes, as pointed out in the comments, parentheses are valid characters in Git branch names; you just need to quote the name appropriately, e.g.
$ git branch 'foo()bar'
$ git branch
  foo()bar
* master
$ git checkout 'foo()bar'
Switched to branch 'foo()bar'

However, the need for quoting such names every single time when used as command-line arguments should convince you to eschew parentheses in reference names. More generally, you should (as much as possible) avoid characters that have a special meaning in shells, to prevent surprises like this one.
Use simple branch names
You should keep your branch names short and sweet anyway. Long descriptions like

SSLOC-201_Implement___str__()_of_ProductSearchQuery

belong in commit messages, not in branch names.


[System] You are a helpful assistant.

[User]
How to prevent that the password to decrypt the private key has to be entered every time when using Git Bash on Windows?
I've an automatic building service which download from a git private repository.
The problem is that when it tries to clone repository it need to provide the password, because it is not remembered; so because there is no human interaction, it waits forever the password.
How can I force it to remember from id_rsa.pub?

[Assistant]
For Windows users, just a note that this is how I set up the Git Bash environment to log me in once when I start it up. I edit my ~/.bashrc file:
eval `ssh-agent`
ssh-add

So when I start Git Bash, it looks like:
Welcome to Git (version 1.7.8-preview20111206)
(etc)
Agent pid 3376
Enter passphrase for /c/Users/starmonkey/.ssh/id_dsa:
Identity added: /c/Users/starmonkey/.ssh/id_dsa (/c/Users/starmonkey/.ssh/id_dsa)

And now I can ssh to other servers without logging in every time.


[System] You are a helpful assistant.

[User]
git svn clone results in empty directory
I have an svn repository with project structure:
/root/projectA/trunk
/root/projectA/branches
/root/projectA/tags

/root/projectB/trunk
/root/projectB/branches
/root/projectB/tags

I want to clone projectA.  When I run:
git svn clone -r <revision number>:HEAD <url>/root/projectA

I get no errors and a git repository is created under the new projectA directory.  However the directory is empty.  Am I missing soemthing?

[Assistant] My problem was using the -s or --stdlayout because my svn repo did NOT have a standard layout (trunk, branches, tags).


[System] You are a helpful assistant.

[User]
Refresh all files in buffer from disk in vim
The command to refresh a file from version on disk is :e!
How can I do the same for all files in the buffer?
Background: I need that because I am using git with multiple branches with one vim open that contains a buffer. When I checkout a branch, I would like to have vim refresh.

[Assistant]
The :checkt[ime] command is designed for this very purpose.
It will prompt you to reload any buffers that have changed; if you wish to skip the prompt, you can do :set autoread beforehand (you'll still get a prompt on buffers with local unsaved changes).
It also avoids the syntax highlighting issue mentioned by Steven Lu on the accepted answer; :bufdo turns off syntax highlighting by design.
Found via: http://vim.1045645.n5.nabble.com/Bug-report-bufdo-e-breaking-syntax-highlighting-on-displayed-buffers-tp1209995p1209998.html


[System] You are a helpful assistant.

[User] git-commit-tree - Create a new commit object  -S[<keyid>]  --gpg-sign[=<keyid>]  --no-gpg-sign

[Assistant]
GPG-sign commits. The keyid argument is optional and
defaults to the committer identity; if specified, it must be
stuck to the option without a space. --no-gpg-sign is useful to
countermand a --gpg-sign option given earlier on the command line.


[System] You are a helpful assistant.

[User]
How to retry pipeline (not individual jobs) in GitLab via the UI?

Basically I am looking for the retry button for the pipeline triggered, but all I see is a retry button for the individuals jobs of that pipeline. I don't want to have to push a commit just to retry a pipeline.
Reference screenshot

[Assistant]
You can retry the latest push on the pipeline by going to:

CI/CD -> Pipelines -> Run Pipeline -> Select the branch to run.

Otherwise, as you've mentioned, you'd have to manually press the retry button for each individual job for the pipeline (for a pipeline that isn't the latest).


[System] You are a helpful assistant.

[User]
Change Git stash message [duplicate]
This question already has answers here:

How can I rename a git stash?

                                (13 answers)

Closed 6 years ago.

I have a stash saved for the future that I want to give a meaningful name. While it's possible to pass a message as argument to git stash save, is there a way to add a message to an existing stash?

[Assistant]
You can directly edit the messages stored in .git/logs/refs/stash.
I know it's probably not ideal, but should work anyway.


[System] You are a helpful assistant.

[User] git-config - Get and set repository or global options  diverging

[Assistant] Shown when a fast-forward is not possible.


[System] You are a helpful assistant.

[User]
Forking from GitHub to Bitbucket

I'm working on a project based on CakePHP, that's hosted on GitHub. My project is being hosted on Bitbucket. Both of them use git. Basically I'd like to create a ‘fork’ (I don't know if I'm using the right terms, since I'm new to git) of CakePHP in my Bitbucket repository, in order to be able to get the updates without the need to download all the CakePHP zip/tar and replace the folder, then commit and push, but maybe with a ‘merge’(?).

[Assistant]
It's not possible to send "pull request" across different sites today. I've added a feature request for this in the Bitbucket issue tracker: #3288. I suggest you add yourself as a follower if you want to track this.
However, you can still move the source from GitHub to Bitbucket without having to download any zip files or tarballs. You make a clone from GitHub and push to Bitbucket:
$ git clone https://github.com/cakephp/cakephp
$ cd cakephp
$ git push [email protected]:mg/cakephp.git master

I created mg/cakephp as an empty Git repository in Bitbucket first. That way you can push/pull changesets from GitHub to Bitbucket.


[System] You are a helpful assistant.

[User]
Retrospectively add --recursive to a git repo
If you git clone with --recursive, you can get all the git submodules too.
If I've forgotten to add this magical flag when cloning, as can happen, how do I now go and get any submodules?
Additionally, how can I set the recursive flag as a default for future clones?

[Assistant]
You can do it with this after a simple top-level clone:
git submodule update --init --recursive

I would not recommend making clone do this by default. The proper way to do this if you are using submodules aggressively for development and not just linking to 3rd party OSS libs on github that you may upgrade once in a blue moon, is to use git slave or subtree.


[System] You are a helpful assistant.

[User] git-update-index - Register file contents in the working tree to the index  --show-index-version

[Assistant]
Report the index format version used by the on-disk index file.
See --index-version above.


[System] You are a helpful assistant.

[User] git-rev-list - Lists commit objects in reverse chronological order  --sparse

[Assistant]
All commits that are walked are included. Note that without --full-history , this still simplifies merges: if
one of the parents is TREESAME, we follow only that one, so the other
sides of the merge are never walked.


[System] You are a helpful assistant.

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

[Assistant] reflog identity name


[System] You are a helpful assistant.

[User]
How to update remote branch information?
In a git repository, a remote branch I am not tracking was deleted. When I type
git branch -r

the deleted branch still shows up (and I can check it out)
What git command do I have to run to update this info?

[Assistant]
If it were branches in remote repository that got deleted, and you want to update all local remote-tracking branches at once, you can use
$ git remote prune <remotename>

to delete all stale remote-tracking branches for a given remote (i.e. those that follow branches which were removed in remote repository).
See git remote documentation.


[System] You are a helpful assistant.

[User]
Is git stash branch-specific or for the whole repository?
I went into a branch and did some work.  I wanted to go into another branch but didn't want to commit so I did git stash.  Then I did git checkout <otherbranch>.  I did some work there and, just like in the first branch, I wanted to switch out of it before committing the work.  So I did git stash there too.  I switched back to the first branch and tried to unstash it (git stash pop) thinking it would get the stash from that specific branch.  I was surprised that it unstashed the stash from <otherbranch> (latest stashed).  I was under the impression that stash is branch-specific but this behavior indicates that there is only one stash for the whole local repository.
Is git stash branch-specific or for the whole repository?  If it is for the whole repository, can I pass options to it to make it branch-specific?

[Assistant]
No and No. git stash is per-repository.
Here is a nice page on how to use it.


[System] You are a helpful assistant.

[User]
Swap git submodule with own fork
I added a submodule to my git repo like this:
$ git submodule add git://github.com/user/some-library some-library

I've decided I want to create a fork of that library to do some adjustments. How can i swap that submodule so that it points to my own github fork instead?

[Assistant]
The submodules are stored in .gitmodules:
$ cat .gitmodules
[submodule "ext/google-maps"]
    path = ext/google-maps
    url = git://git.naquadah.org/google-maps.git

If you edit the url with a text editor, you need to run the following:
$ git submodule sync

This updates .git/config which contains a copy of this submodule list (you could also just edit the relevant [submodule] section of .git/config manually)
There might be a way to do it with only git commands, although the submodule system seems a bit incomplete (e.g see the instructions to remove a submodule)


[System] You are a helpful assistant.

[User]
GIT list of new/modified/deleted files
Is there a way to get the list of all new/deleted/modified directories/files in a local/remote repository with relation to each other in Git?

[Assistant]
The best way to list these file is using git status --porcelain.
For example:
git status --porcelain | awk 'match($1, "D"){print $2}'

shows you the tracked files which have been deleted from the local copy. You can delete all these files by appending an appropriate command to the pipe:
git status --porcelain | awk 'match($1, "D"){print $2}' | xargs git rm


[System] You are a helpful assistant.

[User] git-clone - Clone a repository into a new directory  -v  --verbose

[Assistant]
Run verbosely. Does not affect the reporting of progress status
to the standard error stream.


[System] You are a helpful assistant.

[User]
How can I diff two branches in GitHub?
I am just wondering if there is a way to simply diff two branches in GitHub? I know GitHub has capacity to do it because when we do code-reviews it does list out all the diffs nicely. I was just wondering if there is a way to do it without any code review to compare say Branch to Branch or Commit to Commit? So that when I push something to my remote branch and I want to see how my diffs are going to look like BEFORE it create a PR then it can be very helpful.
I can always be in console and do git diff but that is really not as nice and visually clear as how it shows up in web UI of GitHub. Any ideas?

[Assistant]
Use the compare feature to accomplish this.

To compare different versions of your repository, append /compare to your repository's path.


[System] You are a helpful assistant.

[User]
Why does Git tell me "No such remote 'origin'" when I try to push to origin?

I am very new to Git; I only recently created a GitHub account.
I've just tried to push my very first repository (a sample project), but I'm getting the following error:
No such remote 'origin'

I ran the following commands:
git init
git commit -m "first commit"
git remote add origin https://github.com/VijayNew/NewExample.git
git push -u origin master

However, when I ran git commit -m "first commit", I got the following message:
nothing added to commit but untracked files present (use "git add" to track)

So then I tried to set origin, using
git remote set-url origin https://github.com/VijayNew/NewExample.git

But I got the following error:
No such remote 'origin'

What did I do wrong, and what should I do?

[Assistant]
Two problems:
1 - You never told Git to start tracking any file
You write that you ran
git init
git commit -m "first commit"

and that, at that stage, you got
nothing added to commit but untracked files present (use "git add" to track).

Git is telling you that you never told it to start tracking any files in the first place, and it has nothing to take a snapshot of. Therefore, Git creates no commit. Before attempting to commit, you should tell Git (for instance):

Hey Git, you see that README.md file idly sitting in my working directory, there? Could you put it under version control for me? I'd like it to go in my first commit/snapshot/revision...

For that you need to stage the files of interest, using
git add README.md

before running
git commit -m "some descriptive message"

2 - You haven't set up the remote repository
You then ran
git remote add origin https://github.com/VijayNew/NewExample.git

After that, your local repository should be able to communicate with the remote repository that resides at the specified URL (https://github.com/VijayNew/NewExample.git)... provided that remote repo actually exists!
However, it seems that you never created that remote repo on GitHub in the first place: at the time of writing this answer, if I try to visit the correponding URL, I get

Before attempting to push to that remote repository, you need to make sure that the latter actually exists. So go to GitHub and create the remote repo in question. Then and only then will you be able to successfully push with
git push -u origin master