[System] You are a helpful assistant.

[User]
How to update my fork to have the same branches and tags as the original repository on github?

When you fork a repository on github your forked repo contains all branches and tags.
Over time these branches and tags gets outdated.
How does one as easy it is with fork make sure your fork has all branches and tags without having to reclone ?
i.e. a git magicpull --rebase upstream/* myremote/*
which would fetch all the branches and tags in upstream and make sure the same are present in myremote.

[Assistant]
This assumes your "upstream" remote is named "origin" and you have your custom fork under your username (i.e. "maxandersen")
When you have your clone run the following one-liner (refresh of Track all remote git branches as local branches :
remote=origin ; for brname in `git branch -r | grep origin | grep -v master | grep -v HEAD | sed -e 's/^[^\/]*\///'`; do git branch --track $brname  $remote/$brname ; done

This will setup tracking branches for all the branches found in the remote named 'origin'.
If you already have a checkout with this branchname it will not change anything except ensure the tracking is in place.
(Optional) Now ensure all your branches are uptodate (useful if you have already branches checked out):
git pull --rebase --all

Now with all branches setup for tracking and uptodate push branches and tags to your remote (replace 'maxandersen' with your remote name):
git push --all maxandersen
git push --tags maxandersen

After this your fork is in sync.
The following script does all this including asking for confirmation:
## Checkout all branches from remote as tracking branches. Based on    https://stackoverflow.com/questions/379081/track-all-remote-git-branches-as-local-branches/6300386#6300386

UPSTREAM=$1
MYREPO=$2

usage() {
   echo "Usage:"
   echo "$0 <upstream-remote> <target-remote>"
   echo ""
   echo "Example which ensures remote named 'maxandersen' have all the same branches and tags as 'origin'"
   echo "$0 origin maxandersen"
   exit 1
}

if [ -z "$UPSTREAM" ]
then
 echo Missing upstream remote name.
 usage
fi

if [ -z "$MYREPO" ]
then
 echo Missing target remote name.
 usage
fi

read -p "1. This will setup '$MYREPO' to track all branches in '$UPSTREAM' - Are you sure ?" -n 1 -r

if [[ $REPLY =~ ^[Yy]$ ]]
then
 for brname in `git branch -r | grep "$UPSTREAM" | grep -v master | grep -v HEAD | sed -e 's/.*\///g'`; do git branch --track $brname  $UPSTREAM/$brname ; done
fi

read -p "2. This will push all local branches and tags into '$MYREPO' - Are you sure ?" -n 1 -r

if [[ $REPLY =~ ^[Yy]$ ]]
then
 git push --all $MYREPO
 git push --tags $MYREPO
fi

Save it as 'updateallbranchestags.sh' and execute it with:
sh updateallbranches.sh origin maxandersen

And all branches/tags from 'origin' will be made available in remote named 'maxandersen'


[System] You are a helpful assistant.

[User]
Viewing a Deleted File in Git
I've deleted a file with Git and then committed, so the file is no longer in my working copy. I want to look at the contents of that file, but not actually restore it. How can I do this?

[Assistant]
git show HEAD^:path/to/file

You can use an explicit commit identifier or HEAD~n to see older versions or if there has been more than one commit since you deleted it.


[System] You are a helpful assistant.

[User] git-log - Show commit logs  -F  --fixed-strings

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


[System] You are a helpful assistant.

[User]
Pull new updates from original GitHub repository into forked GitHub repository

I forked someone's repository on GitHub and would like to update my version with commits and updates made in the original repository. These were made after I forked my copy.
How can I pull in the changes that were made in the origin and incorporate them into my repository?

[Assistant]
You have to add the original repository (the one you forked) as a remote.
From the GitHub documentation on forking a repository:

Once the clone is complete your repo will have a remote named “origin” that points to your fork on GitHub.
Don’t let the name confuse you, this does not point to the original repo you forked from. To help you keep track of that repo we will add another remote named “upstream”:
$ cd PROJECT_NAME
$ git remote add upstream https://github.com/ORIGINAL_OWNER/ORIGINAL_REPOSITORY.git
$ git fetch upstream

# then: (like "git pull" which is fetch + merge)
$ git merge upstream/master master

# or, better, replay your local work on top of the fetched branch
# like a "git pull --rebase"
$ git rebase upstream/master

There's also a command-line tool (gh) which can facilitate the operations above.
Here's a visual of how it works:

See also "Are Git forks actually Git clones?".


[System] You are a helpful assistant.

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

[Assistant]
Under certain circumstances, some versions of diff do not correctly
detect a missing new-line at the end of the file. As a result, patches
created by such diff programs do not record incomplete lines
correctly. This option adds support for applying such patches by
working around this bug.


[System] You are a helpful assistant.

[User] git-log - Show commit logs  no

[Assistant] Moved lines are not highlighted.


[System] You are a helpful assistant.

[User]
Git workflow without a server
Git is supposed to be a decentralized system, but all the tutorials and
best practice workflows I have found on Google suggest using a server
(usually GitHub, or else set up your own)
I am using git for small personal projects (2-3 people), where can I find
a best practice workflow for syncing changes directly between the team members machines.
Alternatively, what are some compelling arguments for why I should avoid this and instead set up a 'central' server?

[Assistant]
Depends on what you mean by "server". Git will work happily without a central server, although many teams find it convenient to have a central repository.
If by "server", you mean "install server software", git will also work (central repository or not) without any special software, through ssh or on the file system.
See this document for possible workflows
Workflow with common repository
The workflow that many use is that all developers "push" (send) their changes to a common repository, and get all the changes from that repository. Something like this:

Developer A pushes to central
Developer B pushes to central
Developer C pulls (getting changes from A and B)
Developer A pulls (getting changes from B)
...

In this case the central repository can be on one of the Developers computers, on github, or any other place
Workflow with Email
You can also use git without any server, just using email. In this case the flow would be like this:

Developer A sends changes as an email to the team
Other developers apply the changes from the emails

This can even be done in a semi-automated way
Workflow without a central server
You can setup git to use more than one "remote" repository. The caveat is that you should never push to a repository that is checked out (that is, a Developer copy on which someone is working). So in this case the flow would be like this:

Developer A makes changes
Developer B makes changes
Developer C pulls changes from A
Developer C pulls changes from B
Developer B pulls changes from A
...
No one must ever push

IMHO this type of workflow will quickly lead to confusion and breakdown.


[System] You are a helpful assistant.

[User]
Output of git branch in tree like fashion
Right now, when I type "git branch"
it lists my branches in an arbitrary order.
What I would prefer would be if "git branch" listed my output in a tree like fasion, somethign like:
master
|-- foo
  |-- foo1
  |-- foo2
|-- bar
  |-- bar4

Where here, foo & bar were branched from master; foo1 & foo2 were branched from foo; bar4 was branched from bar.
Is this easy to accomplish?
[Command line utilities only. This needs to fit into my zsh/vim workflow.]

[Assistant]
The answer below uses git log:
I mentioned a similar approach in 2009 with "Unable to show a Git tree in terminal":
git log --graph --pretty=oneline --abbrev-commit

But the full one I have been using is in "How to display the tag name and branch name using git log --graph" (2011):
git config --global alias.lgb "log --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset%n' --abbrev-commit --date=relative --branches"

git lgb

Original answer (2010)
git show-branch --list comes close of what you are looking for (with the topo order)
--topo-order

By default, the branches and their commits are shown in reverse chronological order.
  This option makes them appear in topological order (i.e., descendant commits are shown before their parents).

But the tool git wtf can help too. Example:
$ git wtf
Local branch: master
[ ] NOT in sync with remote (needs push)
    - Add before-search hook, for shortcuts for custom search queries. [4430d1b] (edwardzyang@...; 7 days ago)
Remote branch: origin/master ([email protected]:sup/mainline.git)
[x] in sync with local

Feature branches:
{ } origin/release-0.8.1 is NOT merged in (1 commit ahead)
    - bump to 0.8.1 [dab43fb] (wmorgan-sup@...; 2 days ago)
[ ] labels-before-subj is NOT merged in (1 commit ahead)
    - put labels before subject in thread index view [790b64d] (marka@...; 4 weeks ago)
{x} origin/enclosed-message-display-tweaks merged in
(x) experiment merged in (only locally)

NOTE: working directory contains modified files

git-wtf shows you:

How your branch relates to the remote repo, if it's a tracking branch.
How your branch relates to non-feature ("version") branches, if it's a feature branch.
How your branch relates to the feature branches, if it's a version branch


[System] You are a helpful assistant.

[User] git-config - Get and set repository or global options  color.push.error

[Assistant] Use customized color for push errors.


[System] You are a helpful assistant.

[User] git-clone - Clone a repository into a new directory  -l  --local

[Assistant]
When the repository to clone from is on a local machine,
this flag bypasses the normal "Git aware" transport
mechanism and clones the repository by making a copy of HEAD and everything under objects and refs directories.
The files under .git/objects/ directory are hardlinked
to save space when possible. If the repository is specified as a local path (e.g., /path/to/repo ),
this is the default, and --local is essentially a no-op.  If the
repository is specified as a URL, then this flag is ignored (and we
never use the local optimizations).  Specifying --no-local will
override the default when /path/to/repo is given, using the regular
Git transport instead. If the repository’s $GIT_DIR/objects has symbolic links or is a
symbolic link, the clone will fail. This is a security measure to
prevent the unintentional copying of files by dereferencing the symbolic
links. NOTE : this operation can race with concurrent modification to the
source repository, similar to running cp -r src dst while modifying src .


[System] You are a helpful assistant.

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

[Assistant] compares the index and the files on the filesystem.


[System] You are a helpful assistant.

[User] git-log - Show commit logs  --alternate-refs

[Assistant]
Pretend as if all objects mentioned as ref tips of alternate
repositories were listed on the command line. An alternate
repository is any repository whose object directory is specified
in objects/info/alternates .  The set of included objects may
be modified by core.alternateRefsCommand , etc. See git-config .


[System] You are a helpful assistant.

[User] git-daemon - A really simple server for Git repositories  syslog

[Assistant] Write to syslog, using the git-daemon identifier.


[System] You are a helpful assistant.

[User]
How to clone/pull a git repository, ignoring LFS?
Is there a way to explicitly ignore all git-lfs files on clone and pull?(besides uninstalling git-lfs which I ended up doing).

In this case git-lfs just contains pre-compiled libs for a platform I don't use... so there is absolutely no use in getting them.

[Assistant]
Two alternatives:
(1) Using the GIT_LFS_SKIP_SMUDGE variable:
GIT_LFS_SKIP_SMUDGE=1 git clone SERVER-REPOSITORY

Obs: for "Windows", use the following two commands:
set GIT_LFS_SKIP_SMUDGE=1
git clone SERVER-REPOSITORY

(2) Configuring the git-lfs smudge:
git config --global filter.lfs.smudge "git-lfs smudge --skip -- %f"
git config --global filter.lfs.process "git-lfs filter-process --skip"

git clone SERVER-REPOSITORY

To undo this configuration, execute:
git config --global filter.lfs.smudge "git-lfs smudge -- %f"
git config --global filter.lfs.process "git-lfs filter-process"


[System] You are a helpful assistant.

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

[Assistant]
Verify that the tip commit of the side branch being merged is
signed with a valid key, i.e. a key that has a valid uid: in the
default trust model, this means the signing key has been signed by
a trusted key.  If the tip commit of the side branch is not signed
with a valid key, the merge is aborted. Only useful when merging.


[System] You are a helpful assistant.

[User]
How to list a subgroup's projects using the GitLab API?

In GitLab you can create subgroups within a group and projects within those subgroups. The GitLab documentation allows you to list the subgroups of a group and the projects of a group, but I cannot find anything about listing projects of a subgroup. Does anyone know the curl command for this, or at least know that it's not supported yet?
I've tried:
curl -s -H 'PRIVATE-TOKEN: xxxxx' https://gitlab.com/api/v4/groups/mygroup/subgroups/mysubgroup/projects
curl -s -H 'PRIVATE-TOKEN: xxxxx' https://gitlab.com/api/v4/subgroups/mysubgroup/projects
and other similar variations with no luck so far.

[Assistant]
Use %2f to specify full path to subgroup:
curl -s https://gitlab.com/api/v4/groups/gitlab-org%2fgitter/projects

See this issue.


[System] You are a helpful assistant.

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

[Assistant] Synonym for --dirstat=cumulative


[System] You are a helpful assistant.

[User]
How do I make git merge's default be --no-ff --no-commit?
Company policy is to use --no-ff for merge commits. I personally like to adjust merge log messages so I use --no-commit. Plus I like to actually compile and test before I let the commit go.
How do I make --no-ff and --no-commit the default for me for all branches?
(and I've learned in the years since asking this, I almost always am happy with the commit, so it is simpler to allow it to commit by default and so long as I amend or otherwise fix things up before doing a push things are all good...)

[Assistant]
Put this in $HOME/.gitconfig:
[merge]
    ff = no
    commit = no

You can use git-config to do this:
  git config --global merge.commit no
  git config --global merge.ff no


[System] You are a helpful assistant.

[User] git-format-patch - Prepare patches for e-mail submission  --summary

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


[System] You are a helpful assistant.

[User]
What is `git push origin master`? Help with git's refs, heads and remotes
I have a question about what git push origin master does:

I know that origin is the remote (aka GitHub)
git push origin master is the same as git push origin master_on_my_machine:master_on_github

I don't know if:

master_on_my_machine is equal to /refs/heads/master
master_of_github is equal to /refs/remotes/origin/master

If it's equal, should it be possible to do
git push origin refs/heads/master:refs/heads/origin/master?
Finally, what I want to do is only type git push and git pull when:

I'm on a master branch
I want to push and pull from a my_test branch on github, only typing git push and git pull.

[Assistant]
Git has two types of branches: local and remote. To use git pull and git push as you'd like, you have to tell your local branch (my_test) which remote branch it's tracking. In typical Git fashion this can be done in both the config file and with commands.
Commands
Make sure you're on your master branch with
1)git checkout master
then create the new branch with
2)git branch --track my_test origin/my_test
and check it out with
3)git checkout my_test.
You can then push and pull without specifying which local and remote.
However if you've already created the branch then you can use the -u switch to tell git's push and pull you'd like to use the specified local and remote branches from now on, like so:
git pull -u my_test origin/my_test
git push -u my_test origin/my_test

Config
The commands to setup remote branch tracking are fairly straight forward but I'm listing the config way as well as I find it easier if I'm setting up a bunch of tracking branches. Using your favourite editor open up your project's .git/config and add the following to the bottom.
[remote "origin"]
    url = [email protected]:username/repo.git
    fetch = +refs/heads/*:refs/remotes/origin/*
[branch "my_test"]
    remote = origin
    merge = refs/heads/my_test

This specifies a remote called origin, in this case a GitHub style one, and then tells the branch my_test to use it as it's remote.
You can find something very similar to this in the config after running the commands above.
Some useful resources:

http://www.kernel.org/pub/software/scm/git/docs/git-branch.html
http://gitready.com/beginner/2009/03/09/remote-tracking-branches.html


[System] You are a helpful assistant.

[User] git-config - Get and set repository or global options  interactive.diffFilter

[Assistant]
When an interactive command (such as git add --patch ) shows
a colorized diff, git will pipe the diff through the shell
command defined by this configuration variable. The command may
mark up the diff further for human consumption, provided that it
retains a one-to-one correspondence with the lines in the
original diff. Defaults to disabled (no filtering).


[System] You are a helpful assistant.

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

[Assistant]
Only the selected commits are shown, plus some to have a
meaningful history.


[System] You are a helpful assistant.

[User] git - the stupid content tracker  gitnamespaces

[Assistant] Git namespaces


[System] You are a helpful assistant.

[User]
When I do "git push", what do the statistics mean? (Total, delta, etc.)
Here is an example:
$ git push -u myserver master
Counting objects: 22, done.
Delta compression using up to 8 threads.
Compressing objects: 100% (14/14), done.
Writing objects: 100% (14/14), 1.89 KiB | 0 bytes/s, done.
Total 14 (delta 10), reused 0 (delta 0)
To myserver.com:git/myrepo.git
   ed46414..0cae272  master -> master
Branch master set up to track remote branch master from myserver.

Basically the only number above that makes any sense to me is the 8 in "using up to 8 threads", because I have a quad-core processor with hyperthreading, therefore I can run 8 threads.
What are there 22 of? Why does it say 22 and then 14, what happened to the other 8? Why does it say 0 bytes/s, given that it did stuff and took finite time? What is "total" and "delta" and "reused"?
Details about the example: The example above is copy-pasted from Terminal on Mac OS X. I manually did a find-replace to substitute in "myrepo" and "myserver.com", everything else is verbatim. The repository has 910 commits, and I made about 3 commits since the prior push. The 3 new commits affected at least 3 files. The repo contains over a thousand files.

[Assistant]
Short answer
This is merely the output of the git command git count-objects -v for the push (the same command is called for output when gc, pull and clone). More info in the man pages : git-count-objects(1).
$ git count-objects -v
...
size: 14 # The "Compressing objects: 100% (14/14)" part (the size in KiB)
in-pack: 22 # The "Counting objects: 22" part (the number of objects)
...

Long answer
Counting objects: 22, done.

This is git 22 internal objects being counted for that specific commit. Pretty much everything in git is an object, and are basically blobs saved in your .git/objects folder under their respective hash.  More info in the man pages : 9.2 Git Internals - Git Objects.
Compressing objects: 100% (14/14), done.

This is git compressing the objects before send. The 14/14 is the progression in KiB of the compression (14 KiB to compress).
Writing objects: 100% (14/14), 1.89 KiB | 0 bytes/s, done.

This is git sending (if remote) and writing the objects. The 1.89 KiB | 0 bytes/s is the progression in KiB and the speed (0 bytes/s when finished).
Total 14 (delta 10), reused 0 (delta 0)

This is the output of the packfile algorithm in git (see 9.4 Git Internals - Packfiles) and is fairly obscure. It basically packs the unused objects, typically older history, in .git/objects/pack. After packing, git checks if it can reuse packs (hence the reused 0 part). The delta 0 part is the gain in KiB from the packing or from the reuse.


[System] You are a helpful assistant.

[User]
How do I safely merge a Git branch into master?
A new branch from master is created, we call it test.
There are several developers who either commit to master or create other branches and later merge into master.
Let's say work on test is taking several days and you want to continuously keep test updated with commits inside master.
I would do git pull origin master from test.
Question 1: Is this the right approach?  Other developers could have easily worked on same files as I have worked btw.

My work on test is done and I am ready to merge it back to master. Here are the two ways I can think of:
A:
git checkout test
git pull origin master
git push origin test
git checkout master
git pull origin test

B:
git checkout test
git pull origin master
git checkout master
git merge test

I am not using --rebase because from my understanding, rebase will get the changes from master and stack mine on top of that hence it could overwrite changes other people made.
Question 2: Which one of these two methods is right?  What is the difference there?
The goal in all of this is to keep my test branch updated with the things happening in master and later I could merge them back into master hoping to keep the timeline as linear as possible.

[Assistant]
How I would do this
git checkout master
git pull origin master
git merge test
git push origin master

If I have a local branch from a remote one, I don't feel comfortable with merging other branches than this one with the remote. Also I would not push my changes, until I'm happy with what I want to push and also I wouldn't push things at all, that are only for me and my local repository. In your description it seems, that test is only for you? So no reason to publish it.
git always tries to respect yours and others changes, and so will --rebase. I don't think I can explain it appropriately, so have a look at the Git book - Rebasing or git-ready: Intro into rebasing for a little description. It's a quite cool feature


[System] You are a helpful assistant.

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

[Assistant]
The name of the remote ref being fetched from, minus its refs/<type>/ prefix. In the case of deletion, the name of
the remote ref is "(none)".


[System] You are a helpful assistant.

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

[Assistant]
The name of the ref (the part after $GIT_DIR/).
For a non-ambiguous short name of the ref append :short .
The option core.warnAmbiguousRefs is used to select the strict
abbreviation mode. If lstrip=<N> ( rstrip=<N> ) is appended, strips <N> slash-separated path components from the front (back) of the refname
(e.g. %(refname:lstrip=2) turns refs/tags/foo into foo and %(refname:rstrip=2) turns refs/tags/foo into refs ).
If <N> is a negative number, strip as many path components as
necessary from the specified end to leave -<N> path components
(e.g. %(refname:lstrip=-2) turns refs/tags/foo into tags/foo and %(refname:rstrip=-1) turns refs/tags/foo into refs ). When the ref does not have
enough components, the result becomes an empty string if
stripping with positive <N>, or it becomes the full refname if
stripping with negative <N>.  Neither is an error. strip can be used as a synonym to lstrip .


[System] You are a helpful assistant.

[User]
Git: "Not currently on any branch." Is there an easy way to get back on a branch, while keeping the changes?
So I've done some work in the repository and when I'm about to commit I realize that I'm not currently on any branch.
This happens a lot when working with submodules and I am able to solve it, but the process is tedious and I've been thinking that there must be an easier way to do this.
Is there an easy way to get back on a branch, while keeping the changes?

[Assistant]
If you have not committed:
git stash
git checkout some-branch
git stash pop

If you have committed and have not changed anything since:
git log --oneline -n1 # this will give you the SHA
git checkout some-branch
git merge ${commit-sha}

If you have committed and then done extra work:
git stash
git log --oneline -n1 # this will give you the SHA
git checkout some-branch
git merge ${commit-sha}
git stash pop


[System] You are a helpful assistant.

[User]
What's the difference between git reflog and log?
The man page says that log shows the commit logs and reflog manages reflog information. What exactly is reflog information and what does it have that the log doesn't? The log seems far more detailed.

[Assistant]
git log shows the current HEAD and its ancestry. That is, it prints the commit HEAD points to, then its parent, its parent, and so on. It traverses back through the repo's ancestry, by recursively looking up each commit's parent.
(In practice, some commits have more than one parent. To see a more representative log, use a command like git log --oneline --graph --decorate.)
git reflog doesn't traverse HEAD's ancestry at all. The reflog is an ordered list of the commits that HEAD has pointed to: it's undo history for your repo. The reflog isn't part of the repo itself (it's stored separately to the commits themselves) and isn't included in pushes, fetches or clones; it's purely local.
Aside: understanding the reflog means you can't really lose data from your repo once it's been committed. If you accidentally reset to an older commit, or rebase wrongly, or any other operation that visually "removes" commits, you can use the reflog to see where you were before and git reset --hard back to that ref to restore your previous state. Remember, refs imply not just the commit but the entire history behind it.


[System] You are a helpful assistant.

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

[Assistant]
When a git push --signed sends a push certificate with a
"nonce" that was issued by a receive-pack serving the same
repository within this many seconds, export the "nonce"
found in the certificate to GIT_PUSH_CERT_NONCE to the
hooks (instead of what the receive-pack asked the sending
side to include).  This may allow writing checks in pre-receive and post-receive a bit easier.  Instead of
checking GIT_PUSH_CERT_NONCE_SLOP environment variable
that records by how many seconds the nonce is stale to
decide if they want to accept the certificate, they only
can check GIT_PUSH_CERT_NONCE_STATUS is OK .


[System] You are a helpful assistant.

[User] git - the stupid content tracker

[Assistant] NAME git - the stupid content tracker


[System] You are a helpful assistant.

[User]
GitHub actions: default branch variable

Is there any smart way to determine the default branch in GitHub actions?
Now I need to write something like:
on:
  push:
    branches:
      - master

is there a way to write something like the code below?
on:
  push:
    branches:
      - $default-branch

I tried to google but found nothing

[Assistant]
I accidentally found a really nice way to solve this. That evalutes to the branch name, e.g. master.
${{ github.event.repository.default_branch }}

Also, found out the hard way that that always() is side-effecting: my job was getting skipped if always() was not called even though the other clause was true.
This works to run a job only when running on default branch
  if: ${{ always() && format('refs/heads/{0}', github.event.repository.default_branch) == github.ref }}


[System] You are a helpful assistant.

[User] git-format-patch - Prepare patches for e-mail submission  --no-ext-diff

[Assistant] Disallow external diff drivers.


[System] You are a helpful assistant.

[User]
How to track directories but not their files with Git?
I've recently started using Git and am having trouble with just one thing. How can I track directories without tracking their contents?
For example the site I'm working on allows uploads. I want to track the uploads directory so that it is created when branching, etc. but obviously not the files within it (test files whilst in develop branch or the real files in master).
In my .gitignore I have the following:
uploads/*.*
Have also tried (which ignores the whole directory):
uploads/
This directory may also contain sub directories (uploads/thumbs/ uploads/videos/) I would like to be able to track these but not their files.
Is this possible with Git? I've searched everywhere without finding an answer.

[Assistant]
Git doesn't track directories, it tracks files, so to acheive this you need to track at least one file. So assuming your .gitignore file looks something like this:
upload/*

You can do this:
$ touch upload/.placeholder
$ git add -f upload/.placeholder

If you forget the -f you'll see:

$ git add upload/.placeholder
The following paths are ignored by one of your .gitignore files:
upload
Use -f if you really want to add them.
fatal: no files added

Then when you do git status you'll see:

# On branch master
#
# Initial commit
#
# Changes to be committed:
#   (use "git rm --cached ..." to unstage)
#
#   new file:   upload/.placeholder
#

Obviously you can then do:
$ touch upload/images/.placeholder
$ git add -f upload/images/.placeholder


[System] You are a helpful assistant.

[User] git - the stupid content tracker  GIT_EXTERNAL_DIFF

[Assistant]
When the environment variable GIT_EXTERNAL_DIFF is set, the
program named by it is called to generate diffs, and Git
does not use its builtin diff machinery.
For a path that is added, removed, or modified, GIT_EXTERNAL_DIFF is called with 7 parameters: path old-file old-hex old-mode new-file new-hex new-mode where:


[System] You are a helpful assistant.

[User] git-log - Show commit logs  -p  -u  --patch

[Assistant] Generate patch (see Generating patch text with -p ).


[System] You are a helpful assistant.

[User]
How to clone git repository from its zip

I'm trying to clone a remote repository on github, but it is big and my connection doesn't seem to be stable enough, so I can't clone it successfully.
But I have successfully downloaded the .zip of the repository.
Is there a way to use this zip as it was created by git clone, so I can push, pull etc..?

[Assistant]
A related post here provides the information needed to grab the .git directory and simplify the answer that umläute provided:

Grab the .git directory by cloning a bare repository
$ mkdir repo
$ git clone --bare http://github/user/repo repo

Make the .git directory and move the cloned files
$ mkdir repo/.git
$ mv repo/* repo/.git

Unzip the repository
$ unzip repo.zip

Re-initialize the repository
$ cd repo
$ git init

Verify you're sync'ed
$ git pull

Reset the HEAD to clean up the status
$ git reset HEAD

Here's the log for the repo ... repo location - http://github.com/udacity/fullstack-nanodegree-vm
$ git log
commit ebcbda650bc81d7f4856f5314a0689cea5b43086
Merge: 574774b b5b787e
Author: Karl Krueger <[email protected]>
Date:   Tue Apr 7 11:39:54 2015 -0700`

        Merge pull request #3 from pmallory/sharedDirAlert

        Add a login alert to explain how to access Vagrant's shared directory

commit b5b787efdb1ecec0c3c9c7f9c0fd4732f984fcb3
Author: Philip Mallory <[email protected]>
Date:   Mon Apr 6 15:40:32 2015 -0700`

       move the alert into the motd

commit b8012f33c86b0d19fc4c2b972af092e88d00978f
Author: Philip Mallory <[email protected]>
Date:   Mon Apr 6 14:32:01 2015 -0700`

       Add a login alert to explain how to access Vagrant's shared directory

commit 574774ba29ccd661154431d5600240f090440c37
Author: Lorenzo Brown <[email protected]>
Date:   Wed Mar 11 14:08:02 2015 -0700`

       Update pg_config.sh

       Added installs for Auth&Auth

commit 88fc5537b1a0017a1d76af4587a22412473809a4
Author: Lorenzo Brown <[email protected]>
Date:   Wed Mar 4 13:00:25 2015 -0800`

       Update and rename vagrant to vagrant/catalog/README.txt

commit f978cdc14c62b7295d8da1a95452faaa1bd108b8
Author: Lorenzo Brown <[email protected]>
Date:   Wed Feb 4 11:06:03 2015 -0800`

       Update Vagrantfile

       switched to port forwarding on 8080

commit d6a3a26578ef3c6d01d28abca76d817938892c7f
Author: Lorenzo Brown <[email protected]>
Date:   Tue Feb 3 14:52:34 2015 -0800`

       Update Vagrantfile

       Added:

       config.vm.network "forwarded_port", guest: 80, host: 8080
       config.vm.network "forwarded_port", guest: 5000, host: 5000

       FSF uses these two ports for lessons 2 & 3 respectively.

commit 752a79e408c7328ef7f1766d1b97bb468ffed90a
Author: Mike Wales <[email protected]>
Date:   Mon Feb 2 11:21:29 2015 -0800`

       Removed .vagrant directory

commit 5af9d19adf9ab19b1d886f6cc78e556f864b42dd
Author: Mike Wales <[email protected]>
Date:   Mon Feb 2 11:16:45 2015 -0800`

       Initial commit.


[System] You are a helpful assistant.

[User] git - the stupid content tracker  GIT_REF_PARANOIA

[Assistant]
If this Boolean environment variable is set to false, ignore broken or badly named refs when iterating
over lists of refs. Normally Git will try to include any such
refs, which may cause some operations to fail. This is usually
preferable, as potentially destructive operations (e.g., git-prune ) are better off aborting rather than
ignoring broken refs (and thus considering the history they
point to as not worth saving). The default value is 1 (i.e.,
be paranoid about detecting and aborting all operations). You
should not normally need to set this to 0 , but it may be
useful when trying to salvage data from a corrupted repository.


[System] You are a helpful assistant.

[User]
Is there a Github clone in PHP that I can run on my own server? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.

Closed 11 years ago.

I know there are plenty of ways to run git on my server, but I quite like the functionality of git with repo browsing - the fact that i can look at previous versions in the web interface.
Now was I able to, I'd use github, but the problem is our source control rules are very strict and we aren't allowed to put files on other servers, even if they are encrypted.
Is there a script that allows us to run a github like interface, or rather one that allows me to browse the revision history of the git project through a web interface?
I'm running a LAMP server, but would consider alternate languages like python, perl etc should nothing in php be available.
interested in both paid and open source softwares

[Assistant]
The webapp behind Gitorious is open-source. You can have an interface exactly like it from your web server. It doesn't have all the Github bells and whistles but it has source browsing, revision history, commits, etc.
It's rails, which might not be optimal for you, but it's also free :-)


[System] You are a helpful assistant.

[User] git-cat-file - Provide contents or details of repository objects  objectsize

[Assistant] The size, in bytes, of the object (the same as cat-file -s reports).


[System] You are a helpful assistant.

[User]
TortoiseGit-git did not exit cleanly (exit code 1)
I got this message when i tried to create repository by using Git clone.
git did not exit cleanly (exit code 1)

How to fix this?

[Assistant]
Try these two commands in git bash:
1) git gc --force
2) git fetch -p


[System] You are a helpful assistant.

[User]
Git-ignore certain files in sub-directories, but not all
I have a structure similar to the following:
/root/
/root/data/
/root/data/script.php
/root/data/some.json
/root/data/feature/one.json
/root/data/feature/two.json
/root/data/other-feature/one.json
/root/data/other-feature/important-script.php

I'd like git to ignore any .json files under the '/data/...' path, but '/data/' sometimes contains sub-directories.
My understanding is that a simple data/*.json in gitignore will only match one directory, as the * doesn't match /, as stated at http://git-scm.com/docs/gitignore, "Pattern Format", bullet #6:

Otherwise, git treats the pattern as a shell glob suitable for consumption by fnmatch(3) with the FNM_PATHNAME flag: wildcards in the pattern will not match a / in the pathname. For example, "Documentation/*.html" matches "Documentation/git.html" but not "Documentation/ppc/ppc.html" or "tools/perf/Documentation/perf.html".

Is there a simple way to do this, or do I need to actively add gitignore files in each sub-directory, explicitly?

[Assistant]
I've written a post about such problem recently. See here.
Basically what you need is to put one .gitignore with *.json in the /data/ directory.
UPD: Since git 1.8.4 (1.8.2 if you're using msysgit) it is possible to use double-star patterns, like /data/**/*.json


[System] You are a helpful assistant.

[User]
How to remove untracked files in Git? [duplicate]
This question already has answers here:

How do I remove local (untracked) files from the current Git working tree?

                                (42 answers)

Closed last year.

I'm working on a branch, say "experimental", which I branch out from my master branch. Then, I generate a user model in the experimental branch, but don't add them to the index yet.
What do I have to do if I want to discard all the changes of the files recently added in my experimental branch? The untracked files are listed as below:
$ git status
 On branch new_chick
 Untracked files:
   (use "git add <file>..." to include in what will be committed)

       .project
       app/models/user.rb
       db/migrate/
       test/fixtures/users.yml
       test/unit/user_test.rb

I tried to run "git reset --hard" in the hope to undo all those changes, but all the files mentioned above still show up.

[Assistant]
To remove untracked files / directories do:
git clean -fdx

-f - force
-d - directories too
-x - remove ignored files too ( don't use this if you don't want to remove ignored files)

Use with Caution!
These commands can permanently delete arbitrary files, that you havn't thought of at first. Please double check and read all the comments below this answer and the --help section, etc., so to know all details to fine-tune your commands and surely get the expected result.


[System] You are a helpful assistant.

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

[Assistant] tree hash


[System] You are a helpful assistant.

[User]
How do I "un-revert" a reverted Git commit?
Given a change that has been committed using commit, and then reverted using revert, what is the best way to then undo that revert?
Ideally, this should be done with a new commit, so as to not re-write history.

[Assistant]
git cherry-pick <original commit sha>
Will make a copy of the original commit, essentially re-applying the commit
Reverting the revert will do the same thing, with a messier commit message:
git revert <commit sha of the revert>
Either of these ways will allow you to git push without overwriting history, because it creates a new commit after the revert.
When typing the commit sha, you typically only need the first 5 or 6 characters:
git cherry-pick 6bfabc


[System] You are a helpful assistant.

[User]
Git ignore file for Xcode projects
Which files should I include in .gitignore when using Git in conjunction with Xcode?

[Assistant]
I was previously using the top-voted answer, but it needs a bit of cleanup, so here it is redone for Xcode 4, with some improvements.
I've researched every file in this list, but several of them do not exist in Apple's official Xcode documentation, so I had to go on Apple mailing lists.
Apple continues to add undocumented files, potentially corrupting our live projects. This IMHO is unacceptable, and I've now started logging bugs against it each time they do so. I know they don't care, but maybe it'll shame one of them into treating developers more fairly.

If you need to customize, here's a gist you can fork: https://gist.github.com/3786883

#########################
# .gitignore file for Xcode4 and Xcode5 Source projects
#
# Apple bugs, waiting for Apple to fix/respond:
#
#    15564624 - what does the xccheckout file in Xcode5 do? Where's the documentation?
#
# Version 2.6
# For latest version, see: http://stackoverflow.com/questions/49478/git-ignore-file-for-xcode-projects
#
# 2015 updates:
# - Fixed typo in "xccheckout" line - thanks to @lyck for pointing it out!
# - Fixed the .idea optional ignore. Thanks to @hashier for pointing this out
# - Finally added "xccheckout" to the ignore. Apple still refuses to answer support requests about this, but in practice it seems you should ignore it.
# - minor tweaks from Jona and Coeur (slightly more precise xc* filtering/names)
# 2014 updates:
# - appended non-standard items DISABLED by default (uncomment if you use those tools)
# - removed the edit that an SO.com moderator made without bothering to ask me
# - researched CocoaPods .lock more carefully, thanks to Gokhan Celiker
# 2013 updates:
# - fixed the broken "save personal Schemes"
# - added line-by-line explanations for EVERYTHING (some were missing)
#
# NB: if you are storing "built" products, this WILL NOT WORK,
# and you should use a different .gitignore (or none at all)
# This file is for SOURCE projects, where there are many extra
# files that we want to exclude
#
#########################

#####
# OS X temporary files that should never be committed
#
# c.f. http://www.westwind.com/reference/os-x/invisibles.html

.DS_Store

# c.f. http://www.westwind.com/reference/os-x/invisibles.html

.Trashes

# c.f. http://www.westwind.com/reference/os-x/invisibles.html

*.swp

#
# *.lock - this is used and abused by many editors for many different things.
#    For the main ones I use (e.g. Eclipse), it should be excluded
#    from source-control, but YMMV.
#   (lock files are usually local-only file-synchronization on the local FS that should NOT go in git)
# c.f. the "OPTIONAL" section at bottom though, for tool-specific variations!
#
# In particular, if you're using CocoaPods, you'll want to comment-out this line:
*.lock

#
# profile - REMOVED temporarily (on double-checking, I can't find it in OS X docs?)
#profile

####
# Xcode temporary files that should never be committed
#
# NB: NIB/XIB files still exist even on Storyboard projects, so we want this...

*~.nib

####
# Xcode build files -
#
# NB: slash on the end, so we only remove the FOLDER, not any files that were badly named "DerivedData"

DerivedData/

# NB: slash on the end, so we only remove the FOLDER, not any files that were badly named "build"

build/

#####
# Xcode private settings (window sizes, bookmarks, breakpoints, custom executables, smart groups)
#
# This is complicated:
#
# SOMETIMES you need to put this file in version control.
# Apple designed it poorly - if you use "custom executables", they are
#  saved in this file.
# 99% of projects do NOT use those, so they do NOT want to version control this file.
#  ..but if you're in the 1%, comment out the line "*.pbxuser"

# .pbxuser: http://lists.apple.com/archives/xcode-users/2004/Jan/msg00193.html

*.pbxuser

# .mode1v3: http://lists.apple.com/archives/xcode-users/2007/Oct/msg00465.html

*.mode1v3

# .mode2v3: http://lists.apple.com/archives/xcode-users/2007/Oct/msg00465.html

*.mode2v3

# .perspectivev3: http://stackoverflow.com/questions/5223297/xcode-projects-what-is-a-perspectivev3-file

*.perspectivev3

#    NB: also, whitelist the default ones, some projects need to use these
!default.pbxuser
!default.mode1v3
!default.mode2v3
!default.perspectivev3

####
# Xcode 4 - semi-personal settings
#
# Apple Shared data that Apple put in the wrong folder
# c.f. http://stackoverflow.com/a/19260712/153422
#     FROM ANSWER: Apple says "don't ignore it"
#     FROM COMMENTS: Apple is wrong; Apple code is too buggy to trust; there are no known negative side-effects to ignoring Apple's unofficial advice and instead doing the thing that actively fixes bugs in Xcode
# Up to you, but ... current advice: ignore it.
*.xccheckout

#
#
# OPTION 1: ---------------------------------
#     throw away ALL personal settings (including custom schemes!
#     - unless they are "shared")
# As per build/ and DerivedData/, this ought to have a trailing slash
#
# NB: this is exclusive with OPTION 2 below
xcuserdata/

# OPTION 2: ---------------------------------
#     get rid of ALL personal settings, but KEEP SOME OF THEM
#     - NB: you must manually uncomment the bits you want to keep
#
# NB: this *requires* git v1.8.2 or above; you may need to upgrade to latest OS X,
#    or manually install git over the top of the OS X version
# NB: this is exclusive with OPTION 1 above
#
#xcuserdata/**/*

#     (requires option 2 above): Personal Schemes
#
#!xcuserdata/**/xcschemes/*

####
# Xcode 4 workspaces - more detailed
#
# Workspaces are important! They are a core feature of Xcode - don't exclude them :)
#
# Workspace layout is quite spammy. For reference:
#
# /(root)/
#   /(project-name).xcodeproj/
#     project.pbxproj
#     /project.xcworkspace/
#       contents.xcworkspacedata
#       /xcuserdata/
#         /(your name)/xcuserdatad/
#           UserInterfaceState.xcuserstate
#     /xcshareddata/
#       /xcschemes/
#         (shared scheme name).xcscheme
#     /xcuserdata/
#       /(your name)/xcuserdatad/
#         (private scheme).xcscheme
#         xcschememanagement.plist
#
#

####
# Xcode 4 - Deprecated classes
#
# Allegedly, if you manually "deprecate" your classes, they get moved here.
#
# We're using source-control, so this is a "feature" that we do not want!

*.moved-aside

####
# OPTIONAL: Some well-known tools that people use side-by-side with Xcode / iOS development
#
# NB: I'd rather not include these here, but gitignore's design is weak and doesn't allow
#     modular gitignore: you have to put EVERYTHING in one file.
#
# COCOAPODS:
#
# c.f. http://guides.cocoapods.org/using/using-cocoapods.html#what-is-a-podfilelock
# c.f. http://guides.cocoapods.org/using/using-cocoapods.html#should-i-ignore-the-pods-directory-in-source-control
#
#!Podfile.lock
#
# RUBY:
#
# c.f. http://yehudakatz.com/2010/12/16/clarifying-the-roles-of-the-gemspec-and-gemfile/
#
#!Gemfile.lock
#
# IDEA:
#
# c.f. https://www.jetbrains.com/objc/help/managing-projects-under-version-control.html?search=workspace.xml
#
#.idea/workspace.xml
#
# TEXTMATE:
#
# -- UNVERIFIED: c.f. http://stackoverflow.com/a/50283/153422
#
#tm_build_errors

####
# UNKNOWN: recommended by others, but I can't discover what these files are
#


[System] You are a helpful assistant.

[User] git-diff - Show changes between commits, commit and working tree, etc  --ignore-space-at-eol

[Assistant] Ignore changes in whitespace at EOL.


[System] You are a helpful assistant.

[User] git-switch - Switch branches

[Assistant] NAME git-switch - Switch branches


[System] You are a helpful assistant.

[User] git-daemon - A really simple server for Git repositories  --reuseaddr

[Assistant]
Use SO_REUSEADDR when binding the listening socket.
This allows the server to restart without waiting for
old connections to time out.


[System] You are a helpful assistant.

[User]
Redefine tab as 4 spaces in Gitlab CE

See this huge identations is painful (for me). Is there a way to set tab size to 4 spaces.
This picture is taken from local Gitlab CE server with minimal customization. I think tabsize 8 spaces is default.

[Assistant] Go to Settings → Preferences → Behavior and set Tab width.


[System] You are a helpful assistant.

[User]
How to create hierarchical wiki in git lab

How to create a hierarchical wiki pages in GitLab
Home
    <Wiki Page 1>
    <Wiki Page 2>
    <Wiki Page 3>
       <Wiki Page 3 - 1>
       <Wiki Page 3 - 2>
    <Wiki Page 4>

[Assistant]
You can specify wiki page path in page title field, for example section/section/wiki page.
See https://docs.gitlab.com/ee/user/project/wiki/#move-a-wiki-page for details.


[System] You are a helpful assistant.

[User]
Set up git to pull and push all branches
I'd like to push and pull all the branches by default, including the newly created ones.
Is there a setting that I can define for it?
Otherwise, when I add a new branch, locally and I want to pull it from the server, what is the simplest way to do it?
I created a new branch with the same name and tried to pull but it doesn't work. Asks me for all the remote config of the branch. How do I set it.

[Assistant]
The simplest way is to do:
git push --all origin

This will push tags and branches.


[System] You are a helpful assistant.

[User]
Opposite of git branch --set-upstream
I would like to stop tracking certain branches.
I set up tracking using git branch --set-upstream foo origin/foo.
How do I undo this?

[Assistant]
In git 1.8, which will be released shortly, you'll be able to do:
git branch --unset-upstream

However, for the moment you would have to do as manojlds suggests, and use two git config --unset commands.


[System] You are a helpful assistant.

[User]
index file smaller than expected
This morning, I started getting this error from git:

fatal: index file smaller than expected
fatal: git status --porcelain failed

Any idea of what is happening and how to solve it?

[Assistant]
The index file has become corrupted, but it is easily re-creatable. Just remove it...
rm .git/index

Then you can re-add the files you're trying to stage.


[System] You are a helpful assistant.

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

[Assistant]
Branch description, can be edited with git branch --edit-description . Branch description is
automatically added to the format-patch cover letter or
request-pull summary.


[System] You are a helpful assistant.

[User]
How to close off a Git Branch?

I'm starting out using Git + GitHub.
In our distributed team, each member is creating their own branch for each issue/requirement they are allocated.

git branch Issue#1     <-- create this branch
git checkout issue#1   <-- switch over to this branch

now code code, commit, code, commit, etc...
then pull request, code-fixup, commit, code, commit .. etc.
and finally the pull request is accepted.
But, now what?
Does the person who created the branch on their local dev machine need to close off the branch? A suggestion was for the dev person to delete the branch ( ... -D ...) and then do a pull / refresh of the master .. which then will get all their branch code.

[Assistant]
We request that the developer asking for the pull request state that they would like the branch deleted. Most of the time this is the case. There are times when a branch is needed (e.g. copying the changes to another release branch).
My fingers have memorized our process:
git checkout <feature-branch>
git pull
git checkout <release-branch>
git pull
git merge --no-ff <feature-branch>
git push
git tag -a branch-<feature-branch> -m "Merge <feature-branch> into <release-branch>"
git push --tags
git branch -d <feature-branch>
git push origin :<feature-branch>

A branch is for work. A tag marks a place in time. By tagging each branch merge we can resurrect a branch if that is needed. The branch tags have been used several times to review changes.


[System] You are a helpful assistant.

[User]
How to disable osxkeychain as credential helper in git config?
I need to disable the credential helper for OS X: git credential-osxkeychain
It is disabled both in the global config file and in the local one, in fact it has never ben enabled. Still, it keeps memorizing my github login details.
I'm on a laptop, so I don't want automatic passwordless access to my repos.
I will use ssh keys. This is a new computer, and the whole system setup is still a work in progress.
For now I used the https repo refs, and the credential helper keeps kicking in.
These are my conf files:

git config --edit =>
[core]
    repositoryformatversion = 0
    filemode = true
    bare = false
    logallrefupdates = true
    ignorecase = true
    precomposeunicode = false
[remote "origin"]
    url = https://github.com/user/repo.git
    fetch = +refs/heads/*:refs/remotes/origin/*
[branch "master"]
    remote = origin
    merge = refs/heads/master
[branch "develop"]
    remote = origin
    merge = refs/heads/develop
[branch "deploy"]
    remote = origin
    merge = refs/heads/deploy

git config --global --edit =>
[user]
    email = ****************
    name = tom
[color]
    ui = true
[core]
    editor = subl -w
[github]
    user = tompave
[merge]
    conflictstyle = diff3
[push]
    default = simple

Also, running git config --global credential.helper returns nothing (and that's right).
However, running git config credential.helper returns osxkeychain!
How is it possible? I can't see it in the local config file, where is it set?
I tried to set it up locally to see what would happen, and it did appear in the repodir/.git/config. Then I deleted the entry... but the helper is still here and active.
I can clearly see its entry in OS X keychain.
I can delete it, and then git will ask for the password again... but as soon as I type it (let's say, for a git fetch), the entry in keychain is restored.

[Assistant]
To help track down the setting, I'd try to use:
git config --local credential.helper
git config --global credential.helper
git config --system credential.helper

The first one checks the local repo config, the second is your ~/.gitconfig, and the third is based on where git is installed.  Depending on which one comes back showing the credential helper, you can try using the equivalent --unset option:
git config --local --unset credential.helper
git config --global --unset credential.helper
git config --system --unset credential.helper

The last one may not work if you don't have proper permissions.  So you may need to run the last one under sudo for it to work correctly.  FWIW, you may have installed for the pre-built git images for Mac OS X.  If you cat /usr/local/git/etc/gitconfig (or /usr/local/etc/gitconfig if you installed git via Homebrew or a building locally), you'll see that it does set up the credential helper for you.  So the last command above would help fix that problem.


[System] You are a helpful assistant.

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

[Assistant] show the key used to sign a signed commit


[System] You are a helpful assistant.

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

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


[System] You are a helpful assistant.

[User] git-bundle - Move objects and refs by archive  [<refname>…]

[Assistant]
A list of references used to limit the references reported as
available. This is principally of use to git fetch , which
expects to receive only those references asked for and not
necessarily everything in the pack (in this case, git bundle acts
like git fetch-pack ).


[System] You are a helpful assistant.

[User]
What are commit-ish and tree-ish in Git?
The Question
What are specific examples of commit-ish and tree-ish in Git?
The Stack Overflow question "What does tree-ish mean in git?" deals
with tree-ish specifically, but I want to understand more about both.
Background
Usages in Documentation
The Git documentation makes several references to "commit-ish" and
"tree-ish". For example, if you're examining the Git source code:
$ git grep --files-with-matches --extended-regexp "commit(-)*ish"
config.txt
git-describe.txt
git-fast-import.txt
git-name-rev.txt
git-push.txt
git-rebase.txt
git-rev-parse.txt
git.txt
gitcli.txt
glossary-content.txt
howto/revert-branch-rebase.txt
revisions.txt

and
$ git grep --files-with-matches --extended-regexp "tree(-)*ish" | \
$ grep --invert-match RelNotes
diff-format.txt
diff-generate-patch.txt
git-archive.txt
git-cat-file.txt
git-checkout.txt
git-diff-index.txt
git-diff-tree.txt
git-ls-files.txt
git-ls-tree.txt
git-merge-tree.txt
git-read-tree.txt
git-reset.txt
git-svn.txt
git.txt
gitcli.txt
gittutorial-2.txt
glossary-content.txt
revisions.txt

Definitions
The Git documentation defines what "commit-ish" and "tree-ish" are:

<tree>

Indicates a tree object name.
<commit>

Indicates a commit object name.
<tree-ish>

Indicates a tree, commit or tag object name. A command that takes a <tree-ish>
  argument ultimately wants to operate on a <tree> object but automatically
  dereferences <commit> and <tag> objects that point at a <tree>.
<commit-ish>

Indicates a commit or tag object name. A command that takes a <commit-ish>
  argument ultimately wants to operate on a <commit> object but automatically
  dereferences <tag> objects that point at a <commit>.

The Documentation isn't Clear Enough
Even though the documentation above defines what "commit-ish" and "tree-ish" are,
I still find it to be too vague and unclear.
What are specific examples of "commit-ish" and "tree-ish", and how are they
different from each other?

[Assistant]
The Short Answer (TL;DR)
Here's a complete list of commit-ish and tree-ish identifiers (from the Git
revisions documentation):
----------------------------------------------------------------------
|    Commit-ish/Tree-ish    |                Examples
----------------------------------------------------------------------
|  1. <sha1>                | dae86e1950b1277e545cee180551750029cfe735
|  2. <describeOutput>      | v1.7.4.2-679-g3bee7fb
|  3. <refname>             | master, heads/master, refs/heads/master
|  4. <refname>@{<date>}    | master@{yesterday}, HEAD@{5 minutes ago}
|  5. <refname>@{<n>}       | master@{1}
|  6. @{<n>}                | @{1}
|  7. @{-<n>}               | @{-1}
|  8. <refname>@{upstream}  | master@{upstream}, @{u}
|  9. <rev>^                | HEAD^, v1.5.1^0
| 10. <rev>~<n>             | master~3
| 11. <rev>^{<type>}        | v0.99.8^{commit}
| 12. <rev>^{}              | v0.99.8^{}
| 13. <rev>^{/<text>}       | HEAD^{/fix nasty bug}
| 14. :/<text>              | :/fix nasty bug
----------------------------------------------------------------------
|       Tree-ish only       |                Examples
----------------------------------------------------------------------
| 15. <rev>:<path>          | HEAD:README.txt, master:sub-directory/
----------------------------------------------------------------------
|         Tree-ish?         |                Examples
----------------------------------------------------------------------
| 16. :<n>:<path>           | :0:README, :README
----------------------------------------------------------------------

Identifiers #1-14 are all "commit-ish", because they all lead to commits, but
because commits also point to directory trees, they all ultimately lead to
(sub)directory tree objects, and can therefore also be used as "tree-ish".
#15 can also be used as tree-ish when it refers to a (sub)directory, but it
can also be used to identify specific files. When it refers to files, I'm not
sure if it's still considered "tree-ish", or if acts more like "blob-ish" (Git
refers to files as "blobs").
The Long Answer
Commits and Directory Trees in Git
At its lowest levels, Git keeps track of source code using four fundamental
objects:

Annotated tags, which point to commits.
Commits, which point to the root directory tree of your project.
Trees, which are directories and subdirectories.
Blobs, which are files.

Each of these objects has its own sha1 hash ID, since Linus Torvalds designed
Git like an content- addressable filesystem, i.e. files can be retrieved
based on their content (sha1 IDs are generated from file content). The Pro Git
book gives this example diagram:

Commit-ish vs Tree-ish
Many Git commands can accept special identifiers for commits and (sub)directory
trees:

"Commit-ish" are identifiers that ultimately lead to a commit object. For example,
tag -> commit
"Tree-ish" are identifiers that ultimately lead to tree (i.e. directory) objects.
tag -> commit -> project-root-directory

Because commit objects always point to a directory tree object (the root
directory of your project), any identifier that is "commit-ish" is, by
definition, also "tree-ish". In other words, any identifier that leads to a
commit object can also be used to lead to a (sub)directory tree object.
But since directory tree objects never point to commits in Git's versioning
system, not every identifier that points to a (sub)directory tree can also be
used to point to a commit. In other words, the set of "commit-ish" identifiers
is a strict subset of the set of "tree-ish" identifiers.
The set of tree-ish identifiers that cannot be used as commit-ish are

<rev>:<path>, which leads directly to directory trees, not commit
objects. For example, HEAD:subdirectory.
Sha1 identifiers of directory tree objects.


[System] You are a helpful assistant.

[User] git-worktree - Manage multiple working trees  -d  --detach

[Assistant]
With add , detach HEAD in the new worktree. See "DETACHED HEAD"
in git-checkout .


[System] You are a helpful assistant.

[User]
Show which git tag you are on?
I'm having trouble finding out which tag is currently checked out.
When I do:
git checkout tag1
git branch

I can't seem to find out which tag I'm on. It only logs:
* (no branch)
master

Is it possible to find out which tags are checked out? In the above example, this would be tag1.

[Assistant]
Edit
Jakub Narębski has more git-fu. The following much simpler command works perfectly:
git describe --tags

(Or without the --tags if you have checked out an annotated tag. My tag is lightweight, so I need the --tags.)
Original answer
git describe --exact-match --tags $(git log -n1 --pretty='%h')

Someone with more git-fu may have a more elegant solution...
This leverages the fact that git-log reports the log starting from what you've checked out. %h prints the abbreviated hash. Then git describe --exact-match --tags finds the tag (lightweight or annotated) that exactly matches that commit.
The $() syntax above assumes you're using bash or similar.


[System] You are a helpful assistant.

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

[Assistant]
ref name given on the command line by which the commit was reached
(like git log --source ), only works with git log


[System] You are a helpful assistant.

[User]
Clone only one branch [duplicate]

This question already has answers here:

How do I clone a single branch in Git?

                                (27 answers)

Closed 8 years ago.

I would like to know how I could clone only one branch instead of cloning the whole Git repository.

[Assistant]
From the announcement Git 1.7.10 (April 2012):

git clone learned --single-branch option to limit cloning to a single branch (surprise!); tags that do not point into the history of the branch are not fetched.

Git actually allows you to clone only one branch, for example:
git clone -b mybranch --single-branch git://sub.domain.com/repo.git

Note: Also you can add another single branch or "undo" this action.


[System] You are a helpful assistant.

[User]
Replace remote tag with Git
I have some tags on my "origin" repository. Then I realized I needed to add some changes on one of the tags, and push them back on my repository.
Is there a way I can push an existing tag to the repository in one time, or should I delete the tag before ?

[Assistant]
This should not be the practice, though you can delete the tag and push the change to the remote repo.
git tag -d tag1
git push origin :refs/tags/tag1


[System] You are a helpful assistant.

[User]
How can I use a pdf file as the readme in my github repo?

I have a pdf file generated by latex which has many equations and what not.  I want to use this pdf as the readme.md file in my github repo.  How can I do this?
Alternatively, is it possible to directly integrate the tex file in github and use that as a readme instead of the pdf version? Does github allow any integration with latex syntax as does gmail for example?

[Assistant]
You cannot import PDF as Readme, but I also don't see the point as it support the wonderful MD Language which can be seen easily with any device (also mobile).
I have fixed the equations problem by using images. There is a nice website for that: http://mathurl.com/
Just type your latex equation and click "Make Math url" (bottom left button), the copy paste the image link (in red).
I have used it in the wiki of github (but it should work the same with readme.md): https://github.com/scholi/pySPM/wiki/Mass-calibration
Enjoy!


[System] You are a helpful assistant.

[User]
Setting git parent pointer to a different parent
If I have a commit in the past that points to one parent, but I want to change the parent that it points to, how would I go about doing that?

[Assistant]
Using git rebase. It's the generic "take commit(s) and plop it/them on a different parent (base)" command in Git.
Some things to know, however:

Since commit SHAs involve their parents, when you change the parent of a given commit, its SHA will change - as will the SHAs of all commits which come after it (more recent than it) in the line of development.
If you're working with other people, and you've already pushed the commit in question public to where they've pulled it, modifying the commit is probably a Bad Idea™. This is due to #1, and thus the resulting confusion the other users' repositories will encounter when trying to figure out what happened due to your SHAs no longer matching theirs for the "same" commits. (See the "RECOVERING FROM UPSTREAM REBASE" section of the linked man page for details.)

That said, if you're currently on a branch with some commits that you want to move to a new parent, it'd look something like this:
git rebase --onto <new-parent> <old-parent>

That will move everything after <old-parent> in the current branch to sit on top of <new-parent> instead.


[System] You are a helpful assistant.

[User] git - the stupid content tracker  gitsubmodules

[Assistant] Mounting one repository inside another


[System] You are a helpful assistant.

[User]
install private npm package in gitlab pipelines

If one needs to install private repositories with npm the environment variable NPM_TOKEN needs to be set.
NPM_TOKEN=00000000-0000-0000-0000-000000000000

My build stage in gitlab pipelines needs to install a private repository. Thus I put this NPM_TOKEN secret variable in my gitlab pipeline settings.
My current gitlab-ci configuration :
image: x/node

build_job:
  script:
  - printenv NPM_TOKEN
  - npm i @x/test

The docker image is one that I made it just sets a .npmrc file:
FROM node:latest
COPY .npmrc .

where I have .npmrc in the same directory:
//registry.npmjs.org/:_authToken=${NPM_TOKEN}

I've tried the docker image by:
 run -it myimage bash
 export NPM_TOKEN=...
 npm i @x/test

That works, the private package is installed.
However on gitlab pipelines it does not find the package (404). When the job runs I can clearly see the NPM_TOKEN env variable being printed. So I don't know what's up.

[Assistant]
I changed gitlab-ci to this:
image: dasnoo/node

build_job:
  script:
  - printenv NPM_TOKEN
  - npm config set //registry.npmjs.org/:_authToken ${NPM_TOKEN}
  - npm i @dasnoo/testpriv

and it works. not sre why I had to do that though


[System] You are a helpful assistant.

[User] gitsubmodules - Mounting one repository inside another

[Assistant]
Workflow for a third party library # Add a submodule
git submodule add <URL> <path> # Occasionally update the submodule to a new version:
git -C <path> checkout <new-version>
git add <path>
git commit -m "update submodule to new version" # See the list of submodules in a superproject
git submodule status # See FORMS on removing submodules


[System] You are a helpful assistant.

[User] git-diff - Show changes between commits, commit and working tree, etc  --ignore-cr-at-eol

[Assistant] Ignore carriage-return at the end of line when doing a comparison.


[System] You are a helpful assistant.

[User]
GitHub: invalid username or password

I have a project hosted on GitHub. I fail when trying to push my modifications on the master. I always get the following error message
Password for 'https://[email protected]':
remote: Invalid username or password.
fatal: Authentication failed for 'https://[email protected]/eurydyce/MDANSE.git/'

However, setting my ssh key to github seems ok. Indeed, when I do a ssh -T [email protected] I get
Hi eurydyce! You've successfully authenticated, but GitHub does not provide shell access.

Which seems to indicate that everything is OK from that side (eurydyce being my github username). I strictly followed the instructions given on github and the recommendations of many stack discussion but no way. Would you have any idea of what I may have done wrong?

[Assistant]
After enabling Two Factor Authentication (2FA), you may see something like this when attempting to use git clone, git fetch, git pull or git push:
$ git push origin master
Username for 'https://github.com': your_user_name
Password for 'https://[email protected]':
remote: Invalid username or password.
fatal: Authentication failed for 'https://github.com/your_user_name/repo_name.git/'

Why this is happening
From the GitHub Help documentation:

After 2FA is enabled you will need to enter a personal access token instead of a 2FA code and your GitHub password.
...
For example, when you access a repository using Git on the command line using commands like git clone, git fetch, git pull or git push with HTTPS URLs, you must provide your GitHub username and your personal access token when prompted for a username and password. The command line prompt won't specify that you should enter your personal access token when it asks for your password.

How to fix it

Generate a Personal Access Token. (Detailed guide on Creating a personal access token for the command line.)
Copy the Personal Access Token.
Re-attempt the command you were trying and use Personal Access Token in the place of your password.

Related question:
https://stackoverflow.com/a/21374369/101662


[System] You are a helpful assistant.

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

[Assistant]
Pass merge strategy specific option through to the merge
strategy.


[System] You are a helpful assistant.

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

[Assistant]
When true, rebase the branch <name> on top of the fetched branch,
instead of merging the default branch from the default remote when
"git pull" is run. See "pull.rebase" for doing this in a non
branch-specific manner. When merges (or just m ), pass the --rebase-merges option to git rebase so that the local merge commits are included in the rebase (see git-rebase for details). When the value is interactive (or just i ), the rebase is run in interactive
mode. NOTE : this is a possibly dangerous operation; do not use
it unless you understand the implications (see git-rebase for details).


[System] You are a helpful assistant.

[User] git-send-email - Send a collection of patches as emails  --smtp-ssl-cert-path

[Assistant]
Path to a store of trusted CA certificates for SMTP SSL/TLS
certificate validation (either a directory that has been processed
by c_rehash , or a single file containing one or more PEM format
certificates concatenated together: see verify(1) -CAfile and
-CApath for more information on these). Set it to an empty string
to disable certificate verification. Defaults to the value of the sendemail.smtpSSLCertPath configuration variable, if set, or the
backing SSL library’s compiled-in default otherwise (which should
be the best choice on most platforms).


[System] You are a helpful assistant.

[User]
How do I move unpushed committed code to another branch?
So I have the following situation:
I committed some work locally, without pushing to the remote repository. I want to move this local code to another branch, because if I pull, there will be modifications that will ruin all the work I put locally.
This is the output of git status on the old branch:
On branch <branch_name>
Your branch is ahead of 'origin/<branch_name>' by 1 commit.
  (use "git push" to publish your local commits)
nothing to commit, working directory clean

And this is the output of git status on the newly created branch:
On branch <branch_name>
nothing to commit, working directory clean

[Assistant]
If it's just one commit, you can simply do
git reset HEAD~1
git stash
git checkout anotherbranch
git stash pop

And if you want to put it in a fresh new branch, another way is
git branch newbranch
git reset --hard HEAD~1


[System] You are a helpful assistant.

[User]
How do I exit from the text window in Git?
I am using Windows and before committing, Git wants me to enter a text message and a new text window appears.

How can I exit from this?
I am trying to learn Git. So, a little help will be highly appreciated.

[Assistant]
Since you are learning Git, know that this has little to do with git but with the text editor configured for use. In vim, you can press i to start entering text and save by pressing esc and :wq and enter, this will commit with the message you typed. In your current state, to just come out without committing, you can do :q instead of the :wq as mentioned above.
Alternatively, you can just do git commit -m '<message>' instead of having git open the editor to type the message.
Note that you can also change the editor and use something you are comfortable with ( like notepad) - How can I set up an editor to work with Git on Windows?


[System] You are a helpful assistant.

[User] git-rebase - Reapply commits on top of another base tip  -r  --rebase-merges[=(rebase-cousins|no-rebase-cousins)]  --no-rebase-merges

[Assistant]
By default, a rebase will simply drop merge commits from the todo
list, and put the rebased commits into a single, linear branch.
With --rebase-merges , the rebase will instead try to preserve
the branching structure within the commits that are to be rebased,
by recreating the merge commits. Any resolved merge conflicts or
manual amendments in these merge commits will have to be
resolved/re-applied manually. --no-rebase-merges can be used to
countermand both the rebase.rebaseMerges config option and a previous --rebase-merges . When rebasing merges, there are two modes: rebase-cousins and no-rebase-cousins . If the mode is not specified, it defaults to no-rebase-cousins . In no-rebase-cousins mode, commits which do not have <upstream> as direct ancestor will keep their original branch point, i.e.
commits that would be excluded by git-log 's --ancestry-path option will keep their original ancestry by default. In rebase-cousins mode,
such commits are instead rebased onto <upstream> (or <onto> , if
specified). It is currently only possible to recreate the merge commits using the ort merge strategy; different merge strategies can be used only via
explicit exec git merge -s <strategy> [...] commands. See also REBASING MERGES and INCOMPATIBLE OPTIONS below.


[System] You are a helpful assistant.

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

[Assistant] raw body (unwrapped subject and body)


[System] You are a helpful assistant.

[User]
What happen to Git tags pointing to a removed commit
Say I do the following:

Create branch X
Create Tag t (to branch X)
Push
Remove branch X

What happen to tag t? is it just floating there? is it considered as garbage?
Should I remove all tags pointing at branch before removing the branch itself?
Reference
From Git Basics - Tagging:

Git uses two main types of tags: lightweight and annotated. A
lightweight tag is very much like a branch that doesn’t change – it’s
just a pointer to a specific commit.

[Assistant]
What happen to tag t?

Let's say you created branch x from a commit E and then tagged that commit with tag t. E.g.
                           x (branch)
                           |
                           V
A-----B------C------D------E
                           ^
                           |
                           t (tag)

If you remove branch x nothing happens to tag t.
git branch -D x

The tag still points to commit E.
A-----B------C------D------E
                           ^
                           |
                           t (tag)

is it considered as garbage?

No, because the commit is still referenced by tag t.

What if the commit is removed?

You do not remove commits. You remove pointers to commits and if commits are no longer referenced git will garbage collect them some day (depending on your configuration).
See git gc
Even if you removed all ordinary refs, like branches and tags, the commits will still be referenced in the reflog for some time and you can access them, e.g. re-create a branch, tag them or cherry-pick and so on.
You can see the reflog using git reflog. Also take a look at gc.reflogExpireUnreachable and gc.reflogExpire

EDIT
If somehow git's object database is corrupted. Either a file from .git/objects was deleted (e.g. you accidentially deleted it using your file explorer or a command-line command) or a ref points to a non-existent git object (like a commit, tree or blob object), you will get errors if git tries to access these objects.
Here is a list of errors that might occur when git tries to access an object that does not exist or if a non-existent object is referenced.

commit
fatal: Could not parse object '<ref-name>'.

example:
fatal: Could not parse object 'master'.

tree
fatal: unable to read tree <tree-sha1>

example:
fatal: unable to read tree 13a3e0908e4f6fc7526056377673a5987e753fc8

blob
error: unable to read sha1 file of <blob-name> (<blob-sha1>)

example:
error: unable to read sha1 file of test.txt (e69de29bb2d1d6434b8b29ae775ad8c2e48c5391)

Take a look at Git Internals for a deeper understanding.


[System] You are a helpful assistant.

[User]
How to get another branch instead of default branch with go get
I have 2 repositories. Let say them repo_a and repo_b. I imported repo_a in repo_b
When I ran go get, it will get repo_a master branch.
Is there any way to get develop branch using go get or another command from repo_b?
I do not want to git pull on each specific package (in this case repo_a)

[Assistant]
Starting with Go 1.11, this is possible when using Go modules. When installing a dependency for a Go module, you can specify a module query which may contain a branch or tag name:
$ go get <path-to-repo>@<branch>


[System] You are a helpful assistant.

[User] git - the stupid content tracker  gitformat-bundle

[Assistant] The bundle file format


[System] You are a helpful assistant.

[User]
Why is my git repository so big?
145M = .git/objects/pack/
I wrote a script to add up the sizes of differences of each commit and the commit before it going backwards from the tip of each branch. I get 129MB, which is without compression and without accounting for same files across branches and common history among branches.
Git takes all those things into account so I would expect much much smaller repository. So why is .git so big?
I've done:
git fsck --full
git gc --prune=today --aggressive
git repack

To answer about how many files/commits, I have 19 branches about 40 files in each.
287 commits, found using:
git log --oneline --all|wc -l

It should not be taking 10's of megabytes to store information about this.

[Assistant]
Some scripts I use:
git-fatfiles
git rev-list --all --objects | \
    sed -n $(git rev-list --objects --all | \
    cut -f1 -d' ' | \
    git cat-file --batch-check | \
    grep blob | \
    sort -n -k 3 | \
    tail -n40 | \
    while read hash type size; do
         echo -n "-e s/$hash/$size/p ";
    done) | \
    sort -n -k1

...
89076 images/screenshots/properties.png
103472 images/screenshots/signals.png
9434202 video/parasite-intro.avi

If you want more lines, see also Perl version in a neighbouring answer: https://stackoverflow.com/a/45366030/266720
git-eradicate (for video/parasite.avi):
git filter-branch -f  --index-filter \
    'git rm --force --cached --ignore-unmatch video/parasite-intro.avi' \
     -- --all
rm -Rf .git/refs/original && \
    git reflog expire --expire=now --all && \
    git gc --aggressive && \
    git prune

Note: the second script is designed to remove info from Git completely (including all info from reflogs). Use with caution.


[System] You are a helpful assistant.

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

[Assistant]
Only the selected commits are shown, plus some to have a
meaningful history.


[System] You are a helpful assistant.

[User] git - the stupid content tracker  git-ls-remote

[Assistant] List references in a remote repository


[System] You are a helpful assistant.

[User] git-send-email - Send a collection of patches as emails  --compose-encoding=<encoding>

[Assistant] Specify encoding of compose message. Default is the value of the sendemail.composeEncoding ; if that is unspecified, UTF-8 is assumed.


[System] You are a helpful assistant.

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

[Assistant]
This algorithm extends the patience algorithm to "support
low-occurrence common elements".


[System] You are a helpful assistant.

[User] git - the stupid content tracker  git-unpack-objects

[Assistant] Unpack objects from a packed archive


[System] You are a helpful assistant.

[User]
Git: Set local user.name and user.email different for each repo

I'm currently working on 2 projects, which expect that I configure my local username and email with different data when I push to them. For that I'm updating my config all the time like:
git config --local user.email "[email protected]"
Since they are different repositories, is there a way I could define an local email for each repository?
Maybe in the .gitconfig?

[Assistant]
For just one repo, go into to the relevant repo DIR and:
git config user.name "Your Name Here"
git config user.email [email protected]

For (global) default email (which is configured in your ~/.gitconfig):
git config --global user.name "Your Name Here"
git config --global user.email [email protected]

You can check your Git settings with:
git config user.name && git config user.email
If you are in a specific repo which you setup a new user/config for (different to global) then it should show that local config, otherwise it will show your global config.


[System] You are a helpful assistant.

[User] git-clone - Clone a repository into a new directory  --no-tags

[Assistant]
Don’t clone any tags, and set remote.<remote>.tagOpt=--no-tags in the config, ensuring
that future git pull and git fetch operations won’t follow
any tags. Subsequent explicit tag fetches will still work,
(see git-fetch ). Can be used in conjunction with --single-branch to clone and
maintain a branch with no references other than a single cloned
branch. This is useful e.g. to maintain minimal clones of the default
branch of some repository for search indexing.


[System] You are a helpful assistant.

[User] git-gc - Cleanup unnecessary files and optimize the local repository  gc.repackFilterTo

[Assistant]
When repacking and using a filter, see gc.repackFilter , the
specified location will be used to create the packfile
containing the filtered out objects. WARNING: The
specified location should be accessible, using for example the
Git alternates mechanism, otherwise the repo could be
considered corrupt by Git as it migh not be able to access the
objects in that packfile. See the --filter-to=<dir> option
of git-repack and the objects/info/alternates section of gitrepository-layout .


[System] You are a helpful assistant.

[User]
How to run cloned Django project?

I am a junior software engineer and am quite new to Django. I built this app and am working on a README to explain to others how to fork, clone and setup the app on their own machines. I've gotten stuck while trying to re-create the steps.
This is the order in which I've drawn up the steps:

Fork and clone the repo
Source a virtual environment
Pip install requirements.txt
Obtain access_token and secret_key and store in secrets.sh
Setup a Postgres DB, create user & database
Migrate (?) - This is where I get stuck!

I tried migrating the app but there are no migrations to apply.
I tried django-admin startproject ig_miner_app . but am getting this error code:
CommandError: /Users/Erin/Desktop/CodeByEAllard/project/instagram_miner/manage.py already exists, overlaying a project or app into an existing directory won't replace conflicting files
If I can get this sorted out, I should just be able to run the server like normal, right?
I'm sure I'm missing something (or many things) but don't know what they are. I feel silly because I was obviously able to create the app in the first place, but can't figure out how to explain to someone else to do the same! Does any have suggestions for how to get the server to run?
Thank you!

[Assistant]
First off, you are getting that error because you are starting a project within the same directory as the cloned project, this directory already contains an app with the name ig_miner_app hence the name conflict.
As regards steps to running the project by other users , this should work.
clone the project
git clone https://github.com/erinallard/instagram_miner.git

create and start a  a virtual environment
virtualenv env --no-site-packages

source env/bin/activate

Install the project dependencies:
pip install -r requirements.txt

create a file named "secrets.sh"
touch secrets.sh (mac and linux)
obtain a secret from MiniWebTool key and add to secrets.sh
export SECRET_KEY='<secret_key>'

add secrets.sh to .gitignore file
create a postgres db and add the credentials to settings.py
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'db_name',
        'USER': 'name',
        'PASSWORD': '',
        'HOST': 'localhost',
        'PORT': '',
    }
}

then run
python manage.py migrate

create admin account
python manage.py createsuperuser

then
python manage.py makemigrations ig_miner_app

to makemigrations for the app
then again run
python manage.py migrate

to start the development server
python manage.py runserver

and open localhost:8000 on your browser to view the app.
I believe this should get the app up and running on others' machines. Let me know if you get stuck on any of these steps so I make edits, if not, you can just use it and add any other relevant info I might not have added.


[System] You are a helpful assistant.

[User]
How can I format patch with what I stash away
In git, I stash away my changes.  Is it possible that I can create a patch with what I stash away? And then apply that patch in some other repository (my co-worker's)?
I know git format-patch -1, but I think that it's for what I have committed. But I am looking for the same thing for changes that I stashed away.
And how can I apply a patch in other repository?

[Assistant]
Sure, git stash show supports this:
git stash show -p

So, use
git stash list

to find out the number of the stash that you want to export as a patch, then
git stash show -p stash@{<number>} > <name>.patch

to export it.
For example:
git stash show -p stash@{3} > third_stash.patch


[System] You are a helpful assistant.

[User]
IntelliJ, unable to share Project on GitHub (Permission Denied)

I'm new to Git and GitHub/GitLab. I try to share my project to GitHub but it throws this exception:
Can't finish GitHub sharing process
        Successfully created project 'LiveGame1' on GitHub, but initial push failed:
        [email protected]: Permission denied (publickey).
        Could not read from remote repository.
        Please make sure you have the correct access rights
        and the repository exists.

I'm also able to clone a repository via internet link, but not via "[email protected]:/username/repository_name".
How can I fix this error and am I able to share my project directly to GitLab?

[Assistant]
This article helped me get things squared away on my Windows 10 box:
https://richardballard.co.uk/ssh-keys-on-windows-10/
Note:  The first section in the article should be titled "Enable the SSH Client in Windows" and should refer to getting the SSH Client enabled, not the server.
If you can get ssh -T [email protected] working without prompting you for your password, as described in the above article, then you'll be able to push from IntelliJ just fine.
The keys were to:

get the OpenSSH Authentication Agent service running in Windows
make sure ssh-add that is invoked is the one provided in C:\Windows\System32\OpenSSH
make sure git is also configured to use the ssh provided by Windows:

git config --global core.sshCommand "'C:\Windows\System32\OpenSSH\ssh.exe'"
When generating your keys with ssh-keygen consider using the ecdsa algorithm as described here:  https://www.ssh.com/ssh/keygen/
Also important was cleaning up anything else that was trying to do ssh outside of windows (like Putty).  One problem I kept facing with 'invalid format' when trying to run ssh-add I believe was caused by a different ssh-add program on my path that was being used rather than the one from OpenSSH that ships with Windows.


[System] You are a helpful assistant.

[User] git-merge - Join two or more development histories together  --signoff  --no-signoff

[Assistant]
Add a Signed-off-by trailer by the committer at the end of the commit
log message.  The meaning of a signoff depends on the project
to which you’re committing.  For example, it may certify that
the committer has the rights to submit the work under the
project’s license or agrees to some contributor representation,
such as a Developer Certificate of Origin.
(See https://developercertificate.org for the one used by the
Linux kernel and Git projects.)  Consult the documentation or
leadership of the project to which you’re contributing to
understand how the signoffs are used in that project. The --no-signoff option can be used to countermand an earlier --signoff
option on the command line.


[System] You are a helpful assistant.

[User]
What I can do to resolve "1 commit behind master"?

After pushing I've been seeing this message at remote repository:

1 commit behind master.
This merge has conflicts that must be resolved before it can be committed.
To manually merge these changes into TA20footerLast run the following commands:
git checkout 7c891f50c557
Note: This will create a detached head!
git merge remotes/origin/master

[Assistant]
Before you begin, if you are uncomfortable with a command line, you can do all the following steps using SourceTree, GitExtensions, GitHub Desktop, or your favorite tool.
To solve the issue, you might have two scenarios:

1. Fix only remote repository branch which is behind commit
Example: Both branches are on the remote side
ahead === Master branch
behind === Develop branch
Solution:

Clone the repository to the local workspace: this will give you the Master branch, which is ahead with commit
git clone repositoryUrl

Create a branch with Develop name and checkout to that branch locally
git checkout -b DevelopBranchName // this command creates and checkout the branch

Pull from the remote Develop branch. Conflict might occur. if so, fix the
conflict and commit the changes.
 git pull origin DevelopBranchName

Merge the local Develop branch with the remote Develop branch
  git merge origin develop

Push the merged branch to the remote Develop branch
  git push origin develop

2. Local Master branch is behind the remote Master branch
This means every locally created branch is behind.
Before preceding, you have to commit or stash all the changes you made on the branch behind commits.
Solution:

Checkout your local Master branch
git checkout master

Pull from remote Master branch
git pull origin master

Now your local Master is in sync with the remote branch. As a result of the above command, other local branches branched from the previous local Master branch are not in sync. To fix that:

Checkout the branch that is behind your local Master branch
git checkout BranchNameBehindCommit

Merge with the local Master branch
git merge master  // Now your branch is in sync with the local Master branch

If this branch is on the remote repository, you have to push your changes.
    git push origin branchBehindCommit


[System] You are a helpful assistant.

[User]
Integrating GitLab with TeamCity

Since GitLab 7.6, or thereabouts, there is a new option to use TeamCity directly from GitLab projects. In the setup there is this message:

The build configuration in Teamcity must use the build format number
  %build.vcs.number% you will also want to configure monitoring of all
  branches so merge requests build, that setting is in the vsc root
  advanced settings.

I'm not sure how this works. Lets say I have a repository Foo.
I have setup a build on TeamCity to listen to Foo with branch specification: +:refs/pull/*/merge
I then fork Foo in gitlab as FooFork, make a change, then request a merge FooFork -> Foo.
But nothing happens to test this merge, which is what I was expecting GitLab to do. If I accept the merge than the build server jumps into action (immediately) and builds twice (master and /ref/master).
I've also set the build configuration to use exactly: %build.vcs.number% as the build number as prescribed, but gitlab doesn't seem to give me any information about the build result.
So I'm a bit confused really as to what exactly this GitLab -> TeamCity integration is supposed to do and whether I'm doing wrong.
I'm currently running GitLab 7.9 and TeamCity 8.1.4
Update:
Seems this use case was not supported prior to version 8 - https://github.com/gitlabhq/gitlabhq/issues/7240

[Assistant]
I'm running GitLab 8.0.2 and TeamCity 9.1.1 and am able to run CI builds on branches and merge requests.
I trigger CI builds for specific branches by setting a VCS trigger together with the branch specification +:refs/heads/(xyz*) where xyz is the string for our ticket system prefix since all active branches need to be named after an entry in our issue tracker.
I trigger builds for merge requests via the branch specification +:refs/(merge-requests/*)
Everything works as as expected and lets us know the status of all feature / bug branches and merge requests automatically.
Thanks to Rob's comment linking to the GitLab 8 release notes entry on the merge request spec.


[System] You are a helpful assistant.

[User]
GitLab CI: how can I set two dependencies pipelines to run in parallel?

At the moment, I have a pipeline defined with 4 different stages to build dependencies for my project:
stages:
  - dependencies-A
  - dependencies-B
  - dependencies-C
  - dependencies-D
  - build

Thus, the jobs in the pipeline now run like this:
A -> B -> C -> D -> build

Actually, B depends on A, and D depends on C. The sub-pipelines A->B and C->D being independent, I would like to run those two sub-pipelines in parallel, to speed up the build. So, that way:
A -> B \
         build
C -> D /

Is that possible at all?
Thanks for your kind help.

[Assistant]
If you are using Gitlab version > 12.2, you can use needs keyword to create a directed acyclic graph.
In this case your .gitlab-ci.yml shoul look something like this:
Here depB will start after depA successfully completes. Same goes for depC and depD stages.
build stage will run after all the other stages are done.
stages:
  - dependencies-A-C
  - dependencies-B-D
  - build

depA:
  stage: dependencies-A-C

depB:
  stage: dependencies-B-D
  needs: ["depA"]

depC:
  stage: dependencies-A-C

depD:
  stage: ependencies-B-D
  needs: ["depC"]

build:
  stage: build

Find more in docs:
https://docs.gitlab.com/ee/ci/directed_acyclic_graph/
https://docs.gitlab.com/ee/ci/yaml/README.html#needs