[System] You are a helpful assistant.

[User]
Merge branches without checking out branch
I have 3 branches.
     master [ Live Server]
      \
       stage [ Stage Server Where we test changes; merge commits ]
        \
         Dev [ Local Machine ]

I would like to downstream the changes to. Each of these branches are set to tracking each other.
Normally, to downstream the changes i do this:
git checkout stage && git merge master
Then i checkout dev and i do the same
git checkout dev && git merge stage
Then push them all:
git push origin --all
Is there a way to downstream those changes without checking out into each branch?
I maybe using the wrong terminology. I'm not totally sure if i'm using upstream/downstream terminology correctly.

[Assistant]
You can indeed "merge" a branch B into branch A without having to check out branch A, but only if it's a fast-forward merge.
You can use a refspec with fetch to do the "merge". If merging branch B into branch A using git merge would result in a fast-forward merge, then you can do the following without having to checkout A:
git fetch <remote> B:A

The Documentation
The above matches the refspec format
git fetch <remote> <source>:<destination>

From the documentation for git fetch (emphasis mine):

The remote ref that matches <src> is fetched, and if <dst> is not empty string, the local ref that matches it is fast-forwarded using <src>.

See Also

Git checkout and merge without touching working tree
Merge, update, and pull Git branches without using checkouts
Merging without changing the working directory
Merging Branches Without Checkout


[System] You are a helpful assistant.

[User]
GIT commit as different user without email / or only email
I'm trying to commit some changes as a different user, but i do not have a valid email address, following command is not working for me:
git commit --author="john doe" -m "some fix"
fatal: No existing author found with 'john doe'

I have the same problem when trying to commit with only an email address
git commit --author="[email protected]" -m "some fix"
fatal: No existing author found with '[email protected]'

On the GIT man pages for the commit command it says i can use the
standard A U Thor <[email protected]> format

For the --author option.
Where is this format defined ?
what does A and U stand for ? how do i commit for a different user with only a username or only an email?

[Assistant]
The minimal required author format, as hinted to in this SO answer, is
Name <email>

In your case, this means you want to write
git commit --author="Name <email>" -m "whatever"

Per Willem D'Haeseleer's comment, if you don't have an email address, you can use <>:
git commit --author="Name <>" -m "whatever"

As written on the git commit man page that you linked to, if you supply anything less than that, it's used as a search token to search through previous commits, looking for other commits by that author.


[System] You are a helpful assistant.

[User]
Remove deleted files from git history
I'm trying to split a subproject off of my git repository.
However unlike in
Detach (move) subdirectory into separate Git repository
I don't have it in it's own subdirectory (and moving it in and doing the above only yields the history after the move).
I've cloned the branch from which I want to split off the subproject into it's own repository and removed everything that isn't used by the subproject, so basically I could use this as the repository of my subproject.
Now I want to get rid of the history of all files that are no longer in this repository so as to only keep the file history for the files that made it into the offspring.
I think it must be possible with git-filter-branch but I can't figure out how
Many thanks in advance

[Assistant]
Here are some instructions to do what you want.
This will remove file_to_remove:
git filter-branch --index-filter 'git rm --cached --ignore-unmatch file_to_remove' --prune-empty -- --all


[System] You are a helpful assistant.

[User] git-config - Get and set repository or global options  submodule.active

[Assistant]
A repeated field which contains a pathspec used to match against a
submodule’s path to determine if the submodule is of interest to git
commands. See gitsubmodules for details.


[System] You are a helpful assistant.

[User] git-config - Get and set repository or global options  safe.directory

[Assistant]
These config entries specify Git-tracked directories that are
considered safe even if they are owned by someone other than the
current user. By default, Git will refuse to even parse a Git
config of a repository owned by someone else, let alone run its
hooks, and this config setting allows users to specify exceptions,
e.g. for intentionally shared repositories (see the --shared option in git-init ). This is a multi-valued setting, i.e. you can add more than one directory
via git config --add . To reset the list of safe directories (e.g. to
override any such directories specified in the system config), add a safe.directory entry with an empty value. This config setting is only respected in protected configuration (see SCOPES ). This prevents untrusted repositories from tampering with this
value. The value of this setting is interpolated, i.e. ~/<path> expands to a
path relative to the home directory and %(prefix)/<path> expands to a
path relative to Git’s (runtime) prefix. To completely opt-out of this security check, set safe.directory to the
string * . This will allow all repositories to be treated as if their
directory was listed in the safe.directory list. If safe.directory=* is set in system config and you want to re-enable this protection, then
initialize your list with an empty value before listing the repositories
that you deem safe. As explained, Git only allows you to access repositories owned by
yourself, i.e. the user who is running Git, by default.  When Git
is running as root in a non Windows platform that provides sudo,
however, git checks the SUDO_UID environment variable that sudo creates
and will allow access to the uid recorded as its value in addition to
the id from root .
This is to make it easy to perform a common sequence during installation
"make && sudo make install".  A git process running under sudo runs as root but the sudo command exports the environment variable to record
which id the original user has.
If that is not what you would prefer and want git to only trust
repositories that are owned by root instead, then you can remove
the SUDO_UID variable from root’s environment before invoking git.


[System] You are a helpful assistant.

[User]
How do I "git blame" a deleted line?
git blame is great for modified and added lines, but how can I find when a line that existed in a specific previous commit was eventually deleted.  I'm thinking bisect, but I was hoping for something handier.
(Before you ask: in this case, I just did a git log -p and searched through for the code line and (a) some idiot had just deleted the vital line in the previous commit and (b) I was that idiot.)

[Assistant]
If you know the contents of the line, this is an ideal use case for:
git log -S <string> path/to/file

which shows you commits which introduce or remove an instance of that string. There's also the -G<regex> which does the same thing with regular expressions! See man git-log and search for the -G and -S options, or pickaxe (the friendly name for these features) for more information.
The -S option is actually mentioned in the header of the git-blame manpage too, in the description section, where it gives an example using git log -S....


[System] You are a helpful assistant.

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

[Assistant]
List only commits on the respective side of a symmetric difference,
i.e. only those which would be marked < resp. > by --left-right . For example, --cherry-pick --right-only A...B omits those
commits from B which are in A or are patch-equivalent to a commit in A . In other words, this lists the + commits from git cherry A B .
More precisely, --cherry-pick --right-only --no-merges gives the exact
list.


[System] You are a helpful assistant.

[User]
Github: how to fork after cloning?

I cloned a git repo to my local machine, played around with it a bit and found it cool.
Now I would like to keep the result as I modified it in my own github space. How can I proceed?
I suppose the regular way would have been to fork the repo on the first place to my space, clone it, modify and then push it to GitHub, but now I cloned the original's author repo, how can I commit that as a new thing in my personnal?

[Assistant]
First rename the old remote as upstream, in case you want to be able to keep in sync with the original repository.
git remote rename origin upstream

Then add your forked repository as origin:
git remote add origin https://github.com/<your-username>/<your-project>

Or if you're using ssh:
git remote add origin [email protected]:<your-username>/<your-project>.git

To push to your repository:
git push -u origin master

To pull from the base repository:
git pull upstream

I recommend you do all of your work in a separate branch, not the master branch. It will be easier to rebase to the upstream/master branch in case you want to make a pull request.
You don't really have to rename the origin to upstream - the remote names can be arbitrary, however I recommended you to do so to keep up with the naming convention used by GitHub.


[System] You are a helpful assistant.

[User] git-switch - Switch branches

[Assistant]
EXAMPLES The following command switches to the "master" branch: $ git switch master After working in the wrong branch, switching to the correct branch
would be done using: $ git switch mytopic However, your "wrong" branch and correct "mytopic" branch may differ
in files that you have modified locally, in which case the above
switch would fail like this: $ git switch mytopic
error: You have local changes to 'frotz'; not switching branches. You can give the -m flag to the command, which would try a three-way
merge: $ git switch -m mytopic
Auto-merging frotz After this three-way merge, the local modifications are not registered in your index file, so git diff would show you what
changes you made since the tip of the new branch. To switch back to the previous branch before we switched to mytopic
(i.e. "master" branch): $ git switch - You can grow a new branch from any commit. For example, switch to
"HEAD~3" and create branch "fixup": $ git switch -c fixup HEAD~3
Switched to a new branch 'fixup' If you want to start a new branch from a remote branch of the same
name: $ git switch new-topic
Branch 'new-topic' set up to track remote branch 'new-topic' from 'origin'
Switched to a new branch 'new-topic' To check out commit HEAD~3 for temporary inspection or experiment
without creating a new branch: $ git switch --detach HEAD~3
HEAD is now at 9fc9555312 Merge branch 'cc/shared-index-permbits' If it turns out whatever you have done is worth keeping, you can
always create a new name for it (without switching away): $ git switch -c good-surprises


[System] You are a helpful assistant.

[User]
Google Code + SVN or GitHub + Git [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 9 years ago.

                        Improve this question

Let me start by telling you that I never used anything besides SVN and I'm also a Windows user.
I have a couple of simple projects that are open-source, others are on their way when I'm happy enough to release their source code. Either way, I was thinking of using Google Code and SVN to share the source code of my projects instead of providing a link to the source on my website. This has always been a pain because I had to update the binaries and the code every time I released a new version. This would also help me to have a backup of my code some where instead of just my local machine (I used to have a local Subversion server running).
What I want from a service like this is very simple... I just want a place to store my source code that people can download if they want, that allows me to control revisions and provide a simple and easy issue/bug system so people can submit bugs and stuff like that. I guess both of them have this.
But I don't want to host any binaries in their websites. I want this to be hosted on my website so I can control download statistics with my own scripts. I also don't have a need for wiki pages as I prefer to have all the documentation on my own website. Do any of these services provide a way to "disable" features like wiki and downloads and not show them at all for my project(s)?
Now, I'm sure there are lots of pros and cons about using Google Code with SVN and GitHub with Git (of course) but here's what's important for me on each one, and why I like them:
Google Code:

As with any Google page, the complexity is almost non-existent
Everyone (or almost everyone) has a Google account, whcih is nice if people want to report problems using the issues system

GitHub:

May (or may not) be a little more complex (not a problem for me though) than Google's pages but...
...has a much prettier interface than Google's service
It needs people to be registered on GitHub to post about issues
I like the fact that with Git, you have your own revisions locally (can I use TortoiseGit for this or?)

Basically that's it. Not much, I know...
What other common pros and cons can you tell me about each site/software? Keep in mind that my projects are simple, I'm probably the only one who will ever develop these projects on these repositories (or maybe not, but for now I am).

[Assistant] Google Code is supporting Mercurial now.  Mercurial should give you most of the benefits of Git, but you get the maturity of Google Code.  You also have the option to go with subversion there as well should you want to.


[System] You are a helpful assistant.

[User]
Git pull / push - unable to access HTTPS, SSL routines seem to be down

I'm using Git (and GitHub) on a daily basis and everything has been working fine and all of a sudden, I can no longer communicate with my remote GitHub repository through my Git commands. When I try to "Git pull", it gives the following error:

fatal: unable to access 'https://github.com/snahrvar/eatibl.git/':
  error:1407742E:SSL routines:SSL23_GET_SERVER_HELLO:tlsv1 alert
  protocol version

So, I tested across multiple repositories, and I get the same errors on my computer. I had someone else interact with those same repositories, and it works fine for them. Prior to this error, I did an "npm install sharp" on a project and that ended up failing, and I suspect this may have messed with some SSL setting, but that's a wild guess!
Any general thoughts or guidance would be much appreciated!
If it's helpful at all, here is my environment:

Git version: 1.9.4.msysgit.2
Windows version: Windows 8.1

[Assistant]
Updating TortoiseGit and GCM didn't help me, but updating Git itself did, as per @Frederic's advice in comments.
https://git-scm.com/download/win
To make sure the new version of Git installs properly and doesn't conflict with previous installations (it might, if you used TortoiseGit's, because it would use different folders and mess with PATH variable), remove the existing Git installation before installing the updated Git. Might also need to install with administrator rights.


[System] You are a helpful assistant.

[User]
How can I give access to a private GitHub repository?

I have a private git repository and I would like to extend its access to a member of my team. Will I be able to do it through the Github website? I have the username of my member.
I have tried to do this by going through the admin page of the repository but there isn't such an option as I am not the owner.

[Assistant]
If you are the owner it is simple:

Go to your repo and click the Settings button.
In the left menu click Collaborators
Then Add their name.

Then collaborator should visit this example repo link https://github.com/user/repo/invitations
Source: Github Docs.


[System] You are a helpful assistant.

[User]
How to specify a certain commit in dependencies in Cargo.toml?

I am trying to configure my Rust project with an external dependency in GitHub. Unfortunately, some last commits made some changes in interfaces so I am unable to use the latest version. The developers also do not care of tags and separate branches for different versions, so I think the only correct way is to specify a certain commit somehow where the interface fits what I worked with.
What I have now in Cargo.toml is:
[dependencies]
...
thelib = { git = 'https://github.com/someguys/thelib' }

I saw it is possible to specify a branch like this:
thelib = { git = 'https://github.com/someguys/thelib', branch = 'branch1' }

But I have not seen a working example with a commit. Could anybody provide one here?

[Assistant]
As hinted in the Cargo.toml vs Cargo.lock section of the Cargo guide, you can use the rev property to specify a commit hash:

[...] If you build this package today, and then you send a copy to me, and I build this package tomorrow, something bad could happen. There could be more commits to rand in the meantime, and my build would include new commits while yours would not. Therefore, we would get different builds. This would be bad because we want reproducible builds.
We could fix this problem by putting a rev line in our Cargo.toml:
[dependencies]
rand = { git = "https://github.com/rust-lang-nursery/rand.git", rev = "9f35b8e" }

It is also mentioned in Specifying dependencies, although no example is given (emphasis mine):

Since we haven’t specified any other information, Cargo assumes that we intend to use the latest commit on the master branch to build our package. You can combine the git key with the rev, tag, or branch keys to specify something else. [...]


[System] You are a helpful assistant.

[User] git-config - Get and set repository or global options  mergetool.<tool>.path

[Assistant]
Override the path for the given tool.  This is useful in case
your tool is not in the PATH.


[System] You are a helpful assistant.

[User]
Can git ignore a specific line?
I'm using git to sync to phonegap while testing on the phone's native browser. As such I have the following line:
var isPhoneGap = false;

Obviously I change this when building, but is there any way I can set up git to ignore this one line or do I have to go and put it in its own file and ignore it that way?
I'm using Gitx and the terminal on OSX 10.6.

[Assistant]
If your file is of a specific type, you can declare a content filter driver, that you can declare in a .gitattributes file (as presented in the "Keyword expansion" of "Git Attributes"):

*.yourType filter=yourFilterName

(you can even set that filter for a specific file, if you want)
Implement:

yourFilterName.smudge (triggered on git checkout) and
  git config --global filter.yourFilterName.smudge 'sed "s/isPhoneGap = .*/isPhoneGap = true/"'

yourFilterName.clean (triggered on git add)
  git config --global filter.yourFilterName.clean 'sed "s/isPhoneGap = .*/isPhoneGap = false/"'

Your file would appear unchanged on git status, yet its checked out version would have the right value for isPhoneGap.

Note: in the comments, ohaal and Roald suggest to isolate the sed calls in a separate helper.sh script:
sed "s/isPhoneGap = .*/isPhoneGap = true/" "$@"


[System] You are a helpful assistant.

[User] git-format-patch - Prepare patches for e-mail submission  --abbrev[=<n>]

[Assistant]
Instead of showing the full 40-byte hexadecimal object
name in diff-raw format output and diff-tree header
lines, show the shortest prefix that is at least <n> hexdigits long that uniquely refers the object.
In diff-patch output format, --full-index takes higher
precedence, i.e. if --full-index is specified, full blob
names will be shown regardless of --abbrev .
Non default number of digits can be specified with --abbrev=<n> .


[System] You are a helpful assistant.

[User] git-grep - Print lines matching a pattern  -q  --quiet

[Assistant]
Do not output matched lines; instead, exit with status 0 when
there is a match and with non-zero status when there isn’t.


[System] You are a helpful assistant.

[User]
Git ignore local changes to portions of tracked files
Specifically, I maintain a git repository of my dotfiles. I recently started working on a new machine and cloned my repository on the same.
Now, I wish to make some changes to my dotfiles which are specific to this system only. These changes I wish to ignore in my repository.
Other changes that I make, should continue to be tracked and committed.
For example, in my .gitconfig, I have a setting as:
[push]
   default = simple

Now, on my new machine, the version of git being used it very old. It still not not support the setting simple for push. So, I'd like to change this, but only locally.
However, if I make any other changes to my .gitconfig, I'd like to keep track of those. Anyway I can achieve this?
EDIT:
I know of git update-index --assume-unchanged. The problem with it is that git will no longer track my file at all, until I reverse it. And then, it will track all changes.
I wish to ignore certain changes and track the rest.

[Assistant]
Try using this command:
git update-index --assume-unchanged FILENAME_TO_IGNORE

To reverse it (if you ever want to commit changes to it), use:
git update-index --no-assume-unchanged

UPDATE:
Here's how to list 'assume unchanged' files under current directory:
git ls-files -v | grep -E "^[a-z]"

As the -v option will use lowercase letters for 'assume unchanged' files.


[System] You are a helpful assistant.

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

[Assistant] (ERROR) Invalid date value in an author/committer line.


[System] You are a helpful assistant.

[User]
How can I publish an npm package with distribution files?
I would like to publish a npm package that contains my source as well as distribution files. My GitHub repository contains src folder which contains JavaScript source files. The build process generates dist folder that contains the distribution files. Of course, the dist folder is not checked into the GitHub repository.
How do I publish a npm package in a way that when someone does npm install, they get src as well as dist folder? Currently when I run npm publish from my Git repository, it results in only the src folder being published.
My package.json file looks like this:
{
  "name": "join-js",
  "version": "0.0.1",
  "homepage": "https://github.com/archfirst/joinjs",
  "repository": {
    "type": "git",
    "url": "https://github.com/archfirst/joinjs.git"
  },
  "main": "dist/index.js",
  "scripts": {
    "test": "gulp",
    "build": "gulp build",
    "prepublish": "npm run build"
  },
  "dependencies": {
    ...
  },
  "devDependencies": {
    ...
  }
}

[Assistant]
When you npm publish, if you don't have an .npmignore file, npm will use your .gitignore file (in your case you excluded the dist folder).
To solve your problem, create a .npmignore file based on your .gitignore file, without ignoring the dist folder.
Source: Keeping files out of your Package


[System] You are a helpful assistant.

[User] gitfaq - Frequently asked questions about using Git  How do I ignore changes to a tracked file?

[Assistant]
Git doesn’t provide a way to do this.  The reason is that if Git needs
to overwrite this file, such as during a checkout, it doesn’t know
whether the changes to the file are precious and should be kept, or
whether they are irrelevant and can safely be destroyed.  Therefore, it
has to take the safe route and always preserve them. It’s tempting to try to use certain features of git update-index , namely the
assume-unchanged and skip-worktree bits, but these don’t work properly for this
purpose and shouldn’t be used this way. If your goal is to modify a configuration file, it can often be helpful to have
a file checked into the repository which is a template or set of defaults which
can then be copied alongside and modified as appropriate.  This second, modified
file is usually ignored to prevent accidentally committing it.


[System] You are a helpful assistant.

[User] git-diff - Show changes between commits, commit and working tree, etc  git diff [<options>] <commit>..<commit> [--] [<path>…]

[Assistant]
This is synonymous to the earlier form (without the .. ) for
viewing the changes between two arbitrary <commit>.  If <commit> on
one side is omitted, it will have the same effect as
using HEAD instead.


[System] You are a helpful assistant.

[User]
How can I make git ignore future revisions to a file?
I have created a default version of a file included in a git repository.  It's important that when someone clones the repository, they get a copy of this file.  However, I would like to set git so that it ignores changes to this file later.  .gitignore works only on untracked files.
My motivation is that this file contains machine-specific information.  I would like to provide default values, while allowing people to make local changes that won't get pushed back to the origin repository, creating merge conflicts when we pull new changes.
We are generally pretty lazy and use git add . a lot, so I'm pretty sure if I can't tell git to ignore this file, changes to it will end up getting committed and pushed.
To summarize,

I would like to create a file, call it default_values.txt that is added to my git repository and is included when someone clones that repository.
git add . should not add default_values.txt to the commit.
This behavior should be passed on to any clones of the repository.

[Assistant]
As many others have mentioned, a good modern solution is:
git update-index --skip-worktree default_values.txt

That will ignore changes to that file, both local and upstream, until you decide to allow them again with:
git update-index --no-skip-worktree default_values.txt

You can get a list of files that are marked skipped with:
git ls-files -v . | grep ^S

Note that unlike --skip-worktree, the --assume-unchanged status will get lost once an upstream change is pulled.


[System] You are a helpful assistant.

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

[Assistant]
Spend extra time to make sure the smallest possible
diff is produced.


[System] You are a helpful assistant.

[User] git-init - Create an empty Git repository or reinitialize an existing one

[Assistant] NAME git-init - Create an empty Git repository or reinitialize an existing one


[System] You are a helpful assistant.

[User]
git push Out of memory, malloc failed
I am trying to push my changes remotely to GitHub, every so often git fails due to
C:\dev\projects>git push -v
Pushing to https://[email protected]/mycompany/My-Project.git
Password for 'github.com':
fatal: Out of memory, malloc failed (tried to allocate 524288000 bytes)
fatal: write error: Invalid argument

This is very, very aggravating.  I have run the following commands, upgraded git (which wiped out my settings and caused lots of pain, but I digress)
git gc --auto --prune=today --aggressive
git repack

I have even bumped the value of
http.postbuffer

but eventually it will fail again.
This is a typical Rails 3.1 application, total project size on disk is 9.69 MB.

[Assistant]
My advice is to try several git parameters related with pack:
[pack]
   threads = 1
   deltaCacheSize = 128m
   windowMemory = 50m

What it got better results for me was setting git config pack.threads 1 and git config pack.windowMemory 50m (default is 10m).
Still, my host didn't have enough RAM memory (2GB) and kept failing. I hard copied the repo and moved it to another machine with more RAM (8GB). It got better but still failed.
Finally, I downloaded the latest version of git (https://github.com/git/git), compile it and install it. That fixed the problem just by running git repack -adf with the same parameters. After that I run git gc --aggressive --prune=now
Once I got the repo fixed in my local machine I pushed it to master, overwriting the remote repo, git push -f origin master.
To prevent similar errors in the future try not to add unnecessary large files to the repo (in my case I got a SQL dump of 3.5GB :)) and disable delta compression for large files (such as images, PDFs, videos). Add the following lines to .gitattributes:
*.pdf -delta
*.jpg -delta


[System] You are a helpful assistant.

[User]
Notorious Git Error: remote rejected (failed to lock)

I am trying to push to a branch from my local to the origin. The branch name and the path is same. I have been pushing and pulling from this branch for a while and never had a problem. But suddenly, it started behaving badly. Last time when I tried to push to origin with following command:
git push origin feature/Prizefulfilment

It gives me following errror:
72c6c1da98e5cff4484e254a538d9e3b472156ff but expected 0000000000000000000000000000000000000000

I have Googled around but did not find a quite satisfying solution to it yet.
My exact error looks like following:
$ git push origin feature/Prizefulfilment
Counting objects: 126, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (75/75), done.
Writing objects: 100% (78/78), 8.83 KiB, done.
Total 78 (delta 61), reused 0 (delta 0)
error: Ref refs/heads/feature/Prizefulfilment is at 72c6c1da98e5cff4484e254a538d9e3b472156ff but expected 0000000000000000000000000000000000000000
remote: error: failed to lock refs/heads/feature/Prizefulfilment
To [email protected]:OpusOneSCRUM
 ! [remote rejected] feature/Prizefulfilment -> feature/Prizefulfilment (failed to lock)
error: failed to push some refs to '[email protected]:OpusOneSCRUM'`

Any ideas?

[Assistant]
git push feature/prizeFulfilment: feature/Prizefulfilment

That is similar to this answer:

For the record, I believe the root cause of this problem was the difference in capitalisation between the local and remote branch names, and the case-insensitive nature of the Windows share that hosted the remote repository.
We just encountered this exact same error and were able to resolve the problem simply by renaming the local branch to match the capitalisation of the existing remote branch.

Try and make sure to use the same capitalization between local and remote branches.
You second command make the link between the prizeFulfilment and remote Prizefulfilment explicit, which is why it worked. But it isn't a good solution to keep a local branch with that kind of difference.


[System] You are a helpful assistant.

[User]
Getting a working copy of a bare repository
I have a server on which I have a bare repository for pushing. However, my server needs to have a working copy of the master branch.
How do I get a working copy and that only from a bare repository?

[Assistant]
You can simply clone the repository to another directory on the same machine:
git clone /bare/repo/dir

The current directory will become a non-bare clone of your repo, and you'll get a checkout of the master branch automatically. Then use the usual commands like git pull to update it as needed.
As a side benefit, this operation is very efficient — if you specify a local directory to git clone, git will use hard links to share the read-only parts of the object databases of the two repos.


[System] You are a helpful assistant.

[User]
Squash in SourceTree
Is it possible to squash in SourceTree?  I saw that apparently you can "drag and drop" commits in order to squash them.  However, when I do that it only highlights several commits.

[Assistant]
Updated Answer
SourceTree for Windows
As of version 1.5, you can now do interactive rebases, which will allow you to squash.
SourceTree for Mac
Interactive rebase has been available in SourceTree for Mac since version 1.6 (emphasis mine):

The git rebase –interactive command allows you to reorganise your commits after you’ve created them (but before you’ve made them public), and now you can do this inside SourceTree. Combine (squash) multiple commits together, or re-order them, simply by dragging & dropping. You can also change the commit message, or edit the content of the commits. Just right-click on a commit in the log and choose ‘Rebase children of <sha> interactively’ to kick the process off.

Old Answer
Apparently squashing commits is a feature in SourceTree version 1.6 for the Mac.
However, the feature doesn't seem to be available in the Windows version of SourceTree, which is currently still at version 1.0.8.
Using the command line
You still have the option of using the command line to squash commits:
git rebase -i <sha-of-base-commit>

In the TODO list, put an s (for squash) next to commits to squash into the previous commit:
pick e953225 Add meow meow meow
s def892d Add master

To learn more about how to squash commits using the command line, see Squashing Commits, from the FREE online Pro Git book.


[System] You are a helpful assistant.

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

[Assistant]
The default mode for format-patch to determine which parts of
the cover letter will be populated using the branch’s
description. See the --cover-from-description option in git-format-patch .


[System] You are a helpful assistant.

[User]
git ignore vs. exclude vs. assume-unchanged
I've read the docs on this several times over and I still don't completely get the differences between these different commands. Maybe it's just me, but the documentation could be more lucid:
http://git-scm.com/docs/gitignore
https://help.github.com/articles/ignoring-files
Moreover, a lot of the commentary on this subject seems to use the words "indexed", "committed", "tracked" somewhat loosely, which makes the differences between these three less clear.
My current (admittedly limited) understanding:

Files matched in .gitignore will not be tracked in the future.
(Though they may have been tracked previously.) This means that they
won't ever show up in a future git status list as changed.
However, future changes will still be synced with remote repos. In other words, the files are still "indexed", but they are not "tracked".
Because a .gitignore file is in the project directory, the file
itself can be versioned.

Files matched in .git/info/exclude will also not be "tracked". In
addition, these files will not ever be remotely synced, and thus will
never be seen in any form by any other users. These files should be files that
are specific to a single user's editor or workflow. Because it is in the .git
directory, the exclude file can't itself be versioned.

Files that have had assume-unchanged run on them also don't show up in git status or git diff. This seems similar to exclude, in that these files are neither "indexed" nor "tracked". However, the last version of the file to be committed before assume-unchanged will remain visible to all users in the repo.

My questions:

Is the above interpretation correct? Please correct me.

If a file has already been in a commit, what is the functional
different between matching it in .exclude and running
assume-unchanged on it? Why would one prefer one approach to
another?

My basic use case is that I want to avoid sorting through diffs on
compiled files, but I still want those compiled files synced along
with the source files. Will a gitignore'd file still be pushed? If not, how to manage final deployment of the compiled files?

[Assistant]
I'm going to accept this emailed answer from Junio Hamano (the maintainer of Git) because I think it explains some things more lucidly than the official docs, and it can be taken as "official" advice:

The .gitignore and .git/info/exclude are the two UIs to invoke the
same mechanism.  In-tree .gitignore are to be shared among project
members (i.e. everybody working on the project should consider the
paths that match the ignore pattern in there as cruft).  On the other
hand, .git/info/exclude is meant for personal ignore patterns (i.e.
you, while working on the project, consider them as cruft).
Assume-unchanged should not be abused for an ignore mechanism. It is,
"I know my filesystem operations are slow. My intention is not to
change these paths so I have Git mark them with the 'assume-unchanged' bit.
So, Git will not check for changes in these paths every time I ask
for 'git status' output".  It does not mean anything other than that.
Especially, Git does not promise to always consider that
these paths are unmodified. If Git can determine any of these paths
have changed without incurring extra
lstat(2) cost, it reserves the right to mark them as modified. As a result, "git commit -a" will commit that change.


[System] You are a helpful assistant.

[User] git-apply - Apply a patch to files and/or to the index  --check

[Assistant]
Instead of applying the patch, see if the patch is
applicable to the current working tree and/or the index
file and detects errors.  Turns off "apply".


[System] You are a helpful assistant.

[User]
How to grep (search through) committed code in the Git history
I have deleted a file or some code in a file sometime in the past. Can I search through the content (not just the commit messages)?
A very poor solution is to grep the log:
git log -p | grep <pattern>

However, this doesn't return the commit hash straight away. I played around with git grep to no avail.

[Assistant]
To search for commit content (i.e., actual lines of source, as opposed to commit messages and the like), you need to do:
git grep <regexp> $(git rev-list --all)

git rev-list --all | xargs git grep <expression> will work if you run into an "Argument list too long" error.
If you want to limit the search to some subtree (for instance, "lib/util"), you will need to pass that to the rev-list subcommand and grep as well:
git grep <regexp> $(git rev-list --all -- lib/util) -- lib/util

This will grep through all your commit text for regexp.
The reason for passing the path in both commands is because rev-list will return the revisions list where all the changes to lib/util happened, but also you need to pass to grep so that it will only search in lib/util.
Just imagine the following scenario: grep might find the same <regexp> on other files which are contained in the same revision returned by rev-list (even if there was no change to that file on that revision).
Here are some other useful ways of searching your source:
Search working tree for text matching regular expression regexp:
git grep <regexp>

Search working tree for lines of text matching regular expression regexp1 or regexp2:
git grep -e <regexp1> [--or] -e <regexp2>

Search working tree for lines of text matching regular expression regexp1 and regexp2, reporting file paths only:
git grep -l -e <regexp1> --and -e <regexp2>

Search working tree for files that have lines of text matching regular expression regexp1 and lines of text matching regular expression regexp2:
git grep -l --all-match -e <regexp1> -e <regexp2>

Search working tree for changed lines of text matching pattern:
git diff --unified=0 | grep <pattern>

Search all revisions for text matching regular expression regexp:
git grep <regexp> $(git rev-list --all)

Search all revisions between rev1 and rev2 for text matching regular expression regexp:
git grep <regexp> $(git rev-list <rev1>..<rev2>)


[System] You are a helpful assistant.

[User]
Git Workflows: Rebasing Published/Shared Branches
Our team at work has enthusiastically adopted a rebase workflow, but we might have gotten a little carried away, which is the point of this question: you be the judge.
Using pull --rebase is a no-brainer to me now.  However, we also have large feature branches that multiple people work on.  Periodically, we want to bring in changes that are happening on master.  Conventional wisdom would have us merge since it's a shared branch.  However, in our rebase-obsession, we've decided to rebase those branches.  Of course that requires everyone's cooperation.  The workflow goes something like this:
1) The rebaser coordinates with everyone to make sure they're all checked-in and pushed on the feature branch, then asks them to do no more work on that branch until they get the all clear.
2) The rebaser rebases the feature branch onto master, deletes the remote feature branch (git push origin :feature), and then pushes the new, rebased feature branch (git push origin feature)
3) The rebaser has everyone fetch, which updates their feature branch, then delete their local feature branch (git branch -D feature), then create a new local feature branch that tracks the remote feature branch.  Everyone then gets the all-clear.
This workflow is working, partially because we're a small group, and the work interruptions are small.  However, I worry that we're learning poor Git habits (rebasing a shared branch), or that the workflow won't scale well.
On the upside, our repository history is lovely.
What do you think, Git gurus?  Are we playing with fire, or rocking a reasonable workflow?
UPDATE:
It's two years since I originally asked the question, and my has our workflow changed since then.  We still routinely do git pull --rebase, so that hasn't changed.  It's common sense, and it prevents all the unsightly, confusing mini-merges.  (We keep mostly in sync, so there's little cost to git pull --rebase).
Other than that, however, and the occasional heroic action to correct a mistake, we are over our rebase madness.  Merging makes sense most of the time.  However, wanton merging is problematic, and does contribute to the confusing, chaotic history I was concerned about two years ago.
Our solution has several components:

The master branch is "pristine".  Topic branches get merged in, and once they do, the topic branch is retired.  In other words, merging a topic branch in signifies that that work is ready for production, and is now part of the master branch.  Looking at our version history, it's very clear what's happening: topic branches getting merged into master, and that's that.
We use disposable integration branches when necessary.  For example, if we have topic branches A, B, and C, and none of them are ready for integration into master, but we need to test them together, we just create a QA branch (usually off of master), and then merge A, B, and C in.  At some point, the QA branch is deleted or re-used.  The point is that it's not intended to be permanent in any way, and it doesn't have the same restrictions as the master branch (you can merge in your topic branches as many times as you want).  If the history gets too confusing, you can just delete the QA branch and start fresh (an approach we have found to be very natural).
When merging, always use git merge --no-ff.  This is such a tremendous reversal from our "linear commit history" obsession from two years ago that it deserves comment.  Now that we've relaxed about a linear commit history, and seen that merges are good and useful, we've started to rely on topic branches being actual branches off of master, not just a series of commits that eventually becomes one with master.  git merge --no-ff ensures there's always a merge commit, even when it's not necessary.
We have a well-understood convention for commit messages and branches and, more importantly, it cross-references our issue-tracking system.  Our issue tracking system uses numeric issue numbers, and for any feature (or defect), we have an issue number (1234, for example).  If you're working on that issue, you would create a branch _1234 and start every commit message with "_1234: doing blah blah".  It may seem a little obsessive, but it has really worked well for us, and significantly reduced/eliminated confusion.
Use a git wrapper to encourage workflow adhesion.  This is something we're currently working on, but we've realized is entirely necessary to prevent simple and understandable mistakes, like branching off of the wrong thing (we recently had a complete disaster when a developer created a topic branch off of a disposable QA branch: that topic branch was approved to go live, it was merged in...and a bunch of changers that weren't approved to go live were sucked in).  Our git wrapper will require confirmation whenever you do something unusual (like creating a branch off of anything but master, creating a branch not named _NNNN, making a commit that doesn't start with _NNNN, etc.).  Occasionally, we do need to do these things, so the wrapper doesn't prevent it, but it does keep people from accidentally doing something they shouldn't.

[Assistant] This sounds like it's overly complicated and won't scale well. It's probably a heck of a lot simpler just to merge master into your feature branch periodically, and then when it comes time to merge back into master, then you can do the rebase first (to remove the intermediate unnecessary merge) and merge back into master (presumably with --no-ff to produce a merge commit). This only requires one person deal with the rebase, and they don't have to do any coordination because nobody else needs to force-update anything (because, presumably, the branch is going to be deleted after it's merged, rather than kept around in a rewritten state). You may also decide to skip the rebase entirely and just leave the intermediate merges in place, which would more accurately reflect your development workflow and remove the risk of producing commits that don't actually build.


[System] You are a helpful assistant.

[User]
Git merge without auto commit
Is it possible to do a git merge, but without a commit?
"man git merge" says this:
With --no-commit perform the merge but pretend the merge failed and do not autocommit,
to give the user a chance to inspect and further tweak the merge result before
committing.

But when I try to use git merge with the --no-commit it still auto-commits.  Here's what I did:
$> ~/git/testrepo$ git checkout master
Switched to branch 'master'

$> ~/git/testrepo$ git branch
* master
  v1.0

$> ~/git/testrepo$ git merge --no-commit v1.0
Updating c0c9fd2..18fa02c
Fast-forward
 file1 |    1 +
 1 files changed, 1 insertions(+), 0 deletions(-)

$> ~/git/testrepo$ git status
# On branch master
# Your branch is ahead of 'origin/master' by 1 commit.
#
nothing to commit (working directory clean)

A subsequent git log reveals all the commits from the v1.0 branch merged into master.

[Assistant]
Note the output while doing the merge - it is saying Fast Forward.
In such situations, you want to do:
git merge <name-of-branch> --no-commit --no-ff

Important: If you do it this way, then you are not able to do any changes to the files in the staging area e.g. you can't remove/add files or make any changes to the files.
If you want to merge the changes and then commit as if you had manually typed all of the changes you merged in (as opposed to a traditional merge) you need to run rm .git/MERGE_HEAD afterward, which will force git to forget that the merge happened.


[System] You are a helpful assistant.

[User] git-remote - Manage set of tracked repositories  update

[Assistant]
Fetch updates for remotes or remote groups in the repository as defined by remotes.<group> . If neither group nor remote is specified on the command line,
the configuration parameter remotes.default will be used; if
remotes.default is not defined, all remotes which do not have the
configuration parameter remote.<name>.skipDefaultUpdate set to true will
be updated.  (See git-config ). With --prune option, run pruning against all the remotes that are updated.


[System] You are a helpful assistant.

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

[Assistant] Remove untracked files from the working tree


[System] You are a helpful assistant.

[User] git-svn - Bidirectional operation between a Subversion repository and Git  -m  --merge  -s<strategy>  --strategy=<strategy>  -p  --rebase-merges

[Assistant] These are only used with the dcommit and rebase commands. Passed directly to git rebase when using dcommit if a git reset cannot be used (see dcommit ).


[System] You are a helpful assistant.

[User]
Git: Could not resolve host github.com error while cloning remote repository in git

What I did: I have created a remote repository on Github and I am trying to clone the remote repository on my local machine. While cloning I am providing the clone URL & target folder.
But every time I try to clone, I am getting this error:
Error: "fatal: unable to access 'https://github.com/hyperion057/spring-repo.git/': Could not resolve host: github.com"
What do I need to do to connect to GitHub ?

[Assistant]
I got a similar error, and it's caused by incorrect proxy setting. This command saved me:
git config --global --unset http.proxy

https version:
git config --global --unset https.proxy


[System] You are a helpful assistant.

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

[Assistant] committer date (format respects --date= option)


[System] You are a helpful assistant.

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

[Assistant]
Specify the style in which conflicted hunks are written out to
working tree files upon merge.  The default is "merge", which
shows a <<<<<<< conflict marker, changes made by one side,
a ======= marker, changes made by the other side, and then
a >>>>>>> marker.  An alternate style, "diff3", adds a ||||||| marker and the original text before the ======= marker.  The
"merge" style tends to produce smaller conflict regions than diff3,
both because of the exclusion of the original text, and because
when a subset of lines match on the two sides, they are just pulled
out of the conflict region.  Another alternate style, "zdiff3", is
similar to diff3 but removes matching lines on the two sides from
the conflict region when those matching lines appear near either
the beginning or end of a conflict region.


[System] You are a helpful assistant.

[User]
Don't add "+" to linux kernel version
I am building linux kernel, if my kernel under git, then kernel version every time is:
Image Name:   Linux-2.6.39+

If I am not using git, then everything is OK without any plus at the end.
I know that this done by scripts/setlocalversion script:
if test "$CONFIG_LOCALVERSION_AUTO" = "y"; then
    # full scm version string
    res="$res$(scm_version)"
else
    # append a plus sign if the repository is not in a clean
    # annotated or signed tagged state (as git describe only
    # looks at signed or annotated tags - git tag -a/-s) and
    # LOCALVERSION= is not specified
    if test "${LOCALVERSION+set}" != "set"; then
        scm=$(scm_version --short)
            res="$res${scm:++}"
        fi
fi

So, it is possible without code changes say to build system that no need to add "+" at the end of version line?

[Assistant]
The plus sign at the end of your version string is there as an indicator that the kernel was built from modified sources (that is, there were non-committed changes). This is also indicated by the comments in scripts/setlocalversion.
To avoid the '+' being appended despite having a dirty working directory, simply set LOCALVERSION explicityly when running make:
make LOCALVERSION=

You may also have to change the configuration option CONFIG_LOCALVERSION_AUTO to n in your kernel config (.config) before building:
sed -i "s|CONFIG_LOCALVERSION_AUTO=.*|CONFIG_LOCALVERSION_AUTO=n|" .config


[System] You are a helpful assistant.

[User]
In Jenkins, how to checkout a project into a specific directory (using GIT)

Sorry for the 'svn' style - we are in a process of migration from SVN to GIT (including our CI Jenkins environment).
What we need is to be able to make Jenkins to checkout (or should I say clone?) the GIT project (repository?) into a specific directory. We've tried some refspecs magic but it wasn't too obvious to understand and use successfully.
Furthermore, if in the same Jenkins project we need to checkout several private GitHub repositories into several separate dirs under a project root, how can we do it please?
We have GitHub plugin installed. Hope we've phrased the things right.

[Assistant]
In the new Jenkins 2.0 pipeline (previously named the Workflow Plugin), this is done differently for:

The main repository
Other additional repositories

Here I am specifically referring to the Multibranch Pipeline version 2.9.
Main repository
This is the repository that contains your Jenkinsfile.
In the Configure screen for your pipeline project, enter your repository name, etc.
Do not use Additional Behaviors > Check out to a sub-directory.  This will put your Jenkinsfile in the sub-directory where Jenkins cannot find it.
In Jenkinsfile, check out the main repository in the subdirectory using dir():
dir('subDir') {
    checkout scm
}

Additional repositories
If you want to check out more repositories, use the Pipeline Syntax generator to automatically generate a Groovy code snippet.
In the Configure screen for your pipeline project:

Select Pipeline Syntax. In the Sample
Step drop down menu, choose checkout: General SCM.
Select your SCM system, such as Git.  Fill in the usual information
about your repository or depot.
Note that in the Multibranch Pipeline, environment variable
env.BRANCH_NAME contains the branch name of the main repository.
In the Additional Behaviors drop down menu, select
Check out to a sub-directory
Click Generate Groovy. Jenkins will display the Groovy code snippet
corresponding to the SCM checkout that you specified.
Copy this code into your pipeline script or Jenkinsfile.


[System] You are a helpful assistant.

[User]
git: change one line in file for the complete history
When I started my git repo I commited a few files as initial commit to it. Now, many commits later, I noticed that I included in those files a line with information which I do not want to publish (unlike the rest of the code). So I want to remove/change this one line and keep the rest of the code.
Searching around I found this solution: Insert an empty commit as initial commit (described here: Insert a commit before the root commit in Git?), do a rebase on it and then edit the old first commit via amend. Unfortunately, many cruel merge conflicts arise during rebase (as described here: git: solving conflicts caused by rebase).
Is there a different way to solve my problem or do have to rebase and edit all conflicts by hand?
Thanks in advance :)

[Assistant]
Here's a command that will remove an offending line from a file's history in all your branches:
git filter-branch --tree-filter 'sed -i "/sensitive information/ d" filename' -- --all

This checks out every revision, runs the sed command on it, then commits that revision back.
The sed command in this case matches any lines containing the pattern sensitive information in the file named filename and deletes those lines.
Note:  it's good if you have a backup, and try the sed script on its own first to make sure it's doing what you want, because it can take quite a while to run on a long history.


[System] You are a helpful assistant.

[User]
github/git Checkout Returns 'error: invalid path' on Windows
When I attempt to checkout a repository from github I get the error:
error: invalid path 'configs/perl-modules/DIST.64/perl-HTML-Tree-1:5.03-1.el6.noarch.rpm'

I suspect the issue is that the path contains a : which is illegal on Windows.
After researching the error, I've found 2 possible answers:
1) Change the path on the repository file.  Unfortunately, this is is a team resource and can not be fixed in the foreseeable future.
2) Use sparse-checkout.  I've tried this with no effect as evidenced in the following:

$ git clone -n [email protected]:XXXXXX/deploy.git
Cloning into 'deploy'...
remote: Enumerating objects: 57, done.
remote: Counting objects: 100% (57/57), done.
remote: Compressing objects: 100% (49/49), done.
remote: Total 86457 (delta 10), reused 22 (delta 8), pack-reused 86400
Receiving objects: 100% (86457/86457), 1.50 GiB | 4.73 MiB/s, done.
Resolving deltas: 100% (59779/59779), done.
$ cd deploy/
$ git config core.sparsecheckout true
$ echo www >> .git/info/sparse-checkout
$ git checkout centos6
error: invalid path 'configs/perl-modules/DIST.64/perl-HTML-Tree-1:5.03-1.el6.noarch.rpm'
error: invalid path 'configs/perlbrew/perls/perl-5.24.1/man/man3/App::Cpan.3'
.
. (repeat for many files)
.

This was done with Git for Windows "git version 2.28.0.windows.1".  I have also tried both types of line endings and using various version of .git/info/sparse-checkout such as:
/*
!/configs/perl-modules
!/configs/perlbrew/perls/perl-5.24.1/man/man3

Checkout works fine on Linux, MacOS and WSL, only problem is that my IDEs don't work there.  Why isn't sparse-checkout working on Windows.  Is there any other possibilities?

[Assistant]
After I opened an issue on the git-for-windows bug tracker (https://github.com/git-for-windows/git/issues/2803), I found that my issue had already been filed as https://github.com/git-for-windows/git/issues/2777.  That issue suggested that I need to set another git flag:
git config core.protectNTFS false

This (#2777) indeed contains a bypass for the my problem.  I hope the git or git-for-windows (who were very responsive) come up with a better warning message, or even a true fix like a filepath mapping scheme.
Note that this is only an issue when using sparse-checkout with windows.


[System] You are a helpful assistant.

[User]
GitHub - How to revert changes to previous state

I am using GitHub as my remote repository.
I have already pushed 5 commits to the server and want to revert back to the state before the those commits.
If the commit hash is 3425661dba2aadccdbab, how do I revert the entire local/remote back to that commit? I tried
$ reset --hard 3425661dba2aadccdbab

but that only resetted my working head to that branch and requires me to do a git pull again. I tried checkout, but this caused me to land in a "detached head" branch.

[Assistant]
You basically have two options to revert changes:

create a new commit which applies reverse changes. This is the preferred option as it doesn't changes history on a public repository
Remove the commits and force push them.

The first option can be achieved by using git revert

git-revert - Revert some existing commits
Given one or more existing commits, revert the changes that the related patches introduce, and record some new commits that record them.

An example would be git revert -n HEAD~5..HEAD. This command creates 5 new commits, each of which undoes one of the last 5 commits of the currently checked out branch.
The second option would be to actually remove the commits. Note that this changes history in the repository. So anyone who has already pull the changes will probably be rather surprised and things can get messy quickly. That said, you can do
git reset --hard HEAD~5
git push --force

The first command will wipe any uncommitted changes in your current working copy. and reset your local repository to the state of the current HEAD - 5 commits. The second command will force-push to the default remote (i.e. GitHub) There, any changes diverging from your current local repository are overwritten.
A note of warning again: If you don't really know what you are doing, don't use this option as it can lead to data loss for you or others if not done right. Use the first option instead as it will transparently remove changes but without the nasty side-effects of history-rewriting.


[System] You are a helpful assistant.

[User]
How to have a Gitlab CI Pipeline run some jobs always and other jobs only on merge-requests?

TL/DR:
My goal is to have a Gitlab (CE-12.4.2) pipeline that executes some jobs only on merge-requests and other jobs always (on merge-requests and on all normal pushes). How must the .gitlab-ci.yml look to do this?
My use-case:
I have a big pipeline running a lot of jobs (tests, validation, dep's, build, doc's, ...). Now I have added a staging environment (using kubernetes) and have the pipeline build a new image and deploy that in the staging-environment. This allows me to instantly open up the changed (web-)application and see how the changes behave and look without having to check them out locally. Now building an image and deploying it to staging would be much too resource-heavy to do for every push, so I only want deployments to staging when someone creates a merge-request for me to review.
A very simplified example:
install:
  script: ...

test:
  script: ...

build-image:
  script: ...
  only: [merge_requests]

deploy-staging:
  script: ...
  only: [merge_requests]

For all normal pushes, the jobs install and test should be executed.
For merge-requests, the jobs install, test, build-image and deploy-staging should be executed.
What i have tried: Gitlab has this feature to define only: [merge_requests] on a job, this causes that job to only be executed when the pipeline is executed for a merge-request. Sounds like exactly what I am looking for, but there is a big catch. Once that attribute is applied to one job in a pipeline, all other jobs in that pipeline that do not have that attribute will be removed from the pipeline when executed inside merge-requests. That seemed like a bug to me at first, but is actually documented behaviour:
In the above example, the pipeline contains only a test job. Since the build and deploy jobs don’t have the only: [merge_requests] parameter, they will not run in the merge request.

In order to re-introduce all the other jobs to the pipeline for merge-requests, I have to apply only: [merge_requests] to all other jobs. The problem with that approach is that now these regular jobs do not get executed for normal git-pushes anymore. And I have no way to re-introduce these regular jobs to pipelines for normal pushes, because Gitlab has no support for only: [always] or anything like that.
Now I also have noticed that the only syntax is candidate for deprecation and one should prefer the rules syntax instead, so I took a look at that. There are multiple problems with that approach:

The only way to detect with rules whether the pipeline is executed for a merge-request or not is to evaluate the variables related to merge-requests, like $CI_MERGE_REQUEST_ID. Unfortunately these variables only exist when only: [merge_requests] is used, which would re-introduce the above problems.
Rules only allow the conditional application of other attributes, so I still would have to use only, except or when attributes to actually remove or add jobs from or to the pipeline. Unfortunately Gitlab does not support anything like only: [never] or when: never, so i have no way to actually remove or add the jobs.

I also tried to have the jobs depend on another using need or dependencies attributes, this seemed to have no effect on whether the job is included to the pipeline or not.
The last thing I desperately tried was including all jobs always and just mark them as when: manual to be triggered manually by pushing a button. This somewhat works, but is very tedious because the deployment to staging is a multi-job process with every job taking quite some time to finish. So I would see a merge-request, push the button for the first job, wait 5 minutes, press the next button, wait 5 minutes again, and only then am able to use the staging. For many small merge-requests, this would take up a lot of my time and would not be a efficient solution. I also cannot just mark the first of these jobs as manual because Gitlab will then just skip that job and execute that later ones out of order (And again, needs and dependencies seem to have no effect on this when dealing with manually triggered jobs).
What i am a bit baffled about is that after searching the net, I have found nobody having the same problem. Either I am the only Gitlab User that wants to execute some jobs only for merge-requests without excluding all other jobs (which seems highly unlikely) or I am missing something obvious (which seems more likely). Am I missing something or does Gitlab really not support this use-case?

[Assistant]
From the previous answer:

But there is a problem. This example launches two pipelines for every push after MR is created. One for only: [branch], one for only: [merge_requests]

Check if the last GitLab 13.8 (January 2021) can help:

Use both branch and MR pipelines without duplication
Previously it was not possible to run pipelines for branches first, then switch to merge requests pipelines when the MR is created.
Consequently, with some configurations, a push to a branch could result in duplicate pipelines if a merge request was already open on the branch: one pipeline on the branch and another for the merge request.
Now you can use the new $CI_OPEN_MERGE_REQUESTS predefined environment variable in your CI configurations to switch from branch pipelines to MR pipelines at the right time, and prevent redundant pipelines.

See Documentation and Issue.

user2993689 points out in the comments to the documentation for a similar example:

Avoid duplicate pipeline


[System] You are a helpful assistant.

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

[Assistant] (ERROR) A tree has an invalid format.


[System] You are a helpful assistant.

[User]
Why does git say "Pull is not possible because you have unmerged files"?
When I try to pull in my project directory in the terminal, I see the following error:
harsukh@harsukh-desktop:~/Sites/branch1$ git pull origin master
U app/config/app.php
U app/config/database.php
U app/routes.php
Pull is not possible because you have unmerged files.
Please, fix them up in the work tree, and then use 'git add/rm <file>'
as appropriate to mark resolution, or use 'git commit -a'.

Why does git say "Pull is not possible because you have unmerged files", and how can I resolve it?

[Assistant]
What is currently happening is, that you have a certain set of files, which you have tried merging earlier, but they threw up merge conflicts.
Ideally, if one gets a merge conflict, they should resolve them manually, and commit the changes using git add file.name && git commit -m "removed merge conflicts".
Now, another user has updated the files in question on their repository, and has pushed their changes to the common upstream repo.
It so happens, that your merge conflicts from (probably) the last commit were not not resolved, so your files are not merged all right, and hence the U(unmerged) flag for the files.
So now, when you do a git pull, git is throwing up the error, because you have some version of the file, which is not correctly resolved.
To resolve this, you will have to resolve the merge conflicts in question, and add and commit the changes, before you can do a git pull.
Sample reproduction and resolution of the issue:
# Note: commands below in format `CUURENT_WORKING_DIRECTORY $ command params`
Desktop $ cd test

First, let us create the repository structure
test $ mkdir repo && cd repo && git init && touch file && git add file && git commit -m "msg"
repo $ cd .. && git clone repo repo_clone && cd repo_clone
repo_clone $ echo "text2" >> file && git add file && git commit -m "msg" && cd ../repo
repo $ echo "text1" >> file && git add file && git commit -m "msg" && cd ../repo_clone

Now we are in repo_clone, and if you do a git pull, it will throw up conflicts
repo_clone $ git pull origin master
remote: Counting objects: 5, done.
remote: Total 3 (delta 0), reused 0 (delta 0)
Unpacking objects: 100% (3/3), done.
From /home/anshulgoyal/Desktop/test/test/repo
 * branch            master     -> FETCH_HEAD
   24d5b2e..1a1aa70  master     -> origin/master
Auto-merging file
CONFLICT (content): Merge conflict in file
Automatic merge failed; fix conflicts and then commit the result.

If we ignore the conflicts in the clone, and make more commits in the original repo now,
repo_clone $ cd ../repo
repo $ echo "text1" >> file && git add file && git commit -m "msg" && cd ../repo_clone

And then we do a git pull, we get
repo_clone $ git pull
U   file
Pull is not possible because you have unmerged files.
Please, fix them up in the work tree, and then use 'git add/rm <file>'
as appropriate to mark resolution, or use 'git commit -a'.

Note that the file now is in an unmerged state and if we do a git status, we can clearly see the same:
repo_clone $ git status
On branch master
Your branch and 'origin/master' have diverged,
and have 1 and 1 different commit each, respectively.
  (use "git pull" to merge the remote branch into yours)

You have unmerged paths.
  (fix conflicts and run "git commit")

Unmerged paths:
  (use "git add <file>..." to mark resolution)

        both modified:      file

So, to resolve this, we first need to resolve the merge conflict we ignored earlier
repo_clone $ vi file

and set its contents to
text2
text1
text1

and then add it and commit the changes
repo_clone $ git add file && git commit -m "resolved merge conflicts"
[master 39c3ba1] resolved merge conflicts


[System] You are a helpful assistant.

[User]
Is there an upper limit to the number of commits a git repository can handle?
I'm wondering if there's an upper limit to the number of commits that a git repository can handle.
In a solo project I'm working on right now, I've been coding locally, committing/pushing changes in git, then pulling the changes on my development server.
I treat this as an easier alternative to working locally and uploading changes via FTP... Fortunately/Unfortunately it's such an easy workflow that I sometimes go through many edit/commit/push/pull/browser-refresh cycles while coding.
I'm wondering if this is going to turn around and bite me somewhere down the line.  If it's likely to be a problem, I'm wondering how I can avoid that trouble ... It seems like a rebase might be the way to go, especially since I won't have to worry about conflicting branches etc.

[Assistant]
Well the "upper limit" would likely be the point at which a SHA1 collision occurs, but since the SHAs are 40 hexadecimal digits long (16^40 ~ 1.4x10^48 possibilities), it's so close to zero possibility that it's not even funny. So there's roughly a zero percent chance you'll have any problems for at least the next several millennia.
Hyperbolic Example (just for fun): 1 commit/minute (just changing one file -> three new SHAs used (file, commit, tree) = 3 new shas used / minute = ... = 1.6M shas used / year = 1.6 Billion shahs / millennia = 1x10^-37 % used each millenia... (at 1000 files/commmit/min, it's still 3.6x10^-35%)
That being said, if you want to clean up your history, squashing them down with rebase is probably your best bet. Just make sure you understand the implications if you've shared the repo publicly at all.
You might also want to garbage collect after rebasing to free up some space (make sure the rebase worked right first, though, and you might need to tell it to collect everything or it will, by default, not collect anything newer than two-weeks old).


[System] You are a helpful assistant.

[User] git-config - Get and set repository or global options  gc.auto

[Assistant]
When there are approximately more than this many loose
objects in the repository, git gc --auto will pack them.
Some Porcelain commands use this command to perform a
light-weight garbage collection from time to time.  The
default value is 6700. Setting this to 0 disables not only automatic packing based on the
number of loose objects, but also any other heuristic git gc --auto will
otherwise use to determine if there’s work to do, such as gc.autoPackLimit .


[System] You are a helpful assistant.

[User]
How to git bundle a complete repo
I need to transfer a complete repo to a new non-networked machine, preferable as a single file entity. The git bundle allows a git fetch, git pull style operation in a sneakernet environment but appears to assume that you already have a working version of the repo on the destination machine.
What is the right invocation to:

Bundle all the branches in the current repo
Start up the new repo on the destination directory, i.e. get the root commit correctly installed

I've sent a patch upstream to clarify:
`git clone` can use any bundle created without negative refspecs
(e.g., `new`, but not `old..new`).
If you want to match `git clone --mirror`, which would clone other
refs such as `refs/remotes/*`, use `--all`.
If you want to provide the same set of refs that a clone directly
from the source repository would get, use `--branches --tags` for
the `<git-rev-list-args>`.

So $ git bundle create repo.bundle --branches --tags best matches cloning.
$ git bundle create repo.bundle --all will provide a mirror image of your source machine, including its remote refs.

[Assistant]
What is the right invocation to:

Bundle all the branches in the current repo

Simple:
$ git bundle create repo.bundle --all

Here repo.bundle is the name of bundle file you want to create.  Note that --all would not include remote-tracking branches... just like ordinary clone wouldn't either.

Start up the new repo on the destination directory, i.e. get the root commit correctly installed

First, clone is just init + fetch (+ administrativia).
Second, you can use bundle file everywhere the repository URL can be used, so you can simply clone from a bundle file:
$ git clone repo.bundle

This would create repo as a git repository.


[System] You are a helpful assistant.

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

[Assistant]
By default, git-receive-pack will run "git maintenance run --auto" after
receiving data from git-push and updating refs.  You can stop
it by setting this variable to false.


[System] You are a helpful assistant.

[User]
How do I disable git's credential helper for a single repository?
If I have a credential helper set in my ~/.gitconfig, how can I disable/bypass it in a specific repo and use no credential helper?
I've tried editing the repo's .git/config file to blank out the credential.helper property like this:
[credential]
    helper =

... but when I do a git push I get the following error message, and Git uses my default credential helper from ~/.gitconfig anyway:
git: 'credential-' is not a git command. See 'git --help'.

Did you mean this?
        credential

I'm using git version 1.7.12.
(Backstory/use case: Git is configured to use the store helper, which stores passwords unencrypted on disk. The cache helper is unavailable on this system. I have a couple repos for which I'd rather type the password every time than keep it on disk.)

[Assistant]
With git 2.9 (June 2016), this (helper = ) will actually work!
The credential.helper configuration variable is cumulative and there is no good way to override it from the command line.
As a special case, giving an empty string as its value now serves as the signal to clear the values specified in various files.
See commit 2432137 (26 Feb 2016) by Jeff King (peff).
(Merged by Junio C Hamano -- gitster -- in commit 1b68962, 03 Apr 2016)

credential: let empty credential specs reset helper list

Since the credential.helper key is a multi-valued config list, there's no way to "unset" a helper once it's been set. So if your system /etc/gitconfig sets one, you can never avoid running it, but only add your own helpers on top.
Since an empty value for credential.helper is nonsensical (it would just try to run "git-credential-"), we can assume nobody is using it. Let's define it to reset the helper list, letting you override lower-priority instances which
have come before.

Even more convenient: With Git 2.26 (Q1 2020), this override applies even for any value.
See commit 46fd7b3, commit 82eb249, commit 588c70e, commit 732f934, commit 3fa0e04 (20 Feb 2020) by brian m. carlson (``).
(Merged by Junio C Hamano -- gitster -- in commit 2cbb058, 05 Mar 2020)

credential: use the last matching username in the config
Signed-off-by: brian m. carlson

Everywhere else in the codebase, we use the rule that the last matching configuration option is the one that takes effect.
This is helpful because it allows more specific configuration settings (e.g., per-repo configuration) to override less specific settings (e.g., per-user configuration).
However, in the credential code, we didn't honor this setting, and instead picked the first setting we had, and stuck with it.
This was likely to ensure we picked the value from the URL, which we want to honor over the configuration.
It's possible to do both, though, so let's check if the value is the one we've gotten over our protocol connection, which if present will have come from the URL, and keep it if so.
Otherwise, let's overwrite the value with the latest version we've got from the configuration, so we keep the last configuration value.

Note: user202729 adds in the comments:

If credential helper A is set as global and you want to use B in a local repository (change, not remove the helper), use:
git config --local credential.helper ''
git config --local --add credential.helper B

The first empty item removes the global setting A.
Equivalently, set two lines helper = and helper = B in .git/config.


[System] You are a helpful assistant.

[User] gitglossary - A Git Glossary  unborn

[Assistant]
The HEAD can point at a branch that does not yet exist and that does not have any commit on
it yet, and such a branch is called an unborn branch.  The
most typical way users encounter an unborn branch is by
creating a repository anew without cloning from elsewhere.
The HEAD would point at the main (or master , depending
on your configuration) branch that is yet to be born.  Also
some operations can get you on an unborn branch with their orphan option.


[System] You are a helpful assistant.

[User]
Editing the git commit message in GitHub
Is there any way of online editing the commit message in GitHub.com, after submission?
From the command line, one can do
git commit --amend -m "New commit message"

as correctly suggested in the following question:

How to modify existing, unpushed commit messages?

Trying git pull and then git push has worked (without any other commit having interfered in the mean time).
But can it be done via the GitHub website?

[Assistant]
GitHub's instructions for doing this:

On the command line, navigate to the repository that contains the commit you want to amend.
Type git commit --amend and press Enter.
In your text editor, edit the commit message and save the commit.
Use the git push --force origin example-branch command to force push over the old commit.

Source: https://help.github.com/articles/changing-a-commit-message/


[System] You are a helpful assistant.

[User]
Download single files from GitHub
What are some tips on downloading a single file from a GitHub repo?
I don't want the URL for displaying the raw file; in the case of binaries, there's nothing.
http://support.github.com/discussions/feature-requests/41-download-single-file
Is it even possible to use GitHub as a "download server"?
If we decide to switch to Google Code, is the mentioned functionality presented there?
Or is there any free-of-charge hosting and VCS for open-source projects?

[Assistant]
Go to the file you want to download.
Click it to view the contents within the GitHub UI.
In the top right, right click the Raw button.
Save as...


[System] You are a helpful assistant.

[User] git-fast-import - Backend for fast Git data importers  Reading from the active commit

[Assistant]
This form can only be used in the middle of a commit .
The path names a directory entry within fast-import’s
active commit.  The path must be quoted in this case. 'ls' SP <path> LF


[System] You are a helpful assistant.

[User]
Find the root of the git repository where the file lives
When working in Python (e.g. running a script), how can I find the path of the root of the git repository where the script lives?
So far I know I can get the current path with:
path_to_containing_folder = os.path.dirname(os.path.realpath(__file__))

How can I then find out where the git repository lives?

[Assistant]
Use the GitPython module http://gitpython.readthedocs.io/en/stable/.
pip install gitpython

Assume you have a local Git repo at /path/to/.git. The below example receives /path/to/your/file as input, it correctly returns the Git root as /path/to/.
import git

def get_git_root(path):

        git_repo = git.Repo(path, search_parent_directories=True)
        git_root = git_repo.git.rev_parse("--show-toplevel")
        print git_root

if __name__ == "__main__":
    get_git_root("/path/to/your/file")


[System] You are a helpful assistant.

[User]
GitLab.com CI shared runner for Android projects

I'd like to use GitLab CI system for my Android application gradle project. The project repository is hosted on GitLab.com, so I'd like to use one of the Shared Runners provided by Gitlab Inc.
While the official tutorial provides an example for NodeJS project runner configuration and there are also shared runners for Ruby projects, I couldn't find any example or even a runner that supports Android applications.

Is there a shared runner provided by GitLab.com, which supports Android projects out of the box (by specifying image: android:4.2.2 or something like this)?
Is there a way to configure existing shared runner provided by GitLab.com to support Android projects (by modifying the .gitlab-ci.yml file)?

[Assistant]
I'm using this docker image to run android build on gitlab-ci
Update:
Moved to Gitlab registry
image: registry.gitlab.com/showcheap/android-ci:latest

before_script:
    - export GRADLE_USER_HOME=`pwd`/.gradle
    - chmod +x ./gradlew

cache:
  paths:
     - .gradle/wrapper
     - .gradle/caches

build:
  stage: build
  script:
     - ./gradlew assemble

test:
  stage: test
  script:
     - ./gradlew check

Full Guide can check in this Gitlab Repository:
https://gitlab.com/showcheap/android-ci
If your Target SDK and Build Tools version are not listed, please make a pull request or fork my repo then make your custom target and build version.


[System] You are a helpful assistant.

[User]
Changing the Git user inside Visual Studio Code
The user for my Git commits has changed, but I am not able to change that inside of Visual Studio Code.
I changed the global settings in Git, but when I want to push or sync via Visual Studio Code inside my new repositories I get the error that the oldusername has not the permission to push into newrepository.
At this point it is not the permission. The change of the username did not work for Visual Studio Code. When I use the terminal I can push. It is also not a solution to allow the olduser to push to the newrepository.
I am on Windows 10. So all other tools are working, but just at Visual Studio Code I was not able to change the user.
How can I fix this problem?

[Assistant]
I resolved this issue by setting an email address in Git:
git config --global user.email "[email protected]"


[System] You are a helpful assistant.

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

[Assistant] author email (respecting .mailmap, see git-shortlog or git-blame )


[System] You are a helpful assistant.

[User]
Git: warning: refname 'master' is ambiguous
I saw a few people asking the same question on here but it seems none of their advice is applicable to me. I'm getting the warning that is in the title of this but I don't have any tags named "master". This is the result of git branch -a:
* master
  remotes/origin/HEAD -> origin/master
  remotes/origin/master

Any idea what could be going wrong here? I've only been using git for a few months now, so it mostly just worries me that this ambiguity might mess with the repo in the future.

[Assistant]
For me I tracked down the source of this warning to much earlier when I incorrectly issued an "update-ref" command.  If you forget to specify the full refs/heads/mybranchname path in the first arg, then a file .git/mybranchname gets created, which later leads to this warning when you try to switch to that branch.
It is solved by simply deleting the .git/mybranchname, eg:
rm .git/master

And for reference, the correct form for the update-ref command is:
git update-ref refs/heads/mybranchname mytargetbranch

Don't forget the "refs/heads" part!
Also, my most common use-case for update-ref is simply manually moving a branch to point to another commit, which I've found a simpler syntax to do:
git branch -f myBranchToMove destinationBranchOrHash
This syntax is easier for me because it doesn't require that error-prone refs/heads path qualifier.


[System] You are a helpful assistant.

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

[Assistant]
Shown when git-fetch takes a long time
to calculate forced updates after ref updates, or to warn
that the check is disabled.


[System] You are a helpful assistant.

[User] git-rev-parse - Pick out and massage parameters  HEAD

[Assistant] names the commit on which you based the changes in the working tree.


[System] You are a helpful assistant.

[User]
How to determine the URL that a local Git repository was originally cloned from

I pulled a project with several forks on GitHub, but forgot which fork it was. How do I determine which fork I pulled?

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

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

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

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


[System] You are a helpful assistant.

[User] git-rev-parse - Pick out and massage parameters  <rev>^{/<text>} , e.g. HEAD^{/fix nasty bug}

[Assistant]
A suffix ^ to a revision parameter, followed by a brace
pair that contains a text led by a slash,
is the same as the :/fix nasty bug syntax below except that
it returns the youngest matching commit which is reachable from
the <rev> before ^ .


[System] You are a helpful assistant.

[User]
How do you rename a Git tag?
Today I was looking through the logs for a project and realized that I fat fingered a tag name some time ago. Is there some way to rename the tag? Google hasn't turned up anything useful.
I realize I could check out the tagged version and make a new tag, I even tried that. But that seems to create a tag object that isn't quite right. For one,
git tag -l

lists it out of order relative to all of the other tags. I have no idea if that's significant, but it leads me to believe that the new tag object isn't quite what I want. I can live with that, because I really only care that the tag name matches the documentation, but I'd rather do it "right", assuming there is a right way to do this.

[Assistant]
Here is how I rename a lightweight tag old to new:
git tag new old           # Create a new local tag named `new` from tag `old`.
git tag -d old            # Delete local tag `old`.
git push origin new :old  # Push `new` to your remote named "origin", and delete
                          #     tag `old` on origin (by pushing an empty tag
                          #     name to it).

The colon in the push command removes the tag from the remote repository. If
you don't do this, Git will create the old tag on your machine when you pull.
Finally, make sure that the other users remove the deleted tag. Please tell
them (co-workers) to run the following command:
git fetch --prune --prune-tags

Note that if you are renaming an annotated tag, you need to ensure that the new tag name is referencing the underlying commit and not the old annotated tag object that you're about to delete. If the old tag is an annotated tag, or you aren't sure, you can use ^{} to dereference the object until a non-tag object is found:
# create a new annotated tag "new" referencing the object
# which the old annotated tag "old" was referencing:
git tag -a new old^{}


[System] You are a helpful assistant.

[User] git-svn - Bidirectional operation between a Subversion repository and Git  -r <n>[:<n>]  --revision=<n>[:<n>]

[Assistant]
is supported, non-numeric args are not:
HEAD, NEXT, BASE, PREV, etc …


[System] You are a helpful assistant.

[User] gitglossary - A Git Glossary

[Assistant] NAME gitglossary - A Git Glossary