Git how to update local repository
Git how to update local repository
Совместная работа и обновление проектов
Не так уж много команд в Git требуют сетевого подключения для своей работы, практически все команды оперируют с локальной копией проекта. Когда вы готовы поделиться своими наработками, всего несколько команд помогут вам работать с удалёнными репозиториями.
git fetch
Команда git fetch связывается с удалённым репозиторием и забирает из него все изменения, которых у вас пока нет и сохраняет их локально.
Мы познакомились с ней в разделе Получение изменений из удалённого репозитория — Fetch и Pull главы 2 и продолжили знакомство в разделе Удалённые ветки главы 3.
Мы использовали эту команду в нескольких примерах из раздела Участие в проекте.
Мы использовали её для скачивания запросов на слияние (pull request) из других репозиториев в разделе Ссылки на запрос слияния главы 6, также мы рассмотрели использование git fetch для работы с упакованными репозиториями в разделе Создание пакетов главы 7.
Мы рассмотрели тонкую настройку git fetch в главе и Спецификации ссылок.
git pull
Мы познакомились с ней в разделе Получение изменений из удалённого репозитория — Fetch и Pull главы 2 и показали как узнать, какие изменения будут приняты в случае применения в разделе Просмотр удаленного репозитория главы 2.
Мы также увидели как она может оказаться полезной для разрешения сложностей при перемещении веток в разделе Меняя базу, меняй основание главы 3.
Мы показали как можно использовать только URL удалённого репозитория без сохранения его в списке удалённых репозиториев в разделе Извлечение удалённых веток главы 5.
git push
Команда git push используется для установления связи с удалённым репозиторием, вычисления локальных изменений отсутствующих в нём, и собственно их передачи в вышеупомянутый репозиторий. Этой команде нужно право на запись в репозиторий, поэтому она использует аутентификацию.
На протяжении раздела Участие в проекте мы показали несколько примеров использования git push для совместной работы в нескольких удалённых репозиториях одновременно.
Наконец, в разделе Спецификации ссылок для отправки данных на сервер главы 10 мы рассмотрели передачу данных с полным указанием передаваемых ссылок, вместо использования распространённых сокращений. Это может быть полезным если вы хотите очень точно указать, какими изменениями хотите поделиться.
git remote
Команда git remote служит для управления списком удалённых репозиториев. Она позволяет сохранять длинные URL репозиториев в виде понятных коротких строк, например «origin», так что вам не придётся забивать голову всякой ерундой и набирать её каждый раз для связи с сервером. Вы можете использовать несколько удалённых репозиториев для работы и git remote поможет добавлять, изменять и удалять их.
Эта команда детально рассмотрена в разделе Работа с удалёнными репозиториями главы 2, включая вывод списка удалённых репозиториев, добавление новых, удаление или переименование существующих.
git archive
Команда git archive используется для упаковки в архив указанных коммитов или всего репозитория.
Мы использовали git archive для создания тарбола ( tar.gz файла) всего проекта для передачи по сети в разделе Подготовка релиза главы 5.
git submodule
Эта команда упомянута и полностью раскрыта в разделе Подмодули главы 7.
How to update local repo with master?
I am used to using SVN and only recently switched to GitHub.
I am trying to update some files in a GitHub repo, but I get this message:
In SVN I’d just do svn update and then commit my changes.
2 Answers 2
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
Check your current branch with the command:
git branch
It will show your current branch name with an asterisk (*) next the name.
Then update your local branch with the remote branch:
git pull origin branchname (This is the branch name with asterisks)
Now you can push your code to the remote repository if you have already committed your local changes with the command:
git push origin branchname
If you haven’t committed yet, first do a commit and then do a git pull and push.
It is normal for git to open an editor when you pull. This is because you are merging in the changes from the remote to your local branch.
When you pull, git detects whether it needs to merge your local branch with the remote branch. If it needs to merge, it will do so and present you with the opportunity to write a custom message for the merge commit. At that point, you can choose to just close the editor, and git will finish the process.
Basically, all you had to do is close the editor and you would have been done.
Git how to update local repository and keep my changes
I use git clone for copy remote repository to my local machine. I made some changes (via nano) in some code lets say in 5-10 files (repository have more then 2000 files i think).
But now this repository get some nice updates. And i want get all this updates, but i want keep my custom changes. I cant commit to this repository because i believe my code and fixes are «bad» and not perfect.
Which command i should use to get all updates and keep my changes in files?
2 Answers 2
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
Simplest way (if you are working on the branch on want to update):
Another option is to create another branch to keep your changes:
On booth methods you might get conflicts, to solve them you can use:
One option would be to stash your working directory (and possibly stage), pull the changes in, and then apply the stash afterward:
This should leave you in roughly the state you were in before pulling in the new changes. I said «roughly» because applying the stash may cause merge conflicts. Such conflicts may be unavoidable if the changes you made conflict with changes made to the repo since you last synched.
If you are worried about losing your work, then I would recommend also creating a side branch with your changes. For this you can try:
Then, you can try merging or rebasing this branch on the original remote branch. Assuming you wanted to merge, you could try:
Now you have a branch with a bona fide commit containing your work. It would be really hard to lose your work in this safer setup.
Git 07: Updating Your Repo by Setting Up a Remote
Authors: Megan A. Jones
Last Updated: Apr 8, 2021
This tutorial covers how to set up a Central Repo as a remote to your local repo in order to update your local fork with updates. You want to do this every time before starting new edits in your local repo.
Learning Objectives
At the end of this activity, you will be able to:
Additional Resources
We now have done the following:
Once you’re all setup to work on your project, you won’t need to repeat the fork and clone steps. But you do want to update your local repository with any changes other’s may have added to the central repository. How do we do this?
We will do this by directly pulling the updates from the central repo to our local repo by setting up the local repo as a «remote». A «remote» repo is any repo which is not the repo that you are currently working in.
Update, then Work
Once you’ve established working in your repo, you should follow these steps when starting to work each time in the repo:
Notice that we’ve already learned how to do steps 2-4, now we are completing the circle by learning to update our local repo directly with any changes from the central repo.
The order of steps above is important as it ensures that you incorporate any changes that have been made to the NEON central repository into your forked & local repos prior to adding changes to the central repo. If you do not sync in this order, you are at greater risk of creating a merge conflict.
What’s A Merge Conflict?
A merge conflict occurs when two users edit the same part of a file at the same time. Git cannot decide which edit was first and which was last, and therefore which edit should be in the most current copy. Hence the conflict.
Merge conflicts occur when the same part of a script or document has been changed simultaneously and Git can’t determine which change should be applied. Source: Atlassian
Set up Upstream Remote
We want to directly update our local repo with any changes made in the central repo prior to starting our next edits or additions. To do this we need to set up the central repository as an upstream remote for our repo.
Step 1: Get Central Repository URL
First, we need the URL of the central repository. Navigate to the central repository in GitHub NEONScience/DI-NEON-participants. Select the green Clone or Download button (just like we did when we cloned the repo) to copy the URL of the repo.
Step 2: Add the Remote
Make sure you are still in you local repository in bash
First, navigate to the desired directory.
Here you are identifying that is is a git command with git and then that you are adding an upstream remote with the given URL.
Step 3: Update Local Repo
Use git pull to sync your local repo with the forked GitHub.com repo.
Second, update local repo using git pull with the added directions of upstream indicating the central repository and master specifying which branch you are pulling down (remember, branches are a great tool to look into once you’re comfortable with Git and GitHub, but we aren’t going to focus on them. Just use master ).
Understand the output: The output will change with every update, several things to look for in the output:
Now that you’ve synced your local repo, let’s check the status of the repo.
Step 4: Complete the Cycle
Now you are set up with the additions, you will need to add and commit those changes. Once you’ve done that, you can push the changes back up to your fork on github.com.
Now your commits are added to your forked repo on github.com and you’re ready to repeat the loop with a Pull Request.
Workflow Summary
Syncing Central Repo with Local Repo
Setting It Up (only do this the initial time)
After Initial Set Up
Update your Local Repo & Push Changes
Have questions? No problem. Leave your question in the comment box below. It’s likely some of your colleagues have the same question, too! And also likely someone else knows the answer.
Questions?
If you have questions or comments on this content, please contact us.
Git User Manual
Table of Contents
Introduction
Git is a fast distributed revision control system.
This manual is designed to be readable by someone with basic UNIX command-line skills, but no previous knowledge of Git.
Chapter 1, Repositories and Branches and Chapter 2, Exploring Git history explain how to fetch and study a project using git—read these chapters to learn how to build and test a particular version of a software project, search for regressions, and so on.
Further chapters cover more specialized topics.
With the latter, you can use the manual viewer of your choice; see git-help(1) for more information.
See also Appendix A, Git Quick Reference for a brief overview of Git commands, without any explanation.
Finally, see Appendix B, Notes and todo list for this manual for ways that you can help make this manual more complete.
Chapter 1. Repositories and Branches
Table of Contents
How to get a Git repository
It will be useful to have a Git repository to experiment with as you read this manual.
The best way to get one is by using the git-clone(1) command to download a copy of an existing repository. If you don’t already have a project in mind, here are some interesting examples:
The initial clone may be time-consuming for a large project, but you will only need to clone once.
How to check out a different version of a project
Git is best thought of as a tool for storing the history of a collection of files. It stores the history as a compressed collection of interrelated snapshots of the project’s contents. In Git each such version is called a commit.
Those snapshots aren’t necessarily all arranged in a single line from oldest to newest; instead, work may simultaneously proceed along parallel lines of development, called branches, which may merge and diverge.
A single Git repository can track development on multiple branches. It does this by keeping a list of heads which reference the latest commit on each branch; the git-branch(1) command shows you the list of branch heads:
A freshly cloned repository contains a single branch head, by default named «master», with the working directory initialized to the state of the project referred to by that branch head.
Most projects also use tags. Tags, like heads, are references into the project’s history, and can be listed using the git-tag(1) command:
Tags are expected to always point at the same version of a project, while heads are expected to advance as development progresses.
Create a new branch head pointing to one of these versions and check it out using git-switch(1):
The working directory then reflects the contents that the project had when it was tagged v2.6.13, and git-branch(1) shows two branches, with an asterisk marking the currently checked-out branch:
If you decide that you’d rather see version 2.6.17, you can modify the current branch to point at v2.6.17 instead, with
Note that if the current branch head was your only reference to a particular point in history, then resetting that branch may leave you with no way to find the history it used to point to; so use this command carefully.
Understanding History: Commits
Every change in the history of a project is represented by a commit. The git-show(1) command shows the most recent commit on the current branch:
As you can see, a commit shows who made the latest change, what they did, and why.
Every commit has a 40-hexdigit id, sometimes called the «object name» or the «SHA-1 id», shown on the first line of the git show output. You can usually refer to a commit by a shorter name, such as a tag or a branch name, but this longer name can also be useful. Most importantly, it is a globally unique name for this commit: so if you tell somebody else the object name (for example in email), then you are guaranteed that name will refer to the same commit in their repository that it does in yours (assuming their repository has that commit at all). Since the object name is computed as a hash over the contents of the commit, you are guaranteed that the commit can never change without its name also changing.
In fact, in Chapter 7, Git concepts we shall see that everything stored in Git history, including file data and directory contents, is stored in an object with a name that is a hash of its contents.
Understanding history: commits, parents, and reachability
Every commit (except the very first commit in a project) also has a parent commit which shows what happened before this commit. Following the chain of parents will eventually take you back to the beginning of the project.
However, the commits do not form a simple list; Git allows lines of development to diverge and then reconverge, and the point where two lines of development reconverge is called a «merge». The commit representing a merge can therefore have more than one parent, with each parent representing the most recent commit on one of the lines of development leading to that point.
The best way to see how this works is using the gitk(1) command; running gitk now on a Git repository and looking for merge commits will help understand how Git organizes history.
In the following, we say that commit X is «reachable» from commit Y if commit X is an ancestor of commit Y. Equivalently, you could say that Y is a descendant of X, or that there is a chain of parents leading from commit Y to commit X.
Understanding history: History diagrams
If we need to talk about a particular commit, the character «o» may be replaced with another letter or number.
Understanding history: What is a branch?
When we need to be precise, we will use the word «branch» to mean a line of development, and «branch head» (or just «head») to mean a reference to the most recent commit on a branch. In the example above, the branch head named «A» is a pointer to one particular commit, but we refer to the line of three commits leading up to that point as all being part of «branch A».
However, when no confusion will result, we often just use the term «branch» both for branches and for branch heads.
Manipulating branches
Creating, deleting, and modifying branches is quick and easy; here’s a summary of the commands:
Examining an old version without creating a new branch
The HEAD then refers to the SHA-1 of the commit instead of to a branch, and git branch shows that you are no longer on a branch:
In this case we say that the HEAD is «detached».
This is an easy way to check out a particular version without having to make up a name for the new branch. You can still create a new branch (or tag) for this version later if you decide to.
Examining branches from a remote repository
You might want to build on one of these remote-tracking branches on a branch of your own, just as you would for a tag:
You can also check out origin/todo directly to examine it or write a one-off patch. See detached head.
Note that the name «origin» is just the name that Git uses by default to refer to the repository that you cloned from.
Naming branches, tags, and other references
Branches, remote-tracking branches, and tags are all references to commits. All references are named with a slash-separated path name starting with refs ; the names we’ve been using so far are actually shorthand:
The full name is occasionally useful if, for example, there ever exists a tag and a branch with the same name.
As another useful shortcut, the «HEAD» of a repository can be referred to just using the name of that repository. So, for example, «origin» is usually a shortcut for the HEAD branch in the repository «origin».
For the complete list of paths which Git checks for references, and the order it uses to decide which to choose when there are multiple references with the same shorthand name, see the «SPECIFYING REVISIONS» section of gitrevisions(7).
Updating a repository with git fetch
After you clone a repository and commit a few changes of your own, you may wish to check the original repository for updates.
The git-fetch command, with no arguments, will update all of the remote-tracking branches to the latest version found in the original repository. It will not touch any of your own branches—not even the «master» branch that was created for you on clone.
Fetching branches from other repositories
You can also track branches from repositories other than the one you cloned from, using git-remote(1):
If you run git fetch later, the remote-tracking branches for the named will be updated.
Chapter 2. Exploring Git history
Table of Contents
Git is best thought of as a tool for storing the history of a collection of files. It does this by storing compressed snapshots of the contents of a file hierarchy, together with «commits» which show the relationships between these snapshots.
Git provides extremely flexible and fast tools for exploring the history of a project.
We start with one specialized tool that is useful for finding the commit that introduced a bug into a project.
How to use bisect to find a regression
Suppose version 2.6.18 of your project worked, but the version at «master» crashes. Sometimes the best way to find the cause of such a regression is to perform a brute-force search through the project’s history to find the particular commit that caused the problem. The git-bisect(1) command can help you do this:
If you run git branch at this point, you’ll see that Git has temporarily moved you in «(no branch)». HEAD is now detached from any branch and points directly to a commit (with commit id 65934) that is reachable from «master» but not from v2.6.18. Compile and test it, and see whether it crashes. Assume it does crash. Then:
checks out an older version. Continue like this, telling Git at each stage whether the version it gives you is good or bad, and notice that the number of revisions left to test is cut approximately in half each time.
After about 13 tests (in this case), it will output the commit id of the guilty commit. You can then examine the commit with git-show(1), find out who wrote it, and mail them your bug report with the commit id. Finally, run
to return you to the branch you were on before.
Note that the version which git bisect checks out for you at each point is just a suggestion, and you’re free to try a different version if you think it would be a good idea. For example, occasionally you may land on a commit that broke something unrelated; run
which will run gitk and label the commit it chose with a marker that says «bisect». Choose a safe-looking commit nearby, note its commit id, and check it out with:
then test, run bisect good or bisect bad as appropriate, and continue.
In this case, though, Git may not eventually be able to tell the first bad one between some first skipped commits and a later bad commit.
There are also ways to automate the bisecting process if you have a test script that can tell a good from a bad commit. See git-bisect(1) for more information about this and other git bisect features.
Naming commits
We have seen several ways of naming commits already:
There are many more; see the «SPECIFYING REVISIONS» section of the gitrevisions(7) man page for the complete list of ways to name revisions. Some examples:
Recall that merge commits may have more than one parent; by default, ^ and
follow the first parent listed in the commit, but you can also choose:
In addition to HEAD, there are several other special names for commits:
The git fetch operation always stores the head of the last fetched branch in FETCH_HEAD. For example, if you run git fetch without specifying a local branch as the target of the operation
the fetched commits will still be available from FETCH_HEAD.
When we discuss merges we’ll also see the special name MERGE_HEAD, which refers to the other branch that we’re merging in to the current branch.
The git-rev-parse(1) command is a low-level command that is occasionally useful for translating some name for a commit to the object name for that commit:
Creating tags
We can also create a tag to refer to a particular commit; after running
You can use stable-1 to refer to the commit 1b2e1d63ff.
This creates a «lightweight» tag. If you would also like to include a comment with the tag, and possibly sign it cryptographically, then you should create a tag object instead; see the git-tag(1) man page for details.
Browsing revisions
The git-log(1) command can show lists of commits. On its own, it shows all commits reachable from the parent commit; but you can also make more specific requests:
And of course you can combine all of these; the following finds commits since v2.5 which touch the Makefile or any file under fs :
You can also ask git log to show patches:
Note that git log starts with the most recent commit and works backwards through the parents; however, since Git history can contain multiple independent lines of development, the particular order that commits are listed in may be somewhat arbitrary.
Generating diffs
You can generate diffs between any two versions using git-diff(1):
That will produce the diff between the tips of the two branches. If you’d prefer to find the diff from their common ancestor to test, you can use three dots instead of two:
Sometimes what you want instead is a set of patches; for this you can use git-format-patch(1):
will generate a file with a patch for each commit reachable from test but not from master.
Viewing old file versions
You can always view an old version of a file by just checking out the correct revision first. But sometimes it is more convenient to be able to view an old version of a single file without checking anything out; this command does that:
Before the colon may be anything that names a commit, and after it may be any path to a file tracked by Git.
Examples
Counting the number of commits on a branch
Suppose you want to know how many commits you’ve made on mybranch since it diverged from origin :
Alternatively, you may often see this sort of thing done with the lower-level command git-rev-list(1), which just lists the SHA-1’s of all the given commits:
Check whether two branches point at the same history
Suppose you want to check whether two branches point at the same point in history.
will tell you whether the contents of the project are the same at the two branches; in theory, however, it’s possible that the same project contents could have been arrived at by two different historical routes. You could compare the object names:
will return no commits when the two branches are equal.
Find first tagged version including a given fix
Suppose you know that the commit e05db0fd fixed a certain problem. You’d like to find the earliest tagged release that contains that fix.
Of course, there may be more than one answer—if the history branched after commit e05db0fd, then there could be multiple «earliest» tagged releases.
You could just visually inspect the commits since e05db0fd:
or you can use git-name-rev(1), which will give the commit a name based on any tag it finds pointing to one of the commit’s descendants:
The git-describe(1) command does the opposite, naming the revision using a tag on which the given commit is based:
but that may sometimes help you guess which tags might come after the given commit.
If you just want to verify whether a given tagged version contains a given commit, you could use git-merge-base(1):
The merge-base command finds a common ancestor of the given commits, and always returns one or the other in the case where one is a descendant of the other; so the above output shows that e05db0fd actually is an ancestor of v1.5.0-rc1.
Alternatively, note that
will produce empty output if and only if v1.5.0-rc1 includes e05db0fd, because it outputs only commits that are not reachable from v1.5.0-rc1.
As yet another alternative, the git-show-branch(1) command lists the commits reachable from its arguments with a display on the left-hand side that indicates which arguments that commit is reachable from. So, if you run something like
then a line like
shows that e05db0fd is reachable from itself, from v1.5.0-rc1, and from v1.5.0-rc2, and not from v1.5.0-rc0.
Showing commits unique to a given branch
Suppose you would like to see all the commits reachable from the branch head named master but not from any other head in your repository.
We can list all the heads in this repository with git-show-ref(1):
And then we can ask to see all the commits reachable from master but not from these other heads:
Obviously, endless variations are possible; for example, to see all commits reachable from some head but not from any tag in the repository:
Creating a changelog and tarball for a software release
The git-archive(1) command can create a tar or zip archive from any version of a project; for example:
Versions of Git older than 1.7.7 don’t know about the tar.gz format, you’ll need to use gzip explicitly:
If you’re releasing a new version of a software project, you may want to simultaneously make a changelog to include in the release announcement.
Linus Torvalds, for example, makes new kernel releases by tagging them, then running:
where release-script is a shell script that looks like:
and then he just cut-and-pastes the output commands after verifying that they look OK.
Finding commits referencing a file with given content
Somebody hands you a copy of a file, and asks which commits modified a file such that it contained the given content either before or after the commit. You can find out with this:
Figuring out why this works is left as an exercise to the (advanced) student. The git-log(1), git-diff-tree(1), and git-hash-object(1) man pages may prove helpful.
Chapter 3. Developing with Git
Table of Contents
Telling Git your name
Before creating any commits, you should introduce yourself to Git. The easiest way to do so is to use git-config(1):
See the «CONFIGURATION FILE» section of git-config(1) for details on the configuration file. The file is plain text, so you can also edit it with your favorite editor.
Creating a new repository
Creating a new repository from scratch is very easy:
If you have some initial content (say, a tarball):
How to make a commit
Creating a new commit takes three steps:
In practice, you can interleave and repeat steps 1 and 2 as many times as you want: in order to keep track of what you want committed at step 3, Git maintains a snapshot of the tree’s contents in a special staging area called «the index.»
Modifying the index is easy:
To update the index with the contents of a new or modified file, use
To remove a file from the index and from the working tree, use
After each step you can verify that
always shows the difference between the HEAD and the index file—this is what you’d commit if you created the commit now—and that
shows the difference between the working tree and the index file.
Note that git add always adds just the current contents of a file to the index; further changes to the same file will be ignored unless you run git add on the file again.
When you’re ready, just run
and Git will prompt you for a commit message and then create the new commit. Check to make sure it looks like what you expected with
As a special shortcut,
will update the index with any files that you’ve modified or removed and create a commit, all in one step.
A number of commands are useful for keeping track of what you’re about to commit:
You can also use git-gui(1) to create commits, view changes in the index and the working tree files, and individually select diff hunks for inclusion in the index (by right-clicking on the diff hunk and choosing «Stage Hunk For Commit»).
Creating good commit messages
Though not required, it’s a good idea to begin the commit message with a single short (less than 50 character) line summarizing the change, followed by a blank line and then a more thorough description. The text up to the first blank line in a commit message is treated as the commit title, and that title is used throughout Git. For example, git-format-patch(1) turns a commit into email, and it uses the title on the Subject line and the rest of the commit in the body.
Ignoring files
How to merge
You can rejoin two diverging branches of development using git-merge(1):
merges the development in the branch branchname into the current branch.
A merge is made by combining the changes made in branchname and the changes made up to the latest commit in your current branch since their histories forked. The work tree is overwritten by the result of the merge when this combining is done cleanly, or overwritten by a half-merged results when this combining results in conflicts. Therefore, if you have uncommitted changes touching the same files as the ones impacted by the merge, Git will refuse to proceed. Most of the time, you will want to commit your changes before you can merge, and if you don’t, then git-stash(1) can take these changes away while you’re doing the merge, and reapply them afterwards.
If the changes are independent enough, Git will automatically complete the merge and commit the result (or reuse an existing commit in case of fast-forward, see below). On the other hand, if there are conflicts—for example, if the same file is modified in two different ways in the remote branch and the local branch—then you are warned; the output may look something like this:
Conflict markers are left in the problematic files, and after you resolve the conflicts manually, you can update the index with the contents and run Git commit, as you normally would when creating a new file.
If you examine the resulting commit using gitk, you will see that it has two parents, one pointing to the top of the current branch, and one to the top of the other branch.
Resolving a merge
When a merge isn’t resolved automatically, Git leaves the index and the working tree in a special state that gives you all the information you need to help resolve the merge.
Files with conflicts are marked specially in the index, so until you resolve the problem and update the index, git-commit(1) will fail:
Also, git-status(1) will list those files as «unmerged», and the files with conflicts will have conflict markers added, like this:
All you need to do is edit the files to resolve the conflicts, and then
Note that the commit message will already be filled in for you with some information about the merge. Normally you can just use this default message unchanged, but you may add additional commentary of your own if desired.
The above is all you need to know to resolve a simple merge. But Git also provides more information to help resolve conflicts:
Getting conflict-resolution help during a merge
All of the changes that Git was able to merge automatically are already added to the index file, so git-diff(1) shows only the conflicts. It uses an unusual syntax:
Recall that the commit which will be committed after we resolve this conflict will have two parents instead of the usual one: one parent will be HEAD, the tip of the current branch; the other will be the tip of the other branch, which is stored temporarily in MERGE_HEAD.
During the merge, the index holds three versions of each file. Each of these three «file stages» represents a different version of the file:
When you ask git-diff(1) to show the conflicts, it runs a three-way diff between the conflicted merge results in the work tree with stages 2 and 3 to show only hunks whose contents come from both sides, mixed (in other words, when a hunk’s merge results come only from stage 2, that part is not conflicting and is not shown. Same for stage 3).
After resolving the conflict in the obvious way (but before updating the index), the diff will look like:
This shows that our resolved version deleted «Hello world» from the first parent, deleted «Goodbye» from the second parent, and added «Goodbye world», which was previously absent from both.
Some special diff options allow diffing the working directory against any of these stages:
The git-log(1) and gitk(1) commands also provide special help for merges:
These will display all commits which exist only on HEAD or on MERGE_HEAD, and which touch an unmerged file.
You may also use git-mergetool(1), which lets you merge the unmerged files using external tools such as Emacs or kdiff3.
Each time you resolve the conflicts in a file and update the index:
the different stages of that file will be «collapsed», after which git diff will (by default) no longer show diffs for that file.
Undoing a merge
If you get stuck and decide to just give up and throw the whole mess away, you can always return to the pre-merge state with
Or, if you’ve already committed the merge that you want to throw away,
However, this last command can be dangerous in some cases—never throw away a commit you have already committed if that commit may itself have been merged into another branch, as doing so may confuse further merges.
Fast-forward merges
There is one special case not mentioned above, which is treated differently. Normally, a merge results in a merge commit, with two parents, one pointing at each of the two lines of development that were merged.
However, if the current branch is an ancestor of the other—so every commit present in the current branch is already contained in the other branch—then Git just performs a «fast-forward»; the head of the current branch is moved forward to point at the head of the merged-in branch, without any new commits being created.
Fixing mistakes
If you’ve messed up the working tree, but haven’t yet committed your mistake, you can return the entire working tree to the last committed state with
If you make a commit that you later wish you hadn’t, there are two fundamentally different ways to fix the problem:
Fixing a mistake with a new commit
Creating a new commit that reverts an earlier change is very easy; just pass the git-revert(1) command a reference to the bad commit; for example, to revert the most recent commit:
This will create a new commit which undoes the change in HEAD. You will be given a chance to edit the commit message for the new commit.
You can also revert an earlier change, for example, the next-to-last:
In this case Git will attempt to undo the old change while leaving intact any changes made since then. If more recent changes overlap with the changes to be reverted, then you will be asked to fix conflicts manually, just as in the case of resolving a merge.
Fixing a mistake by rewriting history
Alternatively, you can edit the working directory and update the index to fix your mistake, just as if you were going to create a new commit, then run
which will replace the old commit by a new commit incorporating your changes, giving you a chance to edit the old commit message first.
Again, you should never do this to a commit that may already have been merged into another branch; use git-revert(1) instead in that case.
It is also possible to replace commits further back in the history, but this is an advanced topic to be left for another chapter.
Checking out an old version of a file
In the process of undoing a previous bad change, you may find it useful to check out an older version of a particular file using git-restore(1). The command
replaces path/to/file by the contents it had in the commit HEAD^, and also updates the index to match. It does not change branches.
If you just want to look at an old version of the file, without modifying the working directory, you can do that with git-show(1):
which will display the given version of the file.
Temporarily setting aside work in progress
While you are in the middle of working on something complicated, you find an unrelated but obvious and trivial bug. You would like to fix it before continuing. You can use git-stash(1) to save the current state of your work, and after fixing the bug (or, optionally after doing so on a different branch and then coming back), unstash the work-in-progress changes.
After that, you can go back to what you were working on with git stash pop :
Ensuring good performance
On large repositories, Git depends on compression to keep the history information from taking up too much space on disk or in memory. Some Git commands may automatically run git-gc(1), so you don’t have to worry about running it manually. However, compressing a large repository may take a while, so you may want to call gc explicitly to avoid automatic compression kicking in when it is not convenient.
Ensuring reliability
Checking the repository for corruption
The git-fsck(1) command runs a number of self-consistency checks on the repository, and reports on any problems. This may take some time.
Recovering lost changes
Reflogs
Fortunately, Git also keeps a log, called a «reflog», of all the previous values of each branch. So in this case you can still find the old history using, for example,
A separate reflog is kept for the HEAD, so
will show what HEAD pointed to one week ago, not what the current branch pointed to one week ago. This allows you to see the history of what you’ve checked out.
The reflogs are kept by default for 30 days, after which they may be pruned. See git-reflog(1) and git-gc(1) to learn how to control this pruning, and see the «SPECIFYING REVISIONS» section of gitrevisions(7) for details.
Note that the reflog history is very different from normal Git history. While normal history is shared by every repository that works on the same project, the reflog history is not shared: it tells you only about how the branches in your local repository have changed over time.
Examining dangling objects
In some situations the reflog may not be able to save you. For example, suppose you delete a branch, then realize you need the history it contained. The reflog is also deleted; however, if you have not yet pruned the repository, then you may still be able to find the lost commits in the dangling objects that git fsck reports. See the section called “Dangling objects” for the details.
You can examine one of those dangling commits with, for example,
which does what it sounds like: it says that you want to see the commit history that is described by the dangling commit(s), but not the history that is described by all your existing branches and tags. Thus you get exactly the history reachable from that commit that is lost. (And notice that it might not be just one commit: we only report the «tip of the line» as being dangling, but there might be a whole deep and complex commit history that was dropped.)
If you decide you want the history back, you can always create a new reference pointing to it, for example, a new branch:
Other types of dangling objects (blobs and trees) are also possible, and dangling objects can arise in other situations.
Chapter 4. Sharing development with others
Table of Contents
Getting updates with git pull
After you clone a repository and commit a few changes of your own, you may wish to check the original repository for updates and merge them into your own work.
We have already seen how to keep remote-tracking branches up to date with git-fetch(1), and how to merge two branches. So you can merge in changes from the original repository’s master branch with:
However, the git-pull(1) command provides a way to do this in one step:
In fact, if you have master checked out, then this branch has been configured by git clone to get changes from the HEAD branch of the origin repository. So often you can accomplish the above with just a simple
In addition to saving you keystrokes, git pull also helps you by producing a default commit message documenting the branch and repository that you pulled from.
(But note that no such commit will be created in the case of a fast-forward; instead, your branch will just be updated to point to the latest commit from the upstream branch.)
are roughly equivalent.
Submitting patches to a project
If you just have a few changes, the simplest way to submit them may just be to send them as patches in email:
You can then import these into your mail client and send them by hand. However, if you have a lot to send at once, you may prefer to use the git-send-email(1) script to automate the process. Consult the mailing list for your project first to determine their requirements for submitting patches.
Importing patches to a project
Once the index is updated with the results of the conflict resolution, instead of creating a new commit, just run
and Git will create the commit for you and continue applying the remaining patches from the mailbox.
The final result will be a series of commits, one for each patch in the original mailbox, with authorship and commit log message each taken from the message containing each patch.
Public Git repositories
Another way to submit changes to a project is to tell the maintainer of that project to pull the changes from your repository using git-pull(1). In the section «Getting updates with git pull » we described this as a way to get updates from the «main» repository, but it works just as well in the other direction.
If you and the maintainer both have accounts on the same machine, then you can just pull changes from each other’s repositories directly; commands that accept repository URLs as arguments will also accept a local directory name:
For projects with few developers, or for synchronizing a few private repositories, this may be all you need.
However, the more common way to do this is to maintain a separate public repository (usually on a different host) for others to pull changes from. This is usually more convenient, and allows you to cleanly separate private work in progress from publicly visible work.
You will continue to do your day-to-day work in your personal repository, but periodically «push» changes from your personal repository into your public repository, allowing other developers to pull from that repository. So the flow of changes, in a situation where there is one other developer with a public repository, looks like this:
We explain how to do this in the following sections.
Setting up a public repository
Assume your personal repository is in the directory
Next, copy proj.git to the server where you plan to host the public repository. You can use scp, rsync, or whatever is most convenient.
Exporting a Git repository via the Git protocol
This is the preferred method.
If someone else administers the server, they should tell you what directory to put the repository in, and what git:// URL it will appear at. You can then skip to the section «Pushing changes to a public repository», below.
Otherwise, all you need to do is start git-daemon(1); it will listen on port 9418. By default, it will allow access to any directory that looks like a Git directory and contains the magic file git-daemon-export-ok. Passing some directory paths as git daemon arguments will further restrict the exports to those paths.
You can also run git daemon as an inetd service; see the git-daemon(1) man page for details. (See especially the examples section.)
Exporting a git repository via HTTP
The Git protocol gives better performance and reliability, but on a host with a web server set up, HTTP exports may be simpler to set up.
All you need to do is place the newly created bare Git repository in a directory that is exported by the web server, and make some adjustments to give web clients some extra information they need:
(For an explanation of the last two lines, see git-update-server-info(1) and githooks(5).)
(See also setup-git-server-over-http for a slightly more sophisticated setup using WebDAV which also allows pushing over HTTP.)
Pushing changes to a public repository
Note that the two techniques outlined above (exporting via http or git) allow other maintainers to fetch your latest changes, but they do not allow write access, which you will need to update the public repository with the latest changes created in your private repository.
Note that the target of a push is normally a bare repository. You can also push to a repository that has a checked-out working tree, but a push to update the currently checked-out branch is denied by default to prevent confusion. See the description of the receive.denyCurrentBranch option in git-config(1) for details.
which lets you do the same push with just
What to do when a push fails
If a push would not result in a fast-forward of the remote branch, then it will fail with an error like:
This can happen, for example, if you:
You may force git push to perform the update anyway by preceding the branch name with a plus sign:
Normally whenever a branch head in a public repository is modified, it is modified to point to a descendant of the commit that it pointed to before. By forcing a push in this situation, you break that convention. (See the section called “Problems with rewriting history”.)
Nevertheless, this is a common practice for people that need a simple way to publish a work-in-progress patch series, and it is an acceptable compromise as long as you warn other developers that this is how you intend to manage the branch.
It’s also possible for a push to fail in this way when other people have the right to push to the same repository. In that case, the correct solution is to retry the push after first updating your work: either by a pull, or by a fetch followed by a rebase; see the next section and gitcvs-migration(7) for more.
Setting up a shared repository
Another way to collaborate is by using a model similar to that commonly used in CVS, where several developers with special rights all push to and pull from a single shared repository. See gitcvs-migration(7) for instructions on how to set this up.
However, while there is nothing wrong with Git’s support for shared repositories, this mode of operation is not generally recommended, simply because the mode of collaboration that Git supports—by exchanging patches and pulling from public repositories—has so many advantages over the central shared repository:
Allowing web browsing of a repository
The gitweb cgi script provides users an easy way to browse your project’s revisions, file contents and logs without having to install Git. Features like RSS/Atom feeds and blame/annotation details may optionally be enabled.
The git-instaweb(1) command provides a simple way to start browsing the repository using gitweb. The default server when using instaweb is lighttpd.
See the file gitweb/INSTALL in the Git source tree and gitweb(1) for instructions on details setting up a permanent installation with a CGI or Perl capable server.
How to get a Git repository with minimal history
A shallow clone, with its truncated history, is useful when one is interested only in recent history of a project and getting full history from the upstream is expensive.
Merging inside a shallow clone will work as long as a merge base is in the recent history. Otherwise, it will be like merging unrelated histories and may have to result in huge conflicts. This limitation may make such a repository unsuitable to be used in merge based workflows.
Examples
Maintaining topic branches for a Linux subsystem maintainer
This describes how Tony Luck uses Git in his role as maintainer of the IA64 architecture for the Linux kernel.
He uses two public branches:
He also uses a set of temporary branches («topic branches»), each containing a logical grouping of patches.
To set this up, first create your work tree by cloning Linus’s public tree:
Linus’s tree will be stored in the remote-tracking branch named origin/master, and can be updated using git-fetch(1); you can track other public trees using git-remote(1) to set up a «remote» and git-fetch(1) to keep them up to date; see Chapter 1, Repositories and Branches.
These can be easily kept up to date using git-pull(1).
Important note! If you have any local changes in these branches, then this merge will create a commit object in the history (with no local changes Git will simply do a «fast-forward» merge). Many people dislike the «noise» that this creates in the Linux history, so you should avoid doing this capriciously in the release branch, as these noisy commits will become part of the permanent history when you ask Linus to pull from the release branch.
A few configuration variables (see git-config(1)) can make it easy to push both branches to your public tree. (See the section called “Setting up a public repository”.)
Then you can push both the test and release trees using git-push(1):
or push just one of the test and release branches using:
Now to apply some patches from the community. Think of a short snappy name for a branch to hold this patch (or related group of patches), and create a new branch from a recent stable tag of Linus’s branch. Picking a stable base for your branch will: 1) help you: by avoiding inclusion of unrelated and perhaps lightly tested changes 2) help future bug hunters that use git bisect to find problems
Now you apply the patch(es), run some tests, and commit the change(s). If the patch is a multi-part series, then you should apply each as a separate commit to this branch.
When you are happy with the state of this change, you can merge it into the «test» branch in preparation to make it public:
It is unlikely that you would have any conflicts here … but you might if you spent a while on this step and had also pulled new versions from upstream.
Sometime later when enough time has passed and testing done, you can pull the same branch into the release tree ready to go upstream. This is where you see the value of keeping each patch (or patch series) in its own branch. It means that the patches can be moved into the release tree in any order.
After a while, you will have a number of branches, and despite the well chosen names you picked for each of them, you may forget what they are for, or what status they are in. To get a reminder of what changes are in a specific branch, use:
To see whether it has already been merged into the test or release branches, use:
(If this branch has not yet been merged, you will see some log entries. If it has been merged, then there will be no output.)
Once a patch completes the great cycle (moving from test to release, then pulled by Linus, and finally coming back into your local origin/master branch), the branch for this change is no longer needed. You detect this when the output from:
is empty. At this point the branch can be deleted:
Some changes are so trivial that it is not necessary to create a separate branch and then merge into each of the test and release branches. For these changes, just apply directly to the release branch, and then merge that into the test branch.
Here are some of the scripts that simplify all this even further.
Chapter 5. Rewriting history and maintaining patch series
Table of Contents
Normally commits are only added to a project, never taken away or replaced. Git is designed with this assumption, and violating it will cause Git’s merge machinery (for example) to do the wrong thing.
However, there is a situation in which it can be useful to violate this assumption.
Creating the perfect patch series
Suppose you are a contributor to a large project, and you want to add a complicated feature, and to present it to the other developers in a way that makes it easy for them to read your changes, verify that they are correct, and understand why you made each change.
If you present all of your changes as a single patch (or commit), they may find that it is too much to digest all at once.
If you present them with the entire history of your work, complete with mistakes, corrections, and dead ends, they may be overwhelmed.
So the ideal is usually to produce a series of patches such that:
We will introduce some tools that can help you do this, explain how to use them, and then explain some of the problems that can arise because you are rewriting history.
Keeping a patch series up to date using git rebase
You have performed no merges into mywork, so it is just a simple linear sequence of patches on top of origin :
Some more interesting work has been done in the upstream project, and origin has advanced:
At this point, you could use pull to merge your changes back in; the result would create a new merge commit, like this:
However, if you prefer to keep the history in mywork a simple series of commits without any merges, you may instead choose to use git-rebase(1):
and Git will continue applying the rest of the patches.
Rewriting a single commit
We saw in the section called “Fixing a mistake by rewriting history” that you can replace the most recent commit using
which will replace the old commit by a new commit incorporating your changes, giving you a chance to edit the old commit message first. This is useful for fixing typos in your last commit, or for adjusting the patch contents of a poorly staged commit.
If you need to amend commits from deeper in your history, you can use interactive rebase’s edit instruction.
Reordering or selecting from a patch series
Sometimes you want to edit a commit deeper in your history. One approach is to use git format-patch to create a series of patches and then reset the state to before the patches:
Then modify, reorder, or eliminate patches as needed before applying them again with git-am(1):
Using interactive rebases
Rebase your current HEAD on the last commit you want to retain as-is. For example, if you want to reorder the last 5 commits, use:
This will open your editor with a list of steps to be taken to perform your rebase.
As explained in the comments, you can reorder commits, squash them together, edit commit messages, etc. by editing the list. Once you are satisfied, save the list and close your editor, and the rebase will begin.
For a more detailed discussion of the procedure and additional tips, see the «INTERACTIVE MODE» section of git-rebase(1).
Other tools
There are numerous other tools, such as StGit, which exist for the purpose of maintaining a patch series. These are outside of the scope of this manual.
Problems with rewriting history
The primary problem with rewriting the history of a branch has to do with merging. Suppose somebody fetches your branch and merges it into their branch, with a result something like this:
Then suppose you modify the last three commits:
If we examined all this history together in one repository, it will look like:
Git has no way of knowing that the new head is an updated version of the old head; it treats this situation exactly the same as it would if two developers had independently done the work on the old and new heads in parallel. At this point, if someone attempts to merge the new head in to their branch, Git will attempt to merge together the two (old and new) lines of development, instead of trying to replace the old by the new. The results are likely to be unexpected.
You may still choose to publish branches whose history is rewritten, and it may be useful for others to be able to fetch those branches in order to examine or test them, but they should not attempt to pull such branches into their own work.
For true distributed development that supports proper merging, published branches should never be rewritten.
Why bisecting merge commits can be harder than bisecting linear history
The git-bisect(1) command correctly handles history that includes merge commits. However, when the commit that it finds is a merge commit, the user may need to work harder than usual to figure out why that commit introduced a problem.
Imagine this history:
Suppose that on the upper line of development, the meaning of one of the functions that exists at Z is changed at commit X. The commits from Z leading to A change both the function’s implementation and all calling sites that exist at Z, as well as new calling sites they add, to be consistent. There is no bug at A.
Suppose that in the meantime on the lower line of development somebody adds a new calling site for that function at commit Y. The commits from Z leading to B all assume the old semantics of that function and the callers and the callee are consistent with each other. There is no bug at B, either.
Suppose further that the two development lines merge cleanly at C, so no conflict resolution is required.
Nevertheless, the code at C is broken, because the callers added on the lower line of development have not been converted to the new semantics introduced on the upper line of development. So if all you know is that D is bad, that Z is good, and that git-bisect(1) identifies C as the culprit, how will you figure out that the problem is due to this change in semantics?
When the result of a git bisect is a non-merge commit, you should normally be able to discover the problem by examining just that commit. Developers can make this easy by breaking their changes into small self-contained commits. That won’t help in the case above, however, because the problem isn’t obvious from examination of any single commit; instead, a global view of the development is required. To make matters worse, the change in semantics in the problematic function may be just one small part of the changes in the upper line of development.
On the other hand, if instead of merging at C you had rebased the history between Z to B on top of A, you would have gotten this linear history:
Bisecting between Z and D* would hit a single culprit commit Y*, and understanding why Y* was broken would probably be easier.
Partly for this reason, many experienced Git users, even when working on an otherwise merge-heavy project, keep the history linear by rebasing against the latest upstream version before publishing.
Chapter 6. Advanced branch management
Table of Contents
Fetching individual branches
Instead of using git-remote(1), you can also choose just to update one branch at a time, and to store it locally under an arbitrary name:
You can also fetch branches from other repositories; so
will create a new branch named example-master and store in it the branch named master from the repository at the given URL. If you already have a branch named example-master, it will attempt to fast-forward to the commit given by example.com’s master branch. In more detail:
git fetch and fast-forwards
In the previous example, when updating an existing branch, git fetch checks to make sure that the most recent commit on the remote branch is a descendant of the most recent commit on your copy of the branch before updating your copy of the branch to point at the new commit. Git calls this process a fast-forward.
A fast-forward looks something like this:
In some cases it is possible that the new head will not actually be a descendant of the old head. For example, the developer may have realized a serious mistake was made and decided to backtrack, resulting in a situation like:
In this case, git fetch will fail, and print out a warning.
Forcing git fetch to do non-fast-forward updates
If git fetch fails because the new head of a branch is not a descendant of the old head, you may force the update with:
Be aware that commits that the old version of example/master pointed at may be lost, as we saw in the previous section.
Configuring remote-tracking branches
We saw above that origin is just a shortcut to refer to the repository that you originally cloned from. This information is stored in Git configuration variables, which you can see using git-config(1):
If there are other repositories that you also use frequently, you can create similar configuration options to save typing; for example,
After configuring the remote, the following three commands will do the same thing:
See git-config(1) for more details on the configuration options mentioned above and git-fetch(1) for more details on the refspec syntax.
Chapter 7. Git concepts
Table of Contents
Git is built on a small number of simple but powerful ideas. While it is possible to get things done without understanding them, you will find Git much more intuitive if you do.
We start with the most important, the object database and the index.
The Object Database
We already saw in the section called “Understanding History: Commits” that all commits are stored under a 40-digit «object name». In fact, all the information needed to represent the history of a project is stored in objects with such names. In each case the name is calculated by taking the SHA-1 hash of the contents of the object. The SHA-1 hash is a cryptographic hash function. What that means to us is that it is impossible to find two different objects with the same name. This has a number of advantages; among others:
(See the section called “Object storage format” for the details of the object formatting and SHA-1 calculation.)
There are four different types of objects: «blob», «tree», «commit», and «tag».
The object types in some more detail:
Commit Object
As you can see, a commit is defined by:
A commit is usually created by git-commit(1), which creates a commit whose parent is normally the current HEAD, and whose tree is taken from the content currently stored in the index.
Tree Object
The ever-versatile git-show(1) command can also be used to examine tree objects, but git-ls-tree(1) will give you more details:
As you can see, a tree object contains a list of entries, each with a mode, object type, SHA-1 name, and name, sorted by name. It represents the contents of a single directory tree.
The object type may be a blob, representing the contents of a file, or another tree, representing the contents of a subdirectory. Since trees and blobs, like all other objects, are named by the SHA-1 hash of their contents, two trees have the same SHA-1 name if and only if their contents (including, recursively, the contents of all subdirectories) are identical. This allows Git to quickly determine the differences between two related tree objects, since it can ignore any entries with identical object names.
(Note: in the presence of submodules, trees may also have commits as entries. See Chapter 8, Submodules for documentation.)
Note that the files all have mode 644 or 755: Git actually only pays attention to the executable bit.
Blob Object
You can use git-show(1) to examine the contents of a blob; take, for example, the blob in the entry for COPYING from the tree above:
A «blob» object is nothing but a binary blob of data. It doesn’t refer to anything else or have attributes of any kind.
Since the blob is entirely defined by its data, if two files in a directory tree (or in multiple different versions of the repository) have the same contents, they will share the same blob object. The object is totally independent of its location in the directory tree, and renaming a file does not change the object that file is associated with.
Note that any tree or blob object can be examined using git-show(1) with the :
syntax. This can sometimes be useful for browsing the contents of a tree that is not currently checked out.
Trust
If you receive the SHA-1 name of a blob from one source, and its contents from another (possibly untrusted) source, you can still trust that those contents are correct as long as the SHA-1 name agrees. This is because the SHA-1 is designed so that it is infeasible to find different contents that produce the same hash.
Similarly, you need only trust the SHA-1 name of a top-level tree object to trust the contents of the entire directory that it refers to, and if you receive the SHA-1 name of a commit from a trusted source, then you can easily verify the entire history of commits reachable through parents of that commit, and all of those contents of the trees referred to by those commits.
So to introduce some real trust in the system, the only thing you need to do is to digitally sign just one special note, which includes the name of a top-level commit. Your digital signature shows others that you trust that commit, and the immutability of the history of commits tells others that they can trust the whole history.
In other words, you can easily validate a whole archive by just sending out a single email that tells the people the name (SHA-1 hash) of the top commit, and digitally sign that email using something like GPG/PGP.
To assist in this, Git also provides the tag object…
Tag Object
A tag object contains an object, object type, tag name, the name of the person («tagger») who created the tag, and a message, which may contain a signature, as can be seen using git-cat-file(1):
See the git-tag(1) command to learn how to create and verify tag objects. (Note that git-tag(1) can also be used to create «lightweight tags», which are not tag objects at all, but just simple references whose names begin with refs/tags/ ).
How Git stores objects efficiently: pack files
Unfortunately this system becomes inefficient once a project has a lot of objects. Try this on an old project:
The first number is the number of objects which are kept in individual files. The second is the amount of space taken up by those «loose» objects.
You can save space and make Git faster by moving these loose objects in to a «pack file», which stores a group of objects in an efficient compressed format; the details of how pack files are formatted can be found in pack format.
To put the loose objects into a pack, just run git repack:
Although the object files are gone, any commands that refer to those objects will work exactly as they did before.
The git-gc(1) command performs packing, pruning, and more for you, so is normally the only high-level command you need.
Dangling objects
The git-fsck(1) command will sometimes complain about dangling objects. They are not a problem.
The most common cause of dangling objects is that you’ve rebased a branch, or you have pulled from somebody else who rebased a branch—see Chapter 5, Rewriting history and maintaining patch series. In that case, the old head of the original branch still exists, as does everything it pointed to. The branch pointer itself just doesn’t, since you replaced it with another one.
There are also other situations that cause dangling objects. For example, a «dangling blob» may arise because you did a git add of a file, but then, before you actually committed it and made it part of the bigger picture, you changed something else in that file and committed that updated thing—the old state that you added originally ends up not being pointed to by any commit or tree, so it’s now a dangling blob object.
Similarly, when the «ort» merge strategy runs, and finds that there are criss-cross merges and thus more than one merge base (which is fairly unusual, but it does happen), it will generate one temporary midway tree (or possibly even more, if you had lots of criss-crossing merges and more than two merge bases) as a temporary internal merge base, and again, those are real objects, but the end result will not end up pointing to them, so they end up «dangling» in your repository.
Generally, dangling objects aren’t anything to worry about. They can even be very useful: if you screw something up, the dangling objects can be how you recover your old tree (say, you did a rebase, and realized that you really didn’t want to—you can look at what dangling objects you have, and decide to reset your head to some old dangling state).
For commits, you can just use:
This asks for all the history reachable from the given commit but not from any branch, tag, or other reference. If you decide it’s something you want, you can always create a new reference to it, e.g.,
For blobs and trees, you can’t do the same, but you can still examine them. You can just do
to show what the contents of the blob were (or, for a tree, basically what the ls for that directory was), and that may give you some idea of what the operation was that left that dangling object.
Usually, dangling blobs and trees aren’t very interesting. They’re almost always the result of either being a half-way mergebase (the blob will often even have the conflict markers from a merge in it, if you have had conflicting merges that you fixed up by hand), or simply because you interrupted a git fetch with ^C or something like that, leaving some of the new objects in the object database, but just dangling and useless.
Anyway, once you are sure that you’re not interested in any dangling state, you can just prune all unreachable objects:
and they’ll be gone. (You should only run git prune on a quiescent repository—it’s kind of like doing a filesystem fsck recovery: you don’t want to do that while the filesystem is mounted. git prune is designed not to cause any harm in such cases of concurrent accesses to a repository but you might receive confusing or scary messages.)
Recovering from repository corruption
By design, Git treats data trusted to it with caution. However, even in the absence of bugs in Git itself, it is still possible that hardware or operating system errors could corrupt data.
The first defense against such problems is backups. You can back up a Git directory using clone, or just using cp, tar, or any other backup mechanism.
As a last resort, you can search for the corrupted objects and attempt to replace them by hand. Back up your repository before attempting this in case you corrupt things even more in the process.
We’ll assume that the problem is a single missing or corrupted blob, which is sometimes a solvable problem. (Recovering missing trees and especially commits is much harder).
Before starting, verify that there is corruption, and figure out where it is with git-fsck(1); this may be time-consuming.
Assume the output looks like this:
which will create and store a blob object with the contents of somedirectory/myfile, and output the SHA-1 of that object. if you’re extremely lucky it might be 4b9458b3786228369c63936db65827de3cc06200, in which case you’ve guessed right, and the corruption is fixed!
Otherwise, you need more information. How do you tell which version of the file has been lost?
The easiest way to do this is with:
Because you’re asking for raw output, you’ll now get something like
This tells you that the immediately following version of the file was «newsha», and that the immediately preceding version was «oldsha». You also know the commit messages that went with the change from oldsha to 4b9458b and with the change from 4b9458b to newsha.
If you’ve been committing small enough changes, you may now have a good shot at reconstructing the contents of the in-between state 4b9458b.
If you can do that, you can now recreate the missing object with
and your repository is good again!
and just looked for the sha of the missing object (4b9458b) in that whole thing. It’s up to you—Git does have a lot of information, it is just missing one particular blob version.
The index
Note that in older documentation you may see the index called the «current directory cache» or just the «cache». It has three important properties:
The index contains all the information necessary to generate a single (uniquely determined) tree object.
For example, running git-commit(1) generates this tree object from the index, stores it in the object database, and uses it as the tree object associated with the new commit.
The index enables fast comparisons between the tree object it defines and the working tree.
It does this by storing some additional data for each entry (such as the last modified time). This data is not displayed above, and is not stored in the created tree object, but it can be used to determine quickly which files in the working directory differ from what was stored in the index, and thus save Git from having to read all of the data from such files to look for changes.
It can efficiently represent information about merge conflicts between different tree objects, allowing each pathname to be associated with sufficient information about the trees involved that you can create a three-way merge between them.
We saw in the section called “Getting conflict-resolution help during a merge” that during a merge the index can store multiple versions of a single file (called «stages»). The third column in the git-ls-files(1) output above is the stage number, and will take on values other than 0 for files with merge conflicts.
The index is thus a sort of temporary staging area, which is filled with a tree which you are in the process of working on.
If you blow the index away entirely, you generally haven’t lost any information as long as you have the name of the tree that it described.
Chapter 8. Submodules
Table of Contents
Large projects are often composed of smaller, self-contained modules. For example, an embedded Linux distribution’s source tree would include every piece of software in the distribution with some local modifications; a movie player might need to build against a specific, known-working version of a decompression library; several independent programs might all share the same build scripts.
With centralized revision control systems this is often accomplished by including every module in one single repository. Developers can check out all modules or only the modules they need to work with. They can even modify files across several modules in a single commit while moving things around or updating APIs and translations.
Git does not allow partial checkouts, so duplicating this approach in Git would force developers to keep a local copy of modules they are not interested in touching. Commits in an enormous checkout would be slower than you’d expect as Git would have to scan every directory for changes. If modules have a lot of local history, clones would take forever.
On the plus side, distributed revision control systems can much better integrate with external sources. In a centralized model, a single arbitrary snapshot of the external project is exported from its own revision control and then imported into the local revision control on a vendor branch. All the history is hidden. With distributed revision control you can clone the entire external history and much more easily follow development and re-merge local changes.
Git’s submodule support allows a repository to contain, as a subdirectory, a checkout of an external project. Submodules maintain their own identity; the submodule support just stores the submodule repository location and commit ID, so other developers who clone the containing project («superproject») can easily clone all the submodules at the same revision. Partial checkouts of the superproject are possible: you can tell Git to clone none, some or all of the submodules.
The git-submodule(1) command is available since Git 1.5.3. Users with Git 1.5.2 can look up the submodule commits in the repository and manually check them out; earlier versions won’t recognize the submodules at all.
To see how submodule support works, create four example repositories that can be used later as a submodule:
Now create the superproject and add all the submodules:
Do not use local URLs here if you plan to publish your superproject!
See what files git submodule created:
The git submodule add
command does a couple of things:
Commit the superproject:
Now clone the superproject:
The submodule directories are there, but they’re empty:
Now use git submodule update to clone the repositories and check out the commits specified in the superproject:
One major difference between git submodule update and git submodule add is that git submodule update checks out a specific commit, rather than the tip of a branch. It’s like checking out a tag: the head is detached, so you’re not working on a branch.
If you want to make a change within a submodule and you have a detached head, then you should create or checkout a branch, make your changes, publish the change within the submodule, and then update the superproject to reference the new commit:
You have to run git submodule update after git pull if you want to update submodules, too.
Pitfalls with submodules
Always publish the submodule change before publishing the change to the superproject that references it. If you forget to publish the submodule change, others won’t be able to clone the repository:
You also should not rewind branches in a submodule beyond commits that were ever recorded in any superproject.
It’s not safe to run git submodule update if you’ve made and committed changes within a submodule without checking out a branch first. They will be silently overwritten:
The changes are still visible in the submodule’s reflog.
If you have uncommitted changes in your submodule working tree, git submodule update will not overwrite them. Instead, you get the usual warning about not being able switch from a dirty branch.
Chapter 9. Low-level Git operations
Table of Contents
Many of the higher-level commands were originally implemented as shell scripts using a smaller core of low-level Git commands. These can still be useful when doing unusual things with Git, or just as a way to understand its inner workings.
Object access and manipulation
The git-cat-file(1) command can show the contents of any object, though the higher-level git-show(1) is usually more useful.
The git-commit-tree(1) command allows constructing commits with arbitrary parents and trees.
A tree can be created with git-write-tree(1) and its data can be accessed by git-ls-tree(1). Two trees can be compared with git-diff-tree(1).
A tag is created with git-mktag(1), and the signature can be verified by git-verify-tag(1), though it is normally simpler to use git-tag(1) for both.
The Workflow
High-level operations such as git-commit(1) and git-restore(1) work by moving data between the working tree, the index, and the object database. Git provides low-level operations which perform each of these steps individually.
Generally, all Git operations work on the index file. Some operations work purely on the index file (showing the current state of the index), but most operations move data between the index file and either the database or the working directory. Thus there are four main combinations:
working directory → index
The git-update-index(1) command updates the index with information from the working directory. You generally update the index information by just specifying the filename you want to update, like so:
but to avoid common mistakes with filename globbing etc., the command will not normally add totally new entries or remove old entries, i.e. it will normally just update existing cache entries.
The previously introduced git-add(1) is just a wrapper for git-update-index(1).
index → object database
You write your current index file to a «tree» object with the program
that doesn’t come with any options—it will just write out the current index into the set of tree objects that describe that state, and it will return the name of the resulting top-level tree. You can use that tree to re-generate the index at any time by going in the other direction:
object database → index
You read a «tree» file from the object database, and use that to populate (and overwrite—don’t do this if your index contains any unsaved state that you might want to restore later!) your current index. Normal operation is just
and your index file will now be equivalent to the tree that you saved earlier. However, that is only your index file: your working directory contents have not been modified.
index → working directory
You update your working directory from the index by «checking out» files. This is not a very common operation, since normally you’d just keep your files updated, and rather than write to your working directory, you’d tell the index files about the changes in your working directory (i.e. git update-index ).
However, if you decide to jump to a new version, or check out somebody else’s version, or just restore a previous tree, you’d populate your index file with read-tree, and then you need to check out the result with
Finally, there are a few odds and ends which are not purely moving from one representation to the other:
Tying it all together
Normally a «commit» has one parent: the previous state of the tree before a certain change was made. However, sometimes it can have two or more parent commits, in which case we call it a «merge», due to the fact that such a commit brings together («merges») two or more previous states represented by other commits.
In other words, while a «tree» represents a particular directory state of a working directory, a «commit» represents that state in time, and explains how we got there.
You create a commit object by giving it the tree that describes the state at the time of the commit, and a list of parents:
and then giving the reason for the commit on stdin (either through redirection from a pipe or file, or by just typing it at the tty).
Here is a picture that illustrates how various pieces fit together:
Examining the data
You can examine the data represented in the object database and the index with various helper tools. For every object, you can use git-cat-file(1) to examine details about the object:
shows the type of the object, and once you have the type (which is usually implicit in where you find the object), you can use
to see what the top commit was.
Merging multiple trees
Git can help you perform a three-way merge, which can in turn be used for a many-way merge by repeating the merge procedure several times. The usual situation is that you only do one three-way merge (reconciling two lines of history) and commit the result, but if you like to, you can merge several branches in one go.
To perform a three-way merge, you start with the two commits you want to merge, find their closest common parent (a third commit), and compare the trees corresponding to these three commits.
To get the «base» for the merge, look up the common parent of two commits:
This prints the name of a commit they are both based on. You should now look up the tree objects of those commits, which you can easily do with
since the tree object information is always the first line in a commit object.
Once you know the three trees you are going to merge (the one «original» tree, aka the common tree, and the two «result» trees, aka the branches you want to merge), you do a «merge» read into the index. This will complain if it has to throw away your old index contents, so you should make sure that you’ve committed those—in fact you would normally always do a merge against your last commit (which should thus match what you have in your current index anyway).
To do the merge, do
Merging multiple trees, continued
Sadly, many merges aren’t trivial. If there are files that have been added, moved or removed, or if both branches have modified the same file, you will be left with an index tree that contains «merge entries» in it. Such an index tree can NOT be written out to a tree object, and you will have to resolve any such merge clashes using other tools before you can write out the result.
This would leave the merge result in hello.c
2 file, along with conflict markers if there are conflicts. After verifying the merge result makes sense, you can tell Git what the final merge result for this file is by:
When a path is in the «unmerged» state, running git update-index for that path tells Git to mark the path resolved.
The above is the description of a Git merge at the lowest level, to help you understand what conceptually happens under the hood. In practice, nobody, not even Git itself, runs git cat-file three times for this. There is a git merge-index program that extracts the stages to temporary files and calls a «merge» script on it:
Chapter 10. Hacking Git
Table of Contents
This chapter covers internal details of the Git implementation which probably only Git developers need to understand.
Object storage format
All objects have a statically determined «type» which identifies the format of the object (i.e. how it is used, and how it can refer to other objects). There are currently four different object types: «blob», «tree», «commit», and «tag».
The structured objects can further have their structure and connectivity to other objects verified. This is generally done with the git fsck program, which generates a full dependency graph of all objects, and verifies their internal consistency (in addition to just verifying their superficial consistency through the hash).
A birds-eye view of Git’s source code
It is not always easy for new developers to find their way through Git’s source code. This section gives you a little guidance to show where to start.
A good place to start is with the contents of the initial commit, with:
The initial revision lays the foundation for almost everything Git has today, but is small enough to read in one sitting.
Note that terminology has changed since that revision. For example, the README in that revision uses the word «changeset» to describe what we now call a commit.
In the early days, Git (in the tradition of UNIX) was a bunch of programs which were extremely simple, and which you used in scripts, piping the output of one into another. This turned out to be good for initial development, since it was easier to test new things. However, recently many of these parts have become builtins, and some of the core has been «libified», i.e. put into libgit.a for performance, portability reasons, and to avoid code duplication.
Now is a good point to take a break to let this information sink in.
This is just to get you into the groove for the most libified part of Git: the revision walker.
Basically, the initial version of git log was a shell script:
What does this mean?
git rev-parse is not as important any more; it was only used to filter out options that were relevant for the different plumbing commands that were called by the script.
If you are interested in more details of the revision walking process, just have a look at the first implementation of cmd_log() ; call git show v1.3.0
4 and scroll down to that function (note that you no longer need to call setup_pager() directly).
git log looks more complicated in C than it does in the original script, but that allows for a much greater flexibility and performance.
Here again it is a good point to take a pause.
Lesson three is: study the code. Really, it is the best way to learn about the organization of Git (after you know the basic concepts).
Two things are interesting here:
You will see both of these things throughout the code.
Now, for the meat:
This is how you read a blob (actually, not only a blob, but any type of object). To know how the function read_object_with_reference() actually works, find the source code for it (something like git grep read_object_with | grep «:[a-z]» in the Git repository), and read the source.
To find out how the result can be used, just read on in cmd_cat_file() :
In the pager ( less ), just search for «bundle», go a few lines back, and see that it is in commit 18449ab0. Now just copy this object name, and paste it into the command line
Another example: Find out what to do in order to make some script a builtin:
You see, Git is actually the best tool to find out about the source of Git itself!
Chapter 11. Git Glossary
Table of Contents
Git explained
As a noun: A single point in the Git history; the entire history of a project is represented as a set of interrelated commits. The word «commit» is often used by Git in the same places other revision control systems use the words «revision» or «version». Also used as a short hand for commit object.
As a verb: The action of storing a new snapshot of the project’s state in the Git history, by creating a new commit representing the current state of the index and advancing HEAD to point at the new commit.
commit object An object which contains the information about a particular revision, such as parents, committer, author, date and the tree object which corresponds to the top directory of the stored revision. commit-ish (also committish) A commit object or an object that can be recursively dereferenced to a commit object. The following are all commit-ishes: a commit object, a tag object that points to a commit object, a tag object that points to a tag object that points to a commit object, etc. core Git Fundamental data structures and utilities of Git. Exposes only limited source code management tools. DAG Directed acyclic graph. The commit objects form a directed acyclic graph, because they have parents (directed), and the graph of commit objects is acyclic (there is no chain which begins and ends with the same object). dangling object An unreachable object which is not reachable even from other unreachable objects; a dangling object has no references to it from any reference or object in the repository. detached HEAD
Normally the HEAD stores the name of a branch, and commands that operate on the history HEAD represents operate on the history leading to the tip of the branch the HEAD points at. However, Git also allows you to check out an arbitrary commit that isn’t necessarily the tip of any particular branch. The HEAD in such a state is called «detached».
Note that the grafts mechanism is outdated and can lead to problems transferring objects between repositories; see git-replace(1) for a more flexible and robust system to do the same thing.
As a verb: To bring the contents of another branch (possibly from an external repository) into the current branch. In the case where the merged-in branch is from a different repository, this is done by first fetching the remote branch and then merging the result into the current branch. This combination of fetch and merge operations is called a pull. Merging is performed by an automatic process that identifies changes made since the branches diverged, and then applies all those changes together. In cases where changes conflict, manual intervention may be required to complete the merge.
As a noun: unless it is a fast-forward, a successful merge results in the creation of a new commit representing the result of the merge, and having as parents the tips of the merged branches. This commit is referred to as a «merge commit», or sometimes just a «merge».
Pattern used to limit paths in Git commands.
Pathspecs are used on the command line of «git ls-files», «git ls-tree», «git add», «git grep», «git diff», «git checkout», and many other commands to limit the scope of operations to some subset of the tree or working tree. See the documentation of each command for whether paths are relative to the current directory or toplevel. The pathspec syntax is as follows:
A pathspec that begins with a colon : has special meaning. In the short form, the leading colon : is followed by zero or more «magic signature» letters (which optionally is terminated by another colon : ), and the remainder is the pattern to match against the path. The «magic signature» consists of ASCII symbols that are neither alphanumeric, glob, regex special characters nor colon. The optional colon that terminates the «magic signature» can be omitted if the pattern begins with a character that does not belong to «magic signature» symbol set and is not a colon.
A pathspec with only a colon means «there is no pathspec». This form should not be combined with other pathspec.
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».
Two consecutive asterisks (» ** «) in patterns matched against full pathname may have special meaning:
Other consecutive asterisks are considered invalid.
Glob magic is incompatible with literal magic.
After attr: comes a space separated list of «attribute requirements», all of which must be met in order for the path to be considered a match; this is in addition to the usual non-magic pathspec pattern matching. See gitattributes(5).
Each of the attribute requirements for the path takes one of these forms:
Note that when matching against a tree object, attributes are still obtained from working tree, not from the given tree object.
A name that begins with refs/ (e.g. refs/heads/master ) that points to an object name or another ref (the latter is called a symbolic ref). For convenience, a ref can sometimes be abbreviated when used as an argument to a Git command; see gitrevisions(7) for details. Refs are stored in the repository.
The ref namespace is hierarchical. Different subhierarchies are used for different purposes (e.g. the refs/heads/ hierarchy is used to represent local branches).
Источники информации:
- http://stackoverflow.com/questions/26984847/how-to-update-local-repo-with-master
- http://stackoverflow.com/questions/43205981/git-how-to-update-local-repository-and-keep-my-changes
- http://www.neonscience.org/resources/learning-hub/tutorials/git-setup-remote
- http://git.github.io/htmldocs/user-manual.html