[System] You are a helpful assistant.

[User]
Git: checking out a file from a previous commit and amending it to HEAD
I recently committed a file to the HEAD of my branch which has errors in it. I need to do the following things:

 Get that file from one commit previous to HEAD
 Commit that file back into HEAD

What's the best way of going about that?

[Assistant]
You've practically said it yourself:
First get the file back from one commit before:
$> git checkout HEAD~1 path/to/file.ext

Then commit it:
$> git commit -a -m 'Retrieved file from older revision'

If only the changes to that file were present in the last commit, you can even use git revert:
$> git revert HEAD

I think it would be better to make this a separate commit, because it tells you exactly what you've reverted, and why. However, you can squash this into the previous commit by using the --amend switch to git commit.


[System] You are a helpful assistant.

[User]
Prevent pushing to master on GitHub?

GitHub allows you to configure your repository so that users can't force push to master, but is there a way to prevent pushing to master entirely? I'm hoping to make it so that the only way of adding to commits to master is through the GitHub pull request UI.

[Assistant]
Since the original question / answer, Github has added a new option for this to the restricted branches UI which allows you to set this up.

Require pull request reviews before merging When enabled, all commits must be made to a non-protected branch and submitted via a
pull request with the required number of approving reviews and no
changes requested before it can be merged into a branch that matches
this rule.

To find it go to Settings > Branches > Branch Protection Rules
and click 'Add Rule'.

Then, enter the name of the branch you want to protect and click the checkbox to require pull request reviews before merging.

By default, this only stops people who are not moderators. There is also another checkbox later down for ensuring that even moderators cannot merge.


[System] You are a helpful assistant.

[User]
app-release-unsigned.apk is not signed

I downloaded the zip file of an Android app on github and I'm trying to run it, but I get a dialog with this message
app-release-unsigned.apk is not signed. Please configure the signing information for the selected flavor using the Project Structure dialog.

I'm using Android Studio.
What am I supposed to do?

[Assistant]
If anyone wants to debug release build using Android Studio, follow these steps:

Set build variant to release mode.

Right click on app in left navigation pane, click Open Module Settings.
Go to Signing Tab. Add a signing config and fill in information. Select your keychain as well.

Go to Build Type tab. Select release mode and set:

-Debuggable to true.
-Signing Config to the config. (The one you just created).

Sync your gradle. Enjoy!


[System] You are a helpful assistant.

[User]
Which are the pros (and cons) of self-hosting your repositories (in other words: GitLab vs Bitbucket)? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.

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

Closed 8 years ago.

                        Improve this question

I have to decide between Bitbucket and GitLab for repository hosting (yes, they have to be private). I've used Bitbucket in the past, but now I've discovered GitLab and I find the idea of having a self-hosted repository manager quite attractive. But, I have to justify the use of one of them (especially in the case of using GitLab, because of the overhead that supposes its installation and configuration).
We have to take into account the following considerations:

I'm not sure about the backup frequency of the server where GitLab
would be installed in (I think this would be a mayor difference between the two options, but I don't know if Bitbucket assures 100% the integrity of the repos they host).
I can have access to the server from anywhere with VMWare Horizon Client, so Bitbucket and self-hosted GitLab would be tied in this point.

So, which are the reasons I should opt for self-hosted repo manager (GitLab), instead of non self-hosted one (Bitbucket)?

[Assistant]
I’ve used self-hosted repos in some occasions:

Government work. They had strict security policies and a really big team. They also had remote access for some users.
Pharmacy lab, also strict security and big team but no need for remote access though.
I also keep a home git server for a large range of projects from hardware (Raspberry Pi), to Dockerfiles for Pentests, and complimentary services.

My Pros:

Flexibility for your git server code (custom integration and modules).
Flexibility for your infrastructure.
Security - depends on your organisation
Internet connection independence
Speed - depends on your network of course but in my case (Gov work) working on site was much faster.
Data - containment and accessibility depends on you organisation

My Cons:

Its usually a better fit for large teams because of the different tasks required to maintain it.
Security - continuous monitoring just in case your neighbour gets curious…and lucky.
Maintenance - to keep up to date with new functionality you’ll have to be upgrading periodically

Hosted:
I also like the private repo functionality from both Bitbucket and Gitlab just take into consideration that Gitlab doesn’t cap user quantity. Also if you use CI Gitlab has it integrated.
Best of luck


[System] You are a helpful assistant.

[User]
Git doesn't work on MacOS Catalina: "xcrun: error: invalid active developer path (/Library/Developer/CommandLineTools), missing" [duplicate]
This question already has answers here:

Git is not working after macOS update ("xcrun: error: invalid active developer path (/Library/Developer/CommandLineTools")

                                (41 answers)

Closed 4 years ago.

After upgrading to MacOS X 10.15 Catalina, I cannot run any git commands in my shell:

The default interactive shell is now zsh.
To update your account to use zsh, please run chsh -s /bin/zsh.
For more details, please visit https://support.apple.com/kb/HT208050.
~ | git
xcrun: error: invalid active developer path (/Library/Developer/CommandLineTools), missing xcrun at: /Library/Developer/CommandLineTools/usr/bin/xcrun

I thought there's a problem with my shell, so I followed the instructions to change the default Mac OS shell back to bash, using the GUI and also using the command line:
chsh -s /bin/bash

I also restarted the computer. However, I still see the same message, even though echo "$SHELL" outputs /bin/bash.

[Assistant]
You'll need to reinstall the command line tools:
$ xcode-select --install


[System] You are a helpful assistant.

[User]
Reset local repository branch to be just like remote repository HEAD
How do I reset my local branch to be just like the branch on the remote repository?
I tried:
git reset --hard HEAD

But git status claims I have modified files:
On branch master
Changes to be committed:
  (use "git reset HEAD <file>..." to unstage)
      modified:   java/com/mycompany/TestContacts.java
      modified:   java/com/mycompany/TestParser.java

[Assistant]
Setting your branch to exactly match the remote branch can be done in two steps:
git fetch origin
git reset --hard origin/master

If you want to save your current branch's state before doing this (just in case), you can do:
git commit -a -m "Saving my work, just in case"
git branch my-saved-work

Now your work is saved on the branch "my-saved-work" in case you decide you want it back (or want to look at it later or diff it against your updated branch).
Note that the first example assumes that the remote repo's name is "origin" and that the branch named "master" in the remote repo matches the currently checked-out branch in your local repo.
BTW, this situation that you're in looks an awful lot like a common case where a push has been done into the currently checked out branch of a non-bare repository. Did you recently push into your local repo? If not, then no worries -- something else must have caused these files to unexpectedly end up modified. Otherwise, you should be aware that it's not recommended to push into a non-bare repository (and not into the currently checked-out branch, in particular).


[System] You are a helpful assistant.

[User]
Synchronizing a local Git repository with a remote one
I want to synchronize my local repository with a remote one so that my local repository becomes a 100% copy of the remote one - meaning that if certain files differ in these repositories, we override the local ones with the remote ones, and if there are files in local repositories that do not exist in the remote, the local files get removed.
Is there any way to achieve that other than by doing a fresh clone of remote repository?
Similar question as Sync local git repo with remote in one shot discarding local changes/commits.

[Assistant]
[Edited answer] There is a few parts to consider:
While not really operating a 'full sync' with the remote, the following will probably achieve what you need.
Note: you may lose local changes.
The Branch references
When fetching from a repository, the new (remote) references are synced up automatically but the old ones aren't cleaned out from the local. The purge option fixes that. [original answer]
git fetch --prune

-p, --prune
Before fetching, remove any remote-tracking references that no longer exist on the remote. git fetch prune option doc on git-scm

The pull command also has the prune option (--prune or -p) see git-scm doc
git pull -p

The commits
All local branches could potentially be out of sync.
To sync up the current branch with the remote, and potentially lose local work, reset it to the remote position:
git reset --hard origin/<current_branch_name>

Again, caution: this would clear out the local changes (non-committed changes & non-pushed commits).
Note: This would have left 'un-synced' any other branch.
The files/changes
The not staged for commit changes
These would have been removed by the above git reset --hard
The untracked files
These can be cleaned out using
git clean -f -d

Note that you may lose some local work.
The ignored files
Some files are declared to be ignored (via .gitignore files) and become hidden to the git tracking.
To clean them out, run:
git clean -f -d -x

Note that the git clean command comes with a handy dry-run option to avoid making that mistake a little too fast:
git clean -f -d -x -n

-n, --dry-run
Don’t actually remove anything, just show what would be done.

As the top-rated answer, I felt compelled to revisit my not really answering former reply. Thanks to the comments and other answers which helped me form a better reply.


[System] You are a helpful assistant.

[User]
How do I stop a Git commit when VI is on the screen waiting for a commit message?
I have asked Git to perform a commit from within git bash, It has brought up VI as it always does.
I now wish to cancel the commit, how do I prevent proceeding with the commit from this point?

[Assistant]
You have two options:

Provide an empty commit message. If it's a new commit and you haven't yet saved the message, you can simply use :q! (quit without saving). If you’ve already saved (or you're amending a previous commit), just delete the entire log message and save again. This can be done with ggdG + :wq in Vim.
Have the editor exit with a non-zero exit code. In Vim, you can use :cq (quit with an error code).

It's worth noting that you can always reset your working copy to the state it was in before the commit with git reset HEAD^.


[System] You are a helpful assistant.

[User] git-log - Show commit logs  --cherry-mark

[Assistant]
Like --cherry-pick (see below) but mark equivalent commits
with = rather than omitting them, and inequivalent ones with + .


[System] You are a helpful assistant.

[User] git - the stupid content tracker  GIT_TRACE_REFS

[Assistant]
Enables trace messages for operations on the ref database.
See GIT_TRACE for available trace output options.


[System] You are a helpful assistant.

[User]
What does it mean when git says a file "needs update"?
I can't for the life of me find any decent explanation of the "[file]: needs update" message that git sometimes spits out from time to time.  Even the official git FAQ has explaining this marked as a TODO.  If someone could explain A) what it means; and B) how to fix it, I would be extremely grateful.

[Assistant] It means you're trying to merge changes from somewhere, but the changes include modifications to a file that's dirty (currently modified in your working tree). You need to commit your outstanding changes, or stash them, pull/rebase/merge/whatever you're doing to update, and unstash


[System] You are a helpful assistant.

[User] git-blame - Show what revision and author last modified each line of a file  --date <format>

[Assistant]
Specifies the format used to output dates. If --date is not
provided, the value of the blame.date config variable is
used. If the blame.date config variable is also not set, the
iso format is used. For supported values, see the discussion
of the --date option at git-log .


[System] You are a helpful assistant.

[User] git-commit - Record changes to the repository  --allow-empty-message

[Assistant]
Like --allow-empty this command is primarily for use by foreign
SCM interface scripts. It allows you to create a commit with an
empty commit message without using plumbing commands like git-commit-tree .


[System] You are a helpful assistant.

[User] git-fsck - Verifies the connectivity and validity of the objects in the database

[Assistant]
DISCUSSION git-fsck tests SHA-1 and general object sanity, and it does full tracking
of the resulting reachability and everything else. It prints out any
corruption it finds (missing or bad objects), and if you use the --unreachable flag it will also print out objects that exist but that
aren’t reachable from any of the specified head nodes (or the default
set, as mentioned above). Any corrupt objects you will have to find in backups or other archives
(i.e., you can just remove them and do an rsync with some other site in
the hopes that somebody else has the object you have corrupted). If core.commitGraph is true, the commit-graph file will also be inspected
using git commit-graph verify . See git-commit-graph .


[System] You are a helpful assistant.

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

[Assistant]
The cherry-pick will stop when the commit is applied, allowing
you to examine the commit. This is the default behavior.


[System] You are a helpful assistant.

[User]
How to interactively (visually) resolve conflicts in SourceTree / git
I'm using (Windows) SourceTree for my git project. I can do it in either command prompt or Linux terminal.
But, I'm wondering whether there is a nice way to interactively and visually resolve conflicts. For example, if pull detects conflicts, popping up a GUI-based conflict tool (e.g., P4Merge). Is it possible?
I am always doing manual conflict resolving, which is just painful.
This is, for example, a git pull message, from SourceTree.
git -c diff.mnemonicprefix=false -c core.quotepath=false pull --no-commit origin master
From W:\repo\
 * branch            master     -> FETCH_HEAD

Updating 33c07bf..41e0249

error: Your local changes to the following files would be overwritten by merge:
    foo.cpp
    goo.cpp
    goo.hpp
Please, commit your changes or stash them before you can merge.
Aborting

Completed with errors, see above.

[Assistant]
From SourceTree, click on Tools->Options.  Then on the "General" tab, make sure to check the box to allow SourceTree to modify your Git config files.
Then switch to the "Diff" tab.  On the lower half, use the drop down to select the external program you want to use to do the diffs and merging.  I've installed KDiff3 and like it well enough.  When you're done, click OK.
Now when there is a merge, you can go under Actions->Resolve Conflicts->Launch External Merge Tool.


[System] You are a helpful assistant.

[User]
Fatal: could not read username for 'https //github.com' device not configured
I am trying to push code to github with SublimeGit plugin, but something weird occurs to me.

Pushing to https://github.com/username/username.github.io.git
fatal: could not read Username for 'https://github.com': Device not configured

Have been taken a lot of search before asking, like fatal: could not read Username for 'https://github.com': No such file or directory, Fatal: could not read Username for 'https://github.com': No such device or address.
But problem still remains, any effort will be appreciated.

[Assistant]
Mac OS:
Android Studio Preferences -> Git -> at bottom, Use Credentials helper (make sure it is checked)
Windows:
Android Studio File -> Settings -> Git -> Check Credentials Helper at bottom


[System] You are a helpful assistant.

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

[Assistant] Ignore changes whose lines are all blank.


[System] You are a helpful assistant.

[User]
How to generate ssh keys (for github)
Question: How do I generate ssh private and public keys (to be used in GitHub/GitLab) using command line.
The command below generates the error
sh.exe": syntax error near unexpected token '('

I am using Windows XP.
$ ssh-keygen -t rsa -C "[email protected]"
Generating public/private rsa key pair.
Enter file in which to save the key (/c/Users/xxxx/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /c/Users/xxxx/.ssh/id_rsa.
Your public key has been saved in /c/Users/xxxx/.ssh/id_rsa.pub.
The key fingerprint is:
01:0f:f4:3b:ca:85:d6:17:a1:7d:f0:68:9d:f0:a2:db [email protected]

[Assistant]
The command to run is only
ssh-keygen -t rsa -C "[email protected]"

All the rest beginning with line 2 of your script is the output of ssh-keygen.
And replace [email protected] with your email address.
Have a look at the manual for ssh-keygen to look for additional options. You should probably use a longer key by adding -b 4096 to the option list.


[System] You are a helpful assistant.

[User]
How to ignore files which are in repository?
I have a file (config.php), that is already committed to a Git repository, but I want to ignore locally, i.e. I want that file to remain in repository, but force Git to ignore any changes to it.
I put the file into .gitignore, but it is still marked as changed and Git still is attempting to commit changes to it, every time I commit something.
Any ideas, what am I missing or doing wrong?

[Assistant]
If the file is still displayed in the status, even though it is in the .gitignore, make sure it isn't already tracked.
git rm --cached config.php

If you just want to ignore it locally, you could also make it ignored by the git status:
git update-index --assume-unchanged config.php

As commented, do note that using --assume-unchanged might cause unwanted data loss as git stash resets the "ignored" files to the state in upstream, undoing local changes, without a warning or saving.


[System] You are a helpful assistant.

[User]
How can I get a side-by-side diff when I do "git diff"?
When I type git diff, I'd like to see a side-by-side diff, like with diff -y, or like to display the diff in an interactive diff tool like kdiff3. How can this be done?

[Assistant]
Try git difftool
Use git difftool instead of git diff. You'll never go back.
UPDATE to add an example usage:
Here is a link to another stackoverflow that talks about git difftool:  How do I view 'git diff' output with my preferred diff tool/ viewer?
For newer versions of git, the difftool command supports many external diff tools out-of-the-box. For example vimdiff is auto supported and can be opened from the command line by:
cd /path/to/git/repo
git difftool --tool=vimdiff

Other supported external diff tools are listed via git difftool --tool-help here is an example output:
'git difftool --tool=<tool>' may be set to one of the following:
        araxis
        kompare
        vimdiff
        vimdiff2

The following tools are valid, but not currently available:
        bc3
        codecompare
        deltawalker
        diffuse
        ecmerge
        emerge
        gvimdiff
        gvimdiff2
        kdiff3
        meld
        opendiff
        tkdiff
        xxdiff


[System] You are a helpful assistant.

[User]
Why can't I push to this bare repository?
Can you explain what is wrong with this workflow?
$ git init --bare bare
Initialized empty Git repository in /work/fun/git_experiments/bare/
$ git clone bare alice
Cloning into alice...
done.
warning: You appear to have cloned an empty repository.
$ cd alice/
$ touch a
$ git add a
$ git commit -m "Added a"
[master (root-commit) 70d52d4] Added a
 0 files changed, 0 insertions(+), 0 deletions(-)
 create mode 100644 a
$ git push
No refs in common and none specified; doing nothing.
Perhaps you should specify a branch such as 'master'.
fatal: The remote end hung up unexpectedly
error: failed to push some refs to '/work/fun/git_experiments/bare'

Doesn't git push always push to the repository I cloned from?

[Assistant]
Yes, the problem is that there are no commits in "bare".  This is a problem with the first commit only, if you create the repos in the order (bare,alice).  Try doing:
git push --set-upstream origin master

This would only be required the first time.  Afterwards it should work normally.
As Chris Johnsen pointed out, you would not have this problem if your push.default was customized.  I like upstream/tracking.


[System] You are a helpful assistant.

[User]
Multiple GitHub accounts on the same computer?

Trying to work on both my actual "work" repos, and my repos on GitHub, from my computer.
The work account was set up first, and everything works flawlessly.
My account, however, cannot seem to push to my repo, which is set up under a different account/email.
I've tried copying my work key up to my account, but that throws an error because of course a key can only be attached to one account.
How can I push/pull to and from both accounts with their respective GitHub credentials?

[Assistant]
All you need to do is configure your SSH setup with multiple SSH keypairs.

This link is easy to follow (Thanks Eric):
http://code.tutsplus.com/tutorials/quick-tip-how-to-work-with-github-and-multiple-accounts--net-22574

Generating SSH keys (Win/msysgit):
https://help.github.com/articles/generating-an-ssh-key/

Relevant steps from the first link:

Generate an SSH-key:
ssh-keygen -t ed25519 -C "[email protected]"

Follow the prompts and decide a name, e.g. id_ed25519_example_company.

Copy the SSH public-key to GitHub from ~/.ssh/id_ed25519_doe_company.pub and tell ssh about the key:
ssh-add ~/.ssh/id_ed25519_doe_company

Create a config file in ~/.ssh with the following contents:
Host github-doe-company
  HostName github.com
  User git
  IdentityFile ~/.ssh/id_ed25519_doe_company

Add your remote:
git remote add origin git@github-doe-company:username/repo.git

or change using:
git remote set-url origin git@github-doe-company:username/repo.git

Also, if you're working with multiple repositories using different personas, you need to make sure that your individual repositories have the user settings overridden accordingly:
Setting user name, email and GitHub token – Overriding settings for individual repos
https://help.github.com/articles/setting-your-commit-email-address-in-git/
Note:
Some of you may require different emails to be used for different repositories, from git 2.13 you can set the email on a directory basis by editing the global config file found at: ~/.gitconfig using conditionals like so:
[user]
    name = Default Name
    email = [email protected]

[includeIf "gitdir:~/work/"]
    path = ~/work/.gitconfig

And then your work-specific config ~/work/.gitconfig would look like this:
[user]
    name = Pavan Kataria
    email = [email protected]

Thank you @alexg for informing me of this in the comments.


[System] You are a helpful assistant.

[User] gitglossary - A Git Glossary  commit graph concept, representations and usage

[Assistant]
A synonym for the DAG structure formed by the commits
in the object database, referenced by branch tips,
using their chain of linked commits.
This structure is the definitive commit graph. The
graph can be represented in other ways, e.g. the "commit-graph" file .


[System] You are a helpful assistant.

[User]
git pull origin master does not update origin/master?

According to the documentation, git pull performs a git fetch then a git merge, however in that case performing git pull origin master should perform a git fetch origin master right?  However,  it does not appear to be doing so.  Here is an example.
Supposed my remote origin master (on GitHub in my case) has the following history:
commit 1111111 : my first commit
commit 2222222 : a commit from someone else

and I only have my first commit locally as doing following shows
git checkout master
git log --pretty=format:'%h' -n 1
1111111

git checkout origin/master
git log --pretty=format:'%h' -n 1
1111111

From here I do my pull and look at the results as follows:
git checkout master
git pull origin master

git log --pretty=format:'%h' -n 1
2222222

git checkout origin/master
git log --pretty=format:'%h' -n 1
1111111

As can be seen, the pull did in fact update my master branch with the new commit(s) from the remote origin, but my local origin/master is still where it was.  Forcing me to do the following
git fetch origin master

git checkout origin/master
git log --pretty=format:'%h' -n 1
2222222

Is this correct behavior for git pull or might I have something miss configured?  I looked through the git pull man page and didn't see anything that suggested this but I may have missed it.

[Assistant]
It's a bit weird, but if you use git pull [remote] <refspec> it actually doesn't update the remote refs. It sort of makes sense if you think about it a certain way: since you're specifying a specific ref to fetch, it doesn't have to look up anything about your remote branches, so it doesn't inherently know what remote branch it should update. It of course could figure it out, and I wouldn't be surprised if it gets fixed eventually, but that's the existing behavior. (There may be messages on the mailing list about it - I don't know.)
You can easily work around it, though. If you use git pull origin/master, since you're specifying what to fetch via a remote branch, it should update that remote branch. And if you're on your master branch anyway (or any other branch tracking origin/master), you can just do git pull and let it fill in the defaults, and it will update remote branches.
This is documented in the git-pull man page, most concisely under EXAMPLES but also elsewhere. The relevant part:

Merge into the current branch the remote branch next:
$ git pull origin next

This leaves a copy of next temporarily in FETCH_HEAD, but does not update any remote-tracking branches. Using remote-tracking branches, the same can be done by invoking fetch and merge:
$ git fetch origin
$ git merge origin/next


[System] You are a helpful assistant.

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

[Assistant]
When moved lines are colored using e.g. the diff.colorMoved setting,
this option controls the <mode> how spaces are treated.
For details of valid modes see --color-moved-ws in git-diff .


[System] You are a helpful assistant.

[User]
Why doesn't my SSH key work for connecting to github?

Note: I'm not a newb, and I've done this a gazillion times, but for some reason today it decided not to work.
I keep getting the Permission denied (publickey). error message when trying to connect to github via SSH or when trying to clone a repo, even after remaking the ssh key and adding it to "SSH Keys" in my account.
This is what I tried to do ten times today without success:

make a key with ssh-keygen.
open ~/.ssh/id_rsa.pub with Gedit or Notepad++ and copy the contents.
Go to account settings on github.com
Go to SSH Keys
Click on the Add Key button.
give the key a title
paste the key into the key box.
Save the key (enter my github password to verify).

And now, when I try doing ssh github.com it just won't work.... What in the world? Am I just too tired right now or am I missing something?
Here's the output from ssh -vvv github.com
OpenSSH_5.9p1, OpenSSL 1.0.0f 4 Jan 2012
debug1: Reading configuration data /etc/ssh/ssh_config
debug2: ssh_connect: needpriv 0
debug1: Connecting to github.com [207.97.227.239] port 22.
debug1: Connection established.
debug3: Incorrect RSA1 identifier
debug3: Could not load "/home/trusktr/.ssh/id_rsa" as a RSA1 public key
debug1: identity file /home/trusktr/.ssh/id_rsa type 1
debug1: identity file /home/trusktr/.ssh/id_rsa-cert type -1
debug1: identity file /home/trusktr/.ssh/id_dsa type -1
debug1: identity file /home/trusktr/.ssh/id_dsa-cert type -1
debug1: identity file /home/trusktr/.ssh/id_ecdsa type -1
debug1: identity file /home/trusktr/.ssh/id_ecdsa-cert type -1
debug1: Remote protocol version 2.0, remote software version OpenSSH_5.1p1 Debian-5github2
debug1: match: OpenSSH_5.1p1 Debian-5github2 pat OpenSSH*
debug1: Enabling compatibility mode for protocol 2.0
debug1: Local version string SSH-2.0-OpenSSH_5.9
debug2: fd 3 setting O_NONBLOCK
debug3: load_hostkeys: loading entries for host "github.com" from file "/home/trusktr/.ssh/known_hosts"
debug3: load_hostkeys: found key type RSA in file /home/trusktr/.ssh/known_hosts:16
debug3: load_hostkeys: loaded 1 keys
debug3: order_hostkeyalgs: prefer hostkeyalgs: [email protected],[email protected],ssh-rsa
debug1: SSH2_MSG_KEXINIT sent
debug1: SSH2_MSG_KEXINIT received
debug2: kex_parse_kexinit: ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha1,diffie-hellman-group1-sha1
debug2: kex_parse_kexinit: [email protected],[email protected],ssh-rsa,[email protected],[email protected],[email protected],[email protected],[email protected],ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521,ssh-dss
debug2: kex_parse_kexinit: aes128-ctr,aes192-ctr,aes256-ctr,arcfour256,arcfour128,aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,aes192-cbc,aes256-cbc,arcfour,[email protected]
debug2: kex_parse_kexinit: aes128-ctr,aes192-ctr,aes256-ctr,arcfour256,arcfour128,aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,aes192-cbc,aes256-cbc,arcfour,[email protected]
debug2: kex_parse_kexinit: hmac-md5,hmac-sha1,[email protected],hmac-sha2-256,hmac-sha2-256-96,hmac-sha2-512,hmac-sha2-512-96,hmac-ripemd160,[email protected],hmac-sha1-96,hmac-md5-96
debug2: kex_parse_kexinit: hmac-md5,hmac-sha1,[email protected],hmac-sha2-256,hmac-sha2-256-96,hmac-sha2-512,hmac-sha2-512-96,hmac-ripemd160,[email protected],hmac-sha1-96,hmac-md5-96
debug2: kex_parse_kexinit: none,[email protected],zlib
debug2: kex_parse_kexinit: none,[email protected],zlib
debug2: kex_parse_kexinit:
debug2: kex_parse_kexinit:
debug2: kex_parse_kexinit: first_kex_follows 0
debug2: kex_parse_kexinit: reserved 0
debug2: kex_parse_kexinit: diffie-hellman-group-exchange-sha256,diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha1,diffie-hellman-group1-sha1
debug2: kex_parse_kexinit: ssh-rsa,ssh-dss
debug2: kex_parse_kexinit: aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,arcfour128,arcfour256,arcfour,aes192-cbc,aes256-cbc,[email protected],aes128-ctr,aes192-ctr,aes256-ctr
debug2: kex_parse_kexinit: aes128-cbc,3des-cbc,blowfish-cbc,cast128-cbc,arcfour128,arcfour256,arcfour,aes192-cbc,aes256-cbc,[email protected],aes128-ctr,aes192-ctr,aes256-ctr
debug2: kex_parse_kexinit: hmac-md5,hmac-sha1,[email protected],hmac-ripemd160,[email protected],hmac-sha1-96,hmac-md5-96
debug2: kex_parse_kexinit: hmac-md5,hmac-sha1,[email protected],hmac-ripemd160,[email protected],hmac-sha1-96,hmac-md5-96
debug2: kex_parse_kexinit: none,[email protected]
debug2: kex_parse_kexinit: none,[email protected]
debug2: kex_parse_kexinit:
debug2: kex_parse_kexinit:
debug2: kex_parse_kexinit: first_kex_follows 0
debug2: kex_parse_kexinit: reserved 0
debug2: mac_setup: found hmac-md5
debug1: kex: server->client aes128-ctr hmac-md5 none
debug2: mac_setup: found hmac-md5
debug1: kex: client->server aes128-ctr hmac-md5 none
debug1: SSH2_MSG_KEX_DH_GEX_REQUEST(1024<1024<8192) sent
debug1: expecting SSH2_MSG_KEX_DH_GEX_GROUP
debug2: dh_gen_key: priv key bits set: 122/256
debug2: bits set: 510/1024
d    ebug1: SSH2_MSG_KEX_DH_GEX_INIT sent
debug1: expecting SSH2_MSG_KEX_DH_GEX_REPLY
debug1: Server host key: RSA 16:27:ac:a5:76:28:2d:36:63:1b:56:4d:eb:df:a6:48
debug3: load_hostkeys: loading entries for host "github.com" from file "/home/trusktr/.ssh/known_hosts"
debug3: load_hostkeys: found key type RSA in file /home/trusktr/.ssh/known_hosts:16
debug3: load_hostkeys: loaded 1 keys
debug3: load_hostkeys: loading entries for host "207.97.227.239" from file "/home/trusktr/.ssh/known_hosts"
debug3: load_hostkeys: found key type RSA in file /home/trusktr/.ssh/known_hosts:16
debug3: load_hostkeys: loaded 1 keys
debug1: Host 'github.com' is known and matches the RSA host key.
debug1: Found key in /home/trusktr/.ssh/known_hosts:16
debug2: bits set: 497/1024
debug1: ssh_rsa_verify: signature correct
debug2: kex_derive_keys
debug2: set_newkeys: mode 1
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug2: set_newkeys: mode 0
debug1: SSH2_MSG_NEWKEYS received
debug1: Roaming not allowed by server
debug1: SSH2_MSG_SERVICE_REQUEST sent
debug2: service_accept: ssh-userauth
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug2: key: /home/trusktr/.ssh/id_rsa (0x14cce60)
debug2: key: trusktr@rocketship (0x14ce2b0)
debug2: key: /home/trusktr/.ssh/id_dsa ((nil))
debug2: key: /home/trusktr/.ssh/id_ecdsa ((nil))
debug1: Authentications that can continue: publickey
debug3: start over, passed a different list publickey
debug3: preferred publickey,keyboard-interactive,password
debug3: authmethod_lookup publickey
debug3: remaining preferred: keyboard-interactive,password
debug3: authmethod_is_enabled publickey
debug1: Next authentication method: publickey
debug1: Offering RSA public key: /home/trusktr/.ssh/id_rsa
debug3: send_pubkey_test
debug2: we sent a publickey packet, wait for reply
debug1: Authentications that can continue: publickey
debug1: Offering RSA public key: trusktr@rocketship
debug3: send_pubkey_test
debug2: we sent a publickey packet, wait for reply
debug1: Authentications that can continue: publickey
debug1: Trying private key: /home/trusktr/.ssh/id_dsa
debug3: no such identity: /home/trusktr/.ssh/id_dsa
debug1: Trying private key: /home/trusktr/.ssh/id_ecdsa
debug3: no such identity: /home/trusktr/.ssh/id_ecdsa
debug2: we did not send a packet, disable method
debug1: No more authentication methods to try.
Permission denied (publickey).

[Assistant]
The GitHub ssh setup mentions testing your GitHub connection with:
$ ssh -T [email protected]

That follow the ssh uri syntax (also illustrated in "this answer").
But you did:
ssh github.com

(without any user). In that case, ssh reverts to the SCP syntax, which relies on a ~/.ssh/config file, with a section "github.com", to list:

the user
the hostname
(and optionally the public key location, but by default it will try ~/.ssh/id_rsa.pub)

To change it to a regular SSH URL, don't edit directly your .git/config file, as shown below.
Use the command git remote set-url:
git remote set-url origin [email protected]:username/repo.git

As noted by STEEL in the comments, should your private SSH key have a passphrase, you can add it to the ssh-agent with:

on Mac: ssh-add -K or (2023) ssh-add --apple-use-keychain
on Linux/Windows: ssh-add


[System] You are a helpful assistant.

[User]
How can I move a directory in a Git repo for all commits?
Let's say I have a repo that includes this directory structure:
repo/
  blog/
    _posts/
      some-post.html
  another-file.txt

I want to move _posts to the top level of the repo, so the structure will look like this:
repo/
  _posts/
    some-post.html
  another-file.txt

This is simple enough with git mv, but I want to make the history look as though _posts always existed at the root of the repo, and I want to be able to get the entire history of some-post.html via git log -- _posts/some-post.html. I imagine I can use some magic with git filter-branch to accomplish this, but I haven't figured out exactly how to do that. Any ideas?

[Assistant]
You can use the subdirectory filter to achieve this
 $ git filter-branch --subdirectory-filter blog/ -- --all

EDIT 1: If you don't want to effectively make _posts the root, use a tree-filter instead:
 $ git filter-branch --tree-filter 'mv blog/_posts .' HEAD

EDIT 2: If blog/_posts did not exist in some of the commits, the above will fail. Use this instead:
 $ git filter-branch --tree-filter 'test -d blog/_posts && mv blog/_posts . || echo "Nothing to do"' HEAD


[System] You are a helpful assistant.

[User] git-for-each-ref - Output information on each ref

[Assistant]
EXAMPLES An example directly producing formatted text.  Show the most recent
3 tagged commits: #!/bin/sh

git for-each-ref --count=3 --sort='-*authordate' \
--format='From: %(*authorname) %(*authoremail)
Subject: %(*subject)
Date: %(*authordate)
Ref: %(*refname)

%(*body)
' 'refs/tags' A simple example showing the use of shell eval on the output,
demonstrating the use of --shell.  List the prefixes of all heads: #!/bin/sh

git for-each-ref --shell --format="ref=%(refname)" refs/heads | \
while read entry
do
	eval "$entry"
	echo `dirname $ref`
done A bit more elaborate report on tags, demonstrating that the format
may be an entire script: #!/bin/sh

fmt='
	r=%(refname)
	t=%(*objecttype)
	T=${r#refs/tags/}

	o=%(*objectname)
	n=%(*authorname)
	e=%(*authoremail)
	s=%(*subject)
	d=%(*authordate)
	b=%(*body)

	kind=Tag
	if test "z$t" = z
	then
		# could be a lightweight tag
		t=%(objecttype)
		kind="Lightweight tag"
		o=%(objectname)
		n=%(authorname)
		e=%(authoremail)
		s=%(subject)
		d=%(authordate)
		b=%(body)
	fi
	echo "$kind $T points at a $t object $o"
	if test "z$t" = zcommit
	then
		echo "The commit was authored by $n $e
at $d, and titled

    $s

Its message reads as:
"
		echo "$b" | sed -e "s/^/    /"
		echo
	fi
'

eval=`git for-each-ref --shell --format="$fmt" \
	--sort='*objecttype' \
	--sort=-taggerdate \
	refs/tags`
eval "$eval" An example to show the usage of %(if)…%(then)…%(else)…%(end).
This prefixes the current branch with a star. git for-each-ref --format="%(if)%(HEAD)%(then)* %(else)  %(end)%(refname:short)" refs/heads/ An example to show the usage of %(if)…%(then)…%(end).
This prints the authorname, if present. git for-each-ref --format="%(refname)%(if)%(authorname)%(then) Authored by: %(authorname)%(end)"


[System] You are a helpful assistant.

[User]
View a file in a different Git branch without changing branches
Is it possible to open a file in a git branch without checking out that branch? How?
Essentially I want to be able to open a file in my github pages branch without switching branches all the time. I don't want to modify it, just want to view it.

[Assistant]
This should work:
git show branch:file

Where branch can be any ref (branch, tag, HEAD, ...) and file is the full path of the file. To export it you could use
git show branch:file > exported_file

You should also look at VonC's answers to some related questions:

How to retrieve a single file from specific revision in Git?
How to get just one file from another branch

UPDATE 2015-01-19:
Nowadays you can use relative paths with git show a1b35:./file.txt.


[System] You are a helpful assistant.

[User] git-log - Show commit logs  -t

[Assistant] Show the tree objects in the diff output.


[System] You are a helpful assistant.

[User]
Change SSH host for cloning

Is there any way to change default ssh host for gitlab (displayed at top of repository view in web interface)? I mean only for SSH in clone urls.
For example I have my gitlab installation on git.example.com, but example.com also points to the same machine (different site). Can I change ssh clone urls from:
git clone [email protected]:user/repository

to:
git clone [email protected]:user/repositiory

but for http and https leave it with git.example.com?

[Assistant]
Yes,
If you are using the omnibus package you can edit /etc/gitlab/gitlab.rb and add gitlab_rails['gitlab_ssh_host'] = 'example.host.com'
There is the equivalent option somewhere in gitlab.yml : ssh_host: example.host.com


[System] You are a helpful assistant.

[User]
Error with gradlew: /usr/bin/env: bash: No such file or directory
After committing my project's gradlew file from my Windows machine to the remote repo using Git, invoking gradlew on my Linux server failed with this message:

/usr/bin/env: bash: No such file or directory

What happened?

[Assistant]
The problem's cause was that Git on Windows converted the line endings of gradlew from Unix style (LF) to Windows style (CRLF).
You can turn off that automatic conversion using git config core.autocrlf false.
Setting the line endings of gradlew back to Unix style fixed the problem. In Vim this is done using :set fileformat=unix.


[System] You are a helpful assistant.

[User]
GitHub "fatal: remote origin already exists"
I am trying to follow along Michael Hartl's Rails tutorial but I've run across an error.
I signed up at GitHub, issued a new SSH key, and created a new repository. But when I enter the next line into the terminal, I get the following error:
Parkers-MacBook-Pro:.ssh ppreyer$ git remote add origin [email protected]:ppreyer/first_app.git
fatal: remote origin already exists.

Just wondered if anybody else has run across this problem?

[Assistant]
Short version:
You should just update the existing remote:
git remote set-url origin [email protected]:ppreyer/first_app.git

Long version:
As the error message indicates, there is already a remote configured with the same name. So you can either add the new remote with a different name or update the existing one if you don't need it.
To add a new remote, called for example github instead of origin (which obviously already exists in your system), do the following:
git remote add github [email protected]:ppreyer/first_app.git

Remember though, everywhere in the tutorial you see "origin" you should replace it with "github". For example $ git push origin master should now be $ git push github master.
However, if you want to see what that already existing origin remote is, you can do a $ git remote -v. If you think this is there by some error, you can update it like so:
git remote set-url origin [email protected]:ppreyer/first_app.git


[System] You are a helpful assistant.

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

[Assistant]
Acts like fsck.skipList , but is used by git-receive-pack instead of git-fsck . See the fsck.skipList documentation for
details.


[System] You are a helpful assistant.

[User] git - the stupid content tracker  GIT_DEFAULT_HASH

[Assistant]
If this variable is set, the default hash algorithm for new
repositories will be set to this value. This value is
ignored when cloning and the setting of the remote repository
is always used. The default is "sha1".
See --object-format in git-init .


[System] You are a helpful assistant.

[User]
Import an existing git project into GitLab?

I have an account of a Gitlab installation where I created the repository "ffki-startseite"
Now I want to clone the repository git://freifunk.in-kiel.de/ffki-startseite.git into that repository with all commits and branches, so I can start working on it in my own scope.
How can I import it?

[Assistant]
I was able to fully export my project along with all commits, branches and tags to gitlab via following commands run locally on my computer:

To illustrate my example, I will be using https://github.com/raveren/kint as the source repository that I want to import into gitlab. I created an empty project named Kint (under namespace raveren) in gitlab beforehand and it told me the http git url of the newly created project there is http://gitlab.example.com/raveren/kint.git
The commands are OS agnostic.

In a new directory:
git clone --mirror https://github.com/raveren/kint
cd kint.git
git remote add gitlab http://gitlab.example.com/raveren/kint.git
git push gitlab --mirror

Now if you have a locally cloned repository that you want to keep using with the new remote, just run the following commands* there:
git remote remove origin
git remote add origin http://gitlab.example.com/raveren/kint.git
git fetch --all

*This assumes that you did not rename your remote master from origin, otherwise, change the first two lines to reflect it.


[System] You are a helpful assistant.

[User] git-blame - Show what revision and author last modified each line of a file  -w

[Assistant]
Ignore whitespace when comparing the parent’s version and
the child’s to find where the lines came from.


[System] You are a helpful assistant.

[User] git - the stupid content tracker  git-merge-index

[Assistant] Run a merge for files needing merging


[System] You are a helpful assistant.

[User]
Move .git repo to parent directory [duplicate]

This question already has answers here:

My Git repository is in the wrong root directory. Can I move it? (../ instead of ./)

                                (10 answers)

Closed 7 years ago.

I have a subdirectory named "www" that is a repo:
site
|-- www/
|    |-- .git/
|    |-- index.html
|-- design/
|    |-- images.jpg

I'd like to change the repo to the parent directory so that the repo structure mirrors the original file structure as follows:
site
|-- .git/
|-- www/
|    |-- index.html
|-- design/
|    |-- images.jpg

Can this be done? Are there implications with then pushing the changes up to Gitlab?

[Assistant]
Create a www directory in your repo.
git mv the HTML files to that directory. Optionally commit this step.
mv the design directory into your repo, and git add .
Commit.
Rename/move your whole repo.


[System] You are a helpful assistant.

[User]
AWS Cloudfront error? invalidation max times while deploying?

I got the error while I'm deploying something from gitlab.
$ aws cloudfront create-invalidation --distribution-id=EVB1B2B3B4B56 --paths "/*"
**An error occurred (ServiceUnavailable) when calling the CreateInvalidation operation (reached max retries: 2): CloudFront encountered an internal error. Please try again.**

I sort it out by creating invalidation manually from AWS console and it works . This is the case happens sometimes causes this error, at that time I'm doing manually . What was the permanent solution ? Please help me to sort it out this.

[Assistant]
I experienced a similar issue when creating multiple invalidations while deploying the same application to many distributions. The error still happens randomly, sometimes just retrying the deployment later works fine, and others fail on a different distribution.
I found a related issue showing the same error in the github aws-cdk repo, there seems to be an error with the AWS Cloudfront API during peak hours.

From the CloudFront team:
CreateInvalidation API suffers from high fault rate during the daily
traffic peaks. It will return faults upto 50% of the requests. It is
primarily due to the limited capacity of the API.
We have evidence that some requests failed even after six retries ,
during the peak. We are working on improving this , but there is no
quick fix for this and we are expecting it will get better by the end
of Q1 2022.

I still didn´t find a "clean" solution to this, what I have done is handle the error within my CLI script and automatically retry until it eventually succeeds.


[System] You are a helpful assistant.

[User] git-fsck - Verifies the connectivity and validity of the objects in the database  hasDotgit

[Assistant] (WARN) A tree contains an entry named .git .


[System] You are a helpful assistant.

[User]
Git interoperability with a Mercurial Repository
I use GIT on a Mac. Enough said. I have the tools, I have the experience. And I want to continue to use it. No wars here...
The problem is always with interoperability. Most people use SVN, which is great for me. Git SVN works out of the box, and is a no frills solution. People can continue happily use SVN and I don't lose my workflow and neither my tools.
Now... Some guys come along with Mercurial. Fine for them: they have their reasons. But I can't find any GIT HG out-of-the-box. I don't want to switch to HG, but I still need to interoperate with their repository.
Any of you guys know a simple solution for this?

[Assistant]
There's a new git-remote-hg tool that provides native support:
Bridge support in Git for Mercurial and Bazaar.
Just copy git-remote-hg to your $PATH, make it executable, and that's it, no dependencies (other than Mercurial):
git clone hg::https://www.mercurial-scm.org/repo/hg/

You should be able to push and pull from it as if it was a native Git repository.
When you push new Git branches, Mercurial bookmarks will be created for them.
See the git-remote-hg wiki for more information.


[System] You are a helpful assistant.

[User]
Issue pushing new code in Github
I created a new repository on Github which has only Readme.md file now.
I have a newly created RoR project which I wanted to push to this repository.
Following are the commands I gave in my Terminal to execute this along with the error I am getting.
git remote add origin https://github.com/aniruddhabarapatre/learn-rails.git

After which I entered my username and password
git push -u origin master

Error ---
To https://github.com/aniruddhabarapatre/learn-rails.git
 ! [rejected]        master -> master (fetch first)
error: failed to push some refs to 'https://github.com/aniruddhabarapatre/learn-rails.git'
hint: Updates were rejected because the remote contains work that you do
hint: not have locally. This is usually caused by another repository pushing
hint: to the same ref. You may want to first merge the remote changes (e.g.,
hint: 'git pull') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.

This is my first time pushing my code to a Github repository and I'm lost with the errors. I searched few other questions that are asked here, but none of them had issues first time.

[Assistant]
If this is your first push, then you might not care about the history on the remote. You could then do a "force push" to skip checks that git does to prevent you from overwriting any existing, or differing, work on remote. Use with extreme care!
just change the
git push **-u** origin master

change it like this!
git push -f origin master


[System] You are a helpful assistant.

[User]
GitHub fork a repo from previous commit

I've found a repository on GitHub I would like to fork - but not the current version.
I want to fork the repo as it was quite a few commits back - is this possible? The repo has not marked any releases, so I'm not sure how to do this. I could obviously copy the code as it was in that commit, but I would prefer to fork, as then I get the link back to the original repo.

[Assistant]
You can only fork the current repository.
You can reset the forked repository's master branch to an earlier commit though, making it look like as if you had forked it at that point.
See: How can I rollback a github repository to a specific commit?
If you reset every branch, it effectively resets your repository to an earlier state of the original repository (with exception of branch-independent data, like configuration, hooks etc which are not reset). Since it's possible that not all branches contain the commit from the master branch, you might need to look up commits by date for each branch, to reset them to the last commit before the commit from which you want to fork.


[System] You are a helpful assistant.

[User]
git status - list last modified date
Using git, is it possible to list an unstaged file's last modified date alongside it's path? using eg.
git status
or
git diff --name-only

[Assistant]
Not directly but you can use a pipe:

Note: original answer updated based on comments

Linux:
git status -s | while read mode file; do echo $mode $file $(stat -c %y $file); done

Windows:
git status -s | while read mode file; do echo $mode $(date --reference=$file +"%Y-%m-%d %H:%M:%S") $file; done

OSX (source):
git status -s | while read mode file; do echo $mode $(stat -f "%Sm" $file) $file; done|sort


[System] You are a helpful assistant.

[User]
Who is "us" and who is "them" according to Git?
After a Git rebase, and in other circumstances, you can find some files marked as deleted by us in the git status report. Who is us according to Git and why?
Is it referring to me sitting on this branch and it working for me? Or is it referring to itself and the folks working on the branch I am rebasing against?

[Assistant]
When you merge, us refers to the branch you're merging into, as opposed to them, the branch to be merged.
When you rebase, us refers the upstream branch, and them is the branch you're moving about. It's a bit counter-intuitive in case of a rebase.
The reason is that Git uses the same merge-engine for rebase, and it's actually cherry-picking your stuff into the upstream branch. us = into, them = from.


[System] You are a helpful assistant.

[User] git-diff - Show changes between commits, commit and working tree, etc  --dirstat-by-file[=<param1,param2>…]

[Assistant] Synonym for --dirstat=files,<param1>,<param2>…


[System] You are a helpful assistant.

[User]
How do I undo the most recent local commits in Git?
I accidentally committed the wrong files to Git, but didn't push the commit to the server yet.
How do I undo those commits from the local repository?

[Assistant]
Undo a commit & redo
$ git commit -m "Something terribly misguided" # (0: Your Accident)
$ git reset HEAD~                              # (1)
[ edit files as necessary ]                    # (2)
$ git add .                                    # (3)
$ git commit -c ORIG_HEAD                      # (4)

git reset is the command responsible for the undo. It will undo your last commit while leaving your working tree (the state of your files on disk) untouched. You'll need to add them again before you can commit them again.
Make corrections to working tree files.
git add anything that you want to include in your new commit.
Commit the changes, reusing the old commit message. reset copied the old head to .git/ORIG_HEAD; commit with -c ORIG_HEAD will open an editor, which initially contains the log message from the old commit and allows you to edit it. If you do not need to edit the message, you could use the -C option.

Alternatively, to edit the previous commit (or just its commit message), commit --amend will add changes within the current index to the previous commit.
To remove (not revert) a commit that has been pushed to the server, rewriting history with git push origin main --force[-with-lease] is necessary. It's almost always a bad idea to use --force; prefer --force-with-lease instead, and as noted in the git manual:

You should understand the implications of rewriting history if you amend a commit that has already been published.

Further Reading
You can use git reflog to determine the SHA-1 for the commit to which you wish to revert. Once you have this value, use the sequence of commands as explained above.

HEAD~ is the same as HEAD~1. The article What is the HEAD in git? is helpful if you want to uncommit multiple commits.


[System] You are a helpful assistant.

[User] git-show - Show various types of objects  -a  --text

[Assistant] Treat all files as text.


[System] You are a helpful assistant.

[User]
How to move the current working branch to master branch in git
I have currently one of the project it contain more branches. master branch not yet merger long time. So i want switched to master with latest code.
Can you please give me necessary commands and steps.
Let me re-frame my question.
I am working in a project with different branches. The latest changes were in some branch other than master. Now my requirement is: is there a way to move the current working branch to master without merging it with master, to avoid conflicts?

[Assistant]
If you want to have in master exactly the same files state as in other_branch and save history - do the following (and note the period at the end):
git checkout master
git checkout other_branch .

Now you will have a full copy of other_branch in current master (it is softer than reset), not yet committed. Then make a regular commit:
git add --all
git commit -m "* copy other_branch to master working tree"

Note: untracked (unindexed) files (directories) from other_branch will remain, if they are not tracked by master. To remove those untracked files (directories):
git clean -fd

See How to remove local (untracked) files from the current Git working tree? for more details.


[System] You are a helpful assistant.

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

[Assistant]
A human-readable explanation. In the case of successfully fetched
refs, no explanation is needed. For a failed ref, the reason for
failure is described.


[System] You are a helpful assistant.

[User]
GitLab CI: Export variable in before_script build job

I try to implement a conditional versioning depending on if the CI script runs for a tagged branch or not.
However the version var is not resolved. Instead it is printed as a string.
The relevant jobs of the GitLab CI script:
# build template
.build_base_template: &build_base_template
  image: registry.gitlab.com/xxxxxxx/npm:latest
  tags:
    - docker
  stage: LintBuildTest
  script:
    - export CUR_VERSION='$(cat ./version.txt)$BUILD_VERSION_SUFFIX'
    - npm ci
    - npm run build
  artifacts:
    expire_in: 1 week
    paths:
      - dist/

# default build job
build:
  before_script:
    - export BUILD_VERSION_SUFFIX='-$CI_COMMIT_REF_SLUG-SNAPSHOT-$CI_COMMIT_SHORT_SHA'
  <<: *build_base_template
  except:
    refs:
      - tags
  only:
    variables:
      - $FEATURE_NAME == null

# specific build job for tagged versions
build_tag:
  before_script:
    - export BUILD_VERSION_SUFFIX=''
  <<: *build_base_template
  only:
    refs:
      - tags

[Assistant]
Variables which are exported within before_script are visible within script.
before:
  before_script:
    - export HELLOWELT="hi martin"
  script:
    - echo $HELLOWELT  # prints "hi martin"


[System] You are a helpful assistant.

[User]
Github: How to embed a gist into README.md?

Is it possible to embed gists into README.md file that resides in a GitHub repository?
Something like:

[Assistant]
Update : My answer works with github pages, built via jekyll. I use the script tags in markdown which is then processed by jekyll.
Since markdown supports html, one can simply use the <script> tag to embed gist.
Simply copy the embed url of the gist provided by github

..and paste it in you markdown file.
Example : Copy the below and paste in your markdown file.
<script src="https://gist.github.com/nisrulz/11c0d63428b108f10c83.js"></script>
..and this is what you will get


[System] You are a helpful assistant.

[User] git - the stupid content tracker  gitprotocol-pack

[Assistant] How packs are transferred over-the-wire


[System] You are a helpful assistant.

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

[Assistant]
Set this option to false to disable the default heuristics
that shift diff hunk boundaries to make patches easier to read.


[System] You are a helpful assistant.

[User]
List Git commits not pushed to the origin yet [duplicate]
This question already has answers here:

Closed 11 years ago.

Possible Duplicate:
Viewing Unpushed Git Commits

How do I list all commits which have not been pushed to the origin yet?
Alternatively, how to determine if a commit with particular hash have been pushed to the origin already?

[Assistant]
git log origin/master..master
or, more generally:
git log <since>..<until>
You can use this with grep to check for a specific, known commit:
git log <since>..<until> | grep <commit-hash>
Or you can also use git-rev-list to search for a specific commit:
git rev-list origin/master | grep <commit-hash>


[System] You are a helpful assistant.

[User]
How to rename a directory/folder on GitHub website?
I was able to find a way on GitHub Website to rename a single file and did so with success.
I was also able to find a way to rename a whole repository and did that with success.
Does anyone know how to do this to a single directory without using command line? For reference, I am trying to change a directory named InterviewTesting (that contains source files, etc) to something else. I tried doing it the single file way.  But this didn't allow me to change the name of the directory (InterviewTesting), only the actual file name.

[Assistant]
Actually, there is a way to rename a folder using web interface.

See https://github.com/blog/1436-moving-and-renaming-files-on-github


[System] You are a helpful assistant.

[User] git-config - Get and set repository or global options  core.packedGitWindowSize

[Assistant]
Number of bytes of a pack file to map into memory in a
single mapping operation.  Larger window sizes may allow
your system to process a smaller number of large pack files
more quickly.  Smaller window sizes will negatively affect
performance due to increased calls to the operating system’s
memory manager, but may improve performance when accessing
a large number of large pack files. Default is 1 MiB if NO_MMAP was set at compile time, otherwise 32
MiB on 32 bit platforms and 1 GiB on 64 bit platforms.  This should
be reasonable for all users/operating systems.  You probably do
not need to adjust this value. Common unit suffixes of k , m , or g are supported.


[System] You are a helpful assistant.

[User]
Warning: Multiple merge bases detected. The list of commits displayed might be incomplete
In Azure Repos, I have created a PR from branch A to branch B. There aren't any merge conflict displayed. But I end up with the warning message

Warning: Multiple merge bases detected. The list of commits displayed might be incomplete.

What does this mean?

[Assistant] I got the same message today. I just pulled the latest changes from the destination branch and merged them in the source branch and the issue was resolved.


[System] You are a helpful assistant.

[User]
Is it better to keep Git repository inside or outside of Eclipse workspace?
I am a typical Eclipse/Subversion user beginning the migration to Git. I've researched the basic concepts of git and have decided to stick to a one project per repository approach initially to keep things simple. I am still having trouble, though, deciding where to place the repository for each project.
I have spent a lot of time reviewing the answers to this question, although I believe the author of that question was assuming that you can only use Eclipse to manage the repository if the repository is located within the Eclipse workspace, which is, of course, not true.
The thing that struck me most about that question, though, was the fact that all but one answer (including the accepted answer) suggested keeping the repository inside the Eclipse workspace, whereas only one answer pointed out that the EGit User Guide recommends the exact opposite.
It would appear in practice, however, that there are a number of approaches implemented by Eclipse/EGit, some of which seem to contradict the EGit recommendations.
For example, if you use the New Project Wizard to create a New PHP Project from Git and the repository is remote, Eclipse/EGit will happily create a project folder in the Eclipse workspace and put the repository (.git) in the project folder. This is the end result that I actually want, as it keeps everything encapsulated within the Eclipse workspace.
However, if you use the New Project Wizard and select a Git repository that is local, Eclipse/EGit doesn't clone the repository like it does for remote repositories. Instead it uses the working copy of that repository as the project location, creates its .project and other meta stuff in that location and also creates a new (seemingly unnecessary) folder within that working copy with the same name as your project (so you end up with, for example,  ~/git/blah/blah). If you delete that superfluous folder you end up with a structure that is identical to the first example, the only difference being that the project folder is not a sub-folder of your Eclipse workspace folder, it is somewhere else on your file system (eg. ~/git/blah). The only positive thing this approach seems to have going for it is that it adheres to the recommendations in the EGit User Guide, but from a technical perspective, its hard to see how this is really all that different to the first example.
Given these puzzling observations, I'm wondering what sort of experiences people have had using each of these approaches and what the pitfalls might be if one ignores the recommendations in the EGit User Guide.

[Assistant]
The implications of both solutions are listed directly in the user guide that you linked. I can tell you that the part

This can result in performance issues

is unfortunately very true. So if you have a git directory with a huge number of files inside your workspace, many git operations will start with a "counting objects..." dialog that blocks your IDE because it scans all files in the workspace. For my current 20000 files this means waiting 10 to 20 seconds for every commit, every switch, ...
In spare time activities, where I can fortunately use the other alternative (having the git working directory outside the workspace) everything feels much snappier and it is fun to merge and switch.
So if you go for large projects, consider the git directory outside the workspace as first choice.


[System] You are a helpful assistant.

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

[Assistant] author date, ISO 8601-like format


[System] You are a helpful assistant.

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

[Assistant]
$ git diff --find-copies-harder -B -C (1) $ git diff -R (2) Spend extra cycles to find renames, copies and complete
rewrites (very expensive). Output diff in reverse.


[System] You are a helpful assistant.

[User] git-log - Show commit logs  files

[Assistant]
Compute the dirstat numbers by counting the number of files changed.
Each changed file counts equally in the dirstat analysis. This is
the computationally cheapest --dirstat behavior, since it does
not have to look at the file contents at all.


[System] You are a helpful assistant.

[User] git-log - Show commit logs  --no-indent-heuristic

[Assistant] Disable the indent heuristic.


[System] You are a helpful assistant.

[User] gitworkflows - An overview of recommended workflows with Git

[Assistant] NAME gitworkflows - An overview of recommended workflows with Git


[System] You are a helpful assistant.

[User]
How to cherry-pick only changes to certain files?
If I want to merge into a Git branch the changes made only to some of the files changed in a particular commit which includes changes to multiple files, how can this be achieved?
Suppose the Git commit called stuff has changes to files A, B, C, and D but I want to merge only stuff's changes to files A and B. It sounds like a job for git cherry-pick but cherry-pick only knows how to merge entire commits, not a subset of the files.

[Assistant]
I'd do it with cherry-pick -n (--no-commit) which lets you inspect (and modify) the result before committing:
git cherry-pick -n <commit>

# unstage modifications you don't want to keep, and remove the
# modifications from the work tree as well.
# this does work recursively!
git checkout HEAD <path>

# commit; the message will have been stored for you by cherry-pick
git commit

If the vast majority of modifications are things you don't want, instead of checking out individual paths (the middle step), you could reset everything back, then add in what you want:
# unstage everything
git reset HEAD

# stage the modifications you do want
git add <path>

# make the work tree match the index
# (do this from the top level of the repo)
git checkout .


[System] You are a helpful assistant.

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

[Assistant]
Compute the dirstat numbers by counting the number of files changed.
Each changed file counts equally in the dirstat analysis. This is
the computationally cheapest --dirstat behavior, since it does
not have to look at the file contents at all.


[System] You are a helpful assistant.

[User] git-write-tree - Create a tree object from the current index  --missing-ok

[Assistant]
Normally git write-tree ensures that the objects referenced by the
directory exist in the object database.  This option disables this
check.


[System] You are a helpful assistant.

[User]
Excluding files from git-diff
I am tracking a project with git. There are some Xcode project files in the working copy that I want to keep tracking, but do not want to see in diffs, because there are always dozens of changed lines that I am never interested in. Is there a simple way to have git-diff skip these files? I’ve tried to set up a custom “silent” diff tool:

$ cat .gitattributes
Project.xcodeproj/* diff=nodiff

$ cat ~/.gitconfig
[diff "nodiff"]
    command = /bin/true

But:

$ git diff
external diff died, stopping at Project.xcodeproj/zoul.mode1v3.

What am I doing wrong?

[Assistant]
The problem is that /bin/true will return immediately without reading its input. git diff therefore thinks, quite reasonably, that it has died prematurely.
You really want to unset the diff attribute, not set it to a bogus command. Try this in your .gitattributes:
Project.xcodeproj/* -diff


[System] You are a helpful assistant.

[User]
Git reset --hard and push to remote repository
I had a repository that had some bad commits on it (D, E and F for this example).

A-B-C-D-E-F master and origin/master

I've modified the local repository specifically with a git reset --hard.  I took a branch before the reset so now I have a repo that looks like:
A-B-C master
     \ D-E-F old_master

A-B-C-D-E-F origin/master

Now I needed some parts of those bad commits so I cherry picked the bits I needed and made some new commits so now I have the following locally:
A-B-C-G-H master
     \ D-E-F old_master

Now I want to push this state of affairs to the remote repo. However, when I try to do a git push Git politely gives me the brush off:
$ git push origin +master:master --force
Total 0 (delta 0), reused 0 (delta 0)
error: denying non-fast forward refs/heads/master (you should pull first)
To [email protected]:myrepo.git
! [remote rejected] master -> master (non-fast forward)
error: failed to push some refs to '[email protected]:myrepo.git'

How do I get the remote repo to take the current state of the local repo?

[Assistant]
If forcing a push doesn't help (git push --force origin or git push --force origin master should be enough), it might mean that the remote server is refusing non fast-forward pushes, via either  receive.denyNonFastForwards config variable (see git config manpage for description), or via an update/pre-receive hook.
With older Git you can work around that restriction by deleting git push origin :master (note the : before branch name) and then re-creating git push origin master given branch.
If you can't change this, then the only solution would be instead of rewriting history to create a commit reverting changes in D-E-F:
A-B-C-D-E-F-[(D-E-F)^-1]   master

A-B-C-D-E-F                origin/master


[System] You are a helpful assistant.

[User]
How can I check out a particular version of one file in Git?
How can I check out a particular version of one file in git?
I found this mail on the mailing list, which said:
$ git checkout HEAD~43 Makefile
$ git reset Makefile

But I don't understand how to find out 'HEAD~43', if I do a git log aFile, how can I find out which 'HEAD~43' I should use?
And why do I need to run git reset for that file? What does it do?

[Assistant]
You know what commit (ie: the specific revision) the file belongs to? Then do:
git checkout <commit> <file>

The other command:
git checkout HEAD~N <file>

Is for when you want to get a version of the file from a range back (which I do for nostalgia).


[System] You are a helpful assistant.

[User]
Which files in .idea folder should be tracked by Git?
Unlike Netbeans, in Jetbrains IDEs, the setting files related to user and team are mixed in the same folder that makes it tricky when you need to push them to git.
There is a number of sample git ignore files for these IDEs and https://intellij-support.jetbrains.com/hc/articles/206544839 page on git site.
However, after using them for a months we figure out that it is safer and actually more convenient to do the reverse. I mean ignoring all .idea files and adding only team-related settings explicitly. (instead of adding all and ignoring some).
The main thing that can be shared among developers is code style configs. So, by using IDE auto-reformatting option all the team will follow a consistent style.
Besides that, the question is which other files are recommended to be included and not ignored? Why?
Answer: I came across with this: https://github.com/salarmehr/idea-gitignore

[Assistant]
Jetbrains has some official guidance on which files should not be checked in, and which files should probably not be checked in, depending on your usage. According to that page, you should check in all files in the .idea directory except:

workspace.xml
tasks.xml

And probably also:

the xml files in the dictionary subdirectory

While the particular answer may depend on your team's particular practices, in my experience, following that guidance generally results in correct separation of user settings and shared project configuration.
Some examples of files that should be shared, according to this guidance:

ant.xml, which, if you use Ant to build your project, points IDEA to your build files and configures properties that should be used to build.
vcs.xml, which specifies the Version Control configuration for your project
encodings.xml, which specifies how IDEA should treat the text files in your project
modules.xml, which points IDEA to each of your project's module configuration files, which should also be shared in your VCS.
all files under the runConfigurations subdirectory, which tells IDEA what it needs to do to run your application
codeStyleSettings.xml, which, as you have alluded to, puts your whole team on the same page in terms of automatic code formatting

Depending on your team's usage, there may be more or less, but those are some of the biggest examples.


[System] You are a helpful assistant.

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

[Assistant]
Output a condensed summary of extended header information
such as creations, renames and mode changes.


[System] You are a helpful assistant.

[User]
Switch on another branch (create if not exists), without checking if already exists?
git checkout -b foo switches on foo branch (even if it doesn't exist, it is created), but if the foo branch already exists it throws an error like this:
fatal: A branch named 'foo' already exists.

What's the command that does the following check?

if the branch already exists, just switch on it (git checkout foo)
if the branch doesn't exist, create it and switch on it (git checkout -b foo)

[Assistant]
Update Q3 2019 (Git 2.23): there now actually is a git switch command!
git switch -c aBranch

Or, if the branch already exists:
git switch aBranch

As I explained in 2020, the git switch command is "experimental" in name only, and is here to stay.
You would need an alias though, which tries first to switch to the existing branch and, if it fails (because the branch might actually not exist), creates it:
switchoc = "!f() { git switch $1 2>/dev/null || git switch -c $1; }; f"

Note the name of the alias: switchoc (for "switch or create").
That combination git switch+git switch -c does precisely what the OP is asking for.
As jar pointed out in the comments:

Anyone trying this in 2021, note that you cannot shadow existing git commands with aliases.
Since git switch is a git command, this alias (named "switch") won't work. You must create your unique name for the alias, like "switchit" or something.

bgusach's alias mentioned below in the comment is safer (based on Jiří Pavelka 's answer):
switch = "!f() { git checkout $1 2>/dev/null || git checkout -b $1; }; f"

git switch abranch

Original answer (2014) You can try:
git checkout -B foo

From git checkout man page:

If -B is given, <new_branch> is created if it doesn’t exist; otherwise, it is reset. This is the transactional equivalent of

$ git branch -f <branch> [<start point>]
$ git checkout <branch>

As mentioned below, use it with caution as it does reset the branch, which is not always desirable.
If you did reset the branch by mistake with this command, you can easily revert to its previous state with:
git reset HEAD@{1}

Tal Jacob - Sir Jacques proposes in the comments:

Configure git alias with:
git config alias.switchoc '!f() { git switch $1 2>/dev/null || git switch -c $1; }; f'

Then use with:
git switchoc <branch>


[System] You are a helpful assistant.

[User]
Git squash all commits in branch without conflicting
A common development workflow for us is to checkout branch b, commit a bunch to it, then squash all those commits into one (still on b).
However, during the rebase -i process to squash all the commits, there are frequently conflicts at multiple steps.
I essentially want to alter the branch into one commit that represents the state of the repository at the time of the final commit on b
I've done some searching but I haven't found exactly what I'm looking for. I don't want to merge --squash because we would like to test the squashed feature branch before merging.

[Assistant]
If you don't need the commit information, then you could just do a soft reset. Then files remain as they were and when you commit, this commit will be on top of the commit you did reset to.
To find the commit to reset to:
git merge-base HEAD BRANCH_YOU_BRANCHED_FROM

Then
git reset --soft COMMIT_HASH

Then re-craft the commit, perhaps:
git commit -am 'This is the new re-created one commit'


[System] You are a helpful assistant.

[User] git-notes - Add or inspect object notes  -m <msg>  --message=<msg>

[Assistant]
Use the given note message (instead of prompting).
If multiple -m options are given, their values
are concatenated as separate paragraphs.
Lines starting with # and empty lines other than a
single line between paragraphs will be stripped out.
If you wish to keep them verbatim, use --no-stripspace .


[System] You are a helpful assistant.

[User] git-log - Show commit logs  plain

[Assistant]
Show words as [-removed-] and {+added+} .  Makes no
attempts to escape the delimiters if they appear in the input,
so the output may be ambiguous.


[System] You are a helpful assistant.

[User]
git: rename local branch failed
I don't know why my attempt of renaming local branch failed. I basically cloned the project, then I also have a submodule within the project, and I downloaded the submodule code as well. However, when I use git branch within the submodule, I have:
* (no branch)
  master

The code looks like I'm on another branch but the output shows that it doesn't have a name. Then I searched online to find how to rename local branch and I got this:
git branch -m <newname>

After I run this command git gave me this error:
error: refname refs/heads/HEAD not found
fatal: Branch rename failed

Anybody know why this happens? Thanks.

[Assistant]
I get into this issue too. The reason is that I didn't have any commit on this git repository.
When I run the command git branch -M main. I get the following error message.
error: refname refs/heads/master not found
fatal: Branch rename failed

After I add my first commit by the following command, all things work.
git add .
git commit -m 'Init'


[System] You are a helpful assistant.

[User]
ArgoCD - what need be done after build a new image

I have deployed the application via ArgoCD successfully, and I can access it via its ingress url
The applicaiton uses the image name with latest tag, such as
image: <private_registry>/app_1_service:latest

I also manage other tags on same of tag latest, such as image:<commit_id> or image:<1.0.xxx>
Now, developers will update the codes, after commit changes, a gitlab pipeline  automatically runs and build a new image and override to tag latest with other tags and push to private docker registry
So what's the next step in ArgoCD?
How argocd know the application is changed, and need be redeployed, and the image:latest need be pull again?

[Assistant]
You can use ArgoCD image-updater
But before using the the image-updater, you need to install and set appropriate permission
helm repo add argo https://argoproj.github.io/argo-helm
helm install argocd-image-updater argo/argocd-image-updater

Once image-updator is up and running, then you need to set a few annotations in the Argocd application, as the update workers on different strategies

semver - Update to the latest version of an image considering semantic versioning constraints
latest - Update to the most recently built image found in a registry
digest - Update to the latest version of a given version (tag), using the tag's SHA digest
name - Sorts tags alphabetically and update to the one with the highest cardinality

latest strategies working awesome with tagging under some regex and digest more suited for testing environment.
update-strategies
You can also pull the private image from gitlab as well.
Here is the working example with helm-release
apiVersion: argoproj.io/v1alpha1
kind: Application
metadata:
  annotations:
    argocd-image-updater.argoproj.io/image-alias.allow-tags: 'regexp:^1.3.0-SNAPSHOT.[0-9]+$'
    argocd-image-updater.argoproj.io/image-alias.force-update: 'true'
    argocd-image-updater.argoproj.io/image-alias.pull-secret: 'pullsecret:develop-namespace/develop-app-gitlab-secrets'
    argocd-image-updater.argoproj.io/image-alias.update-strategy: latest
    argocd-image-updater.argoproj.io/image-list: >-
      image-alias=registry.gitlab.com/myorg/my-test-image
  finalizers:
    - resources-finalizer.argocd.argoproj.io
  labels:
    app.kubernetes.io/instance: develop-platform
  name: develop-app
  namespace: argocd
spec:
  destination:
    namespace: develop-app
    server: 'https://kubernetes.default.svc'
  project: develop-app-west6-b
  source:
    helm:
      releaseName: develop-app
      valueFiles:
        - develop-platform/values.yaml
    path: helm-chart/helm-chart
    repoURL: 'https://gitlab.com/my-org/develop-app.git'
    targetRevision: staging
  syncPolicy:
    automated:
      prune: true
      selfHeal: true

If you need digest or just a latest then remove this
  argocd-image-updater.argoproj.io/image-alias.allow-tags: 'regexp:^1.3.0-SNAPSHOT.[0-9]+$'

this is working base on regex.
so in your case <1.0.xxx>
it can be 'regexp:^1.0.[0-9]+$'
If everything configured properly and image updater working fine then you should be able to see logs image updater logs like this
time="2022-04-27T15:18:36Z" level=info msg="Successfully updated image 'registry.gitlab.com/test-image:0.3.0-SNAPSHOT.115' to 'registry.gitlab.com/test-image:0.3.0-SNAPSHOT.118'


[System] You are a helpful assistant.

[User] git-svn - Bidirectional operation between a Subversion repository and Git  --parents

[Assistant]
Create parent folders. This parameter is equivalent to the parameter
--parents on svn cp commands and is useful for non-standard repository
layouts.


[System] You are a helpful assistant.

[User]
How can I throw away local git commits when getting "Your branch and 'origin/master' have diverged"?
I have the following message in git:
# Your branch and 'origin/master' have diverged,
# and have 3 and 8 different commits each, respectively.
#   (use "git pull" to merge the remote branch into yours)

I would like to throw away the 3 local commits, and pull the 8 remote commits at origin/master.
(Merging is going to be too difficult, I'd rather make the 3 local commits again once master is up to date.)
How can I do this?

[Assistant]
git fetch origin
git reset --hard origin/master

Note that any non-pushed commits or local changes will be lost.


[System] You are a helpful assistant.

[User] git - the stupid content tracker  GIT_ALTERNATE_OBJECT_DIRECTORIES

[Assistant]
Due to the immutable nature of Git objects, old objects can be
archived into shared, read-only directories. This variable
specifies a ":" separated (on Windows ";" separated) list
of Git object directories which can be used to search for Git
objects. New objects will not be written to these directories. Entries that begin with " (double-quote) will be interpreted
as C-style quoted paths, removing leading and trailing
double-quotes and respecting backslash escapes. E.g., the value "path-with-\"-and-:-in-it":vanilla-path has two paths: path-with-"-and-:-in-it and vanilla-path .


[System] You are a helpful assistant.

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

[Assistant] Modify the configured refspec to place all refs into the refs/prefetch/ namespace. See the prefetch task in git-maintenance .


[System] You are a helpful assistant.

[User]
Git "revert" current directory
In Subversion (SVN), it's possible to do svn revert ./* in which the current directory and only the current directory gets reverted.
What is the Git equivalent to svn revert in which only the current directory gets reverted?
I know that there's git reset --hard, but it reverts everything and not just the current directory.
How would I revert just the current directory in Git?

[Assistant]
Like vcsjones says, the solution here is git checkout:
git checkout <refspec> -- path/to/directory  # or path/to/file

where <refspec> can, for instance, be HEAD, that is, the current working commit. Note that this usage of the checkout command will affect the working tree but not the index.
git revert is used to "revert a commit", and by this, it should not be understood that the commit disappears from the tree (it would play havoc with history -- if you want that, look at git rebase -i). A reverted commit consists of applying, in reverse, all changes from the commit given as an argument to the tree and create a new commit with the changes (with a default commit message, which you can modify).


[System] You are a helpful assistant.

[User] git - the stupid content tracker  git-fast-import

[Assistant] Backend for fast Git data importers


[System] You are a helpful assistant.

[User]
Git rename from index.lock to index failed

Using the GitHub Windows client I did a sync to pull remote changes to my local machine, but before finishing the sync, I ran out of disk space and the sync failed.  Now I seem to have a bunch of local changes that are actually changes that were being pulled from origin.  I tried to run git pull but got:
C:\Users\Tom\SourceLog [master +4 ~26 -0 !]> git pull
Updating b3a86e1..5afd74f
error: Your local changes to the following files would be overwritten by merge:
        SourceLog.Interface/IChangedFile.cs
        SourceLog.Interface/ILogEntry.cs
        ...
Please, commit your changes or stash them before you can merge.
error: The following untracked working tree files would be overwritten by merge:
        Lib/MSBuildExtensionPack/4.0.6.0/Ionic.Zip.dll
        Lib/MSBuildExtensionPack/4.0.6.0/MSBuild.ExtensionPack.dll
        ...
Aborting

So now I'm trying to discard the local changes but I'm getting:
C:\Users\Tom\SourceLog [master +4 ~26 -0 !]> git checkout -- .
Rename from '.git/index.lock' to '.git/index' failed. Should I try again? (y/n) y
Rename from '.git/index.lock' to '.git/index' failed. Should I try again? (y/n) n
fatal: unable to write new index file

How can I clean this up?  (I didn't have any local changes before starting the sync.)
Update
Can't seem to reset head..
C:\Users\Tom\SourceLog [master +4 ~0 -0 !]> git reset head
Rename from '.git/index.lock' to '.git/index' failed. Should I try again? (y/n) y
Rename from '.git/index.lock' to '.git/index' failed. Should I try again? (y/n) n
error: Could not write new index file.
fatal: Could not reset index file to revision 'head'.

[Assistant]
In my case, this was caused by using the same Git repo from both admin and non-admin command prompts. When last git pull was from admin cmd, the index was created by it, and then non-admin cmd had insufficient permissions to modify it.
My solution was re-creating the index (while keeping the worktree intact):
del .git\index
del .git\index.lock
git reset --mixed head


[System] You are a helpful assistant.

[User]
How do I properly force a Git push?
I've set up a remote non-bare "main" repo and cloned it to my computer. I made some local changes, updated my local repository, and pushed the changes back to my remote repo. Things were fine up to that point.
Now, I had to change something in the remote repo. Then I changed something in my local repo. I realized that the change to the remote repo was not needed. So I tried to git push from my local repo to my remote repo, but I got an error like:

To prevent you from losing history, non-fast-forward updates were
  rejected Merge the remote changes before pushing again.  See the 'Note
  about fast-forwards' section of git push --help for details.

I thought that probably a
git push --force

would force my local copy to push changes to the remote one and make it the same. It does force the update, but when I go back to the remote repo and make a commit, I notice that the files contain outdated changes (ones that the main remote repo previously had).
As I mentioned in the comments to one of the answers:

[I] tried forcing, but when going back to master server to save the changes, i get outdated staging. Thus, when i commit the repositories are not the same. And when i try to use git push again, i get the same error.

How can I fix this issue?

[Assistant]
Just do:
git push origin <your_branch_name> --force

or if you have a specific repo:
git push https://git.... --force

This will delete your previous commit(s) and push your current one.
It may not be proper, but if anyone stumbles upon this page, thought they might want a simple solution...
Short flag
Also note that -f is short for --force, so
git push origin <your_branch_name> -f

will also work.


[System] You are a helpful assistant.

[User]
Gitlab CI - ERROR: Job failed: executor requires OSType=linux, but Docker Engine supports only OSType=windows

Getting this error while running Gitlab CI pipeline. As I understand the error says that I'm trying to run a Linux type docker image on a windows docker-engine? But the thing is I'm using a windows docker image. What could be the problem?

ERROR: Job failed: executor requires OSType=linux, but Docker Engine supports only OSType=windows

My CI:
image: hello-world:nanoserver

stages:
  - build

build1:
  stage: build
  script:
    - echo "Hello world"

[Assistant]
What's the difference between "Shared" and "Simple" tags?

Some images have separated "Simple Tags" and "Shared Tags" sections
  under "Supported tags and respective Dockerfile links" (see the mongo
  image for an example).
"Simple Tags" are instances of a "single" Linux or Windows image. It
  is often a manifest list that can include the same image built for
  other architectures; for example, mongo:4.0-xenial currently has
  images for amd64 and arm64v8. The Docker daemon is responsible for
  picking the appropriate image for the host architecture.
"Shared Tags" are tags that always point to a manifest list which
  includes some combination of potentially multiple versions of Windows
  and Linux images across all their respective images' architectures --
  in the mongo example, the 4.0 tag is a shared tag consisting of (at
  the time of this writing) all of 4.0-xenial,
  4.0-windowsservercore-ltsc2016, 4.0-windowsservercore-1709, and 4.0-windowsservercore-1803.
The "Simple Tags" enable docker run mongo:4.0-xenial to "do the right
  thing" across architectures on a single platform (Linux in the case of
  mongo:4.0-xenial). The "Shared Tags" enable docker run mongo:4.0 to
  roughly work on both Linux and as many of the various versions of
  Windows that are supported (such as Windows Server Core LTSC 2016,
  where the Docker daemon is again responsible for determining the
  appropriate image based on the host platform and version).

I suggest you to try shared tags:
image: hello-world

the latest  tag has:
linux/386

windows v10.0.17134.1069/amd64

windows v10.0.17763.802/amd64

and Docker will pick up the right one for you
From here you need the executer docker-windows to run Windows Container
so you may add executor = "docker-windows" to your runners config