diff --git a/A-git-in-other-environments.asc b/A-git-in-other-environments.asc index b8346be7..a536b80a 100644 --- a/A-git-in-other-environments.asc +++ b/A-git-in-other-environments.asc @@ -1,4 +1,4 @@ -[#A-git-in-other-environments] +[[A-git-in-other-environments]] [appendix] == Git em Outros Ambientes @@ -13,6 +13,11 @@ include::book/A-git-in-other-environments/sections/visualstudio.asc[] include::book/A-git-in-other-environments/sections/eclipse.asc[] +include::book/A-git-in-other-environments/sections/visualstudiocode.asc[] + +include::book/A-git-in-other-environments/sections/jetbrainsides.asc[] + +include::book/A-git-in-other-environments/sections/sublimetext.asc[] include::book/A-git-in-other-environments/sections/bash.asc[] diff --git a/B-embedding-git.asc b/B-embedding-git-in-your-applications.asc similarity index 60% rename from B-embedding-git.asc rename to B-embedding-git-in-your-applications.asc index 85c46d50..f3e60297 100644 --- a/B-embedding-git.asc +++ b/B-embedding-git-in-your-applications.asc @@ -1,14 +1,19 @@ -[#B-embedding-git] +[[B-embedding-git-in-your-applications]] [appendix] == Embedding Git in your Applications If your application is for developers, chances are good that it could benefit from integration with source control. Even non-developer applications, such as document editors, could potentially benefit from version-control features, and Git's model works very well for many different scenarios. -If you need to integrate Git with your application, you have essentially three choices: spawning a shell and using the Git command-line tool; Libgit2; and JGit. +If you need to integrate Git with your application, you have essentially two options: spawn a shell and call the `git` command-line program, or embed a Git library into your application. +Here we'll cover command-line integration and several of the most popular embeddable Git libraries. include::book/B-embedding-git/sections/command-line.asc[] include::book/B-embedding-git/sections/libgit2.asc[] include::book/B-embedding-git/sections/jgit.asc[] + +include::book/B-embedding-git/sections/go-git.asc[] + +include::book/B-embedding-git/sections/dulwich.asc[] diff --git a/C-git-commands.asc b/C-git-commands.asc index aeaad77a..3e3523ef 100644 --- a/C-git-commands.asc +++ b/C-git-commands.asc @@ -1,4 +1,4 @@ -[#C-git-commands] +[[C-git-commands]] [appendix] == Git Commands @@ -8,6 +8,13 @@ However, this leaves us with examples of usage of the commands somewhat scattere In this appendix, we'll go through all the Git commands we addressed throughout the book, grouped roughly by what they're used for. We'll talk about what each command very generally does and then point out where in the book you can find us having used it. +[TIP] +==== +You can abbreviate long options. +For example, you can type in `git commit --a`, which acts as if you typed `git commit --amend`. +This only works when the letters after `--` are unique for one option. +Do use the full option when writing scripts. +==== === Setup and Config @@ -22,25 +29,62 @@ There are several files this command will read from and write to so you can set The `git config` command has been used in nearly every chapter of the book. -In <> we used it to specify our name, email address and editor preference before we even got started using Git. - -In <> we showed how you could use it to create shorthand commands that expand to long option sequences so you don't have to type them every time. - -In <> we used it to make `--rebase` the default when you run `git pull`. - -In <> we used it to set up a default store for your HTTP passwords. - -In <> we showed how to set up smudge and clean filters on content coming in and out of Git. - -Finally, basically the entirety of <> is dedicated to the command. +In <> we used it to specify our name, email address and editor preference before we even got started using Git. + +In <> we showed how you could use it to create shorthand commands that expand to long option sequences so you don't have to type them every time. + +In <> we used it to make `--rebase` the default when you run `git pull`. + +In <> we used it to set up a default store for your HTTP passwords. + +In <> we showed how to set up smudge and clean filters on content coming in and out of Git. + +Finally, basically the entirety of <> is dedicated to the command. + +[[ch_core_editor]] +==== git config core.editor commands + +Accompanying the configuration instructions in <>, many editors can be set as follows: + +.Exhaustive list of `core.editor` configuration commands +[cols="1,2",options="header"] +|============================== +|Editor | Configuration command +|Atom |`git config --global core.editor "atom --wait"` +|BBEdit (macOS, with command line tools) |`git config --global core.editor "bbedit -w"` +|Emacs |`git config --global core.editor emacs` +|Gedit (Linux) |`git config --global core.editor "gedit --wait --new-window"` +|Gvim (Windows 64-bit) |`git config --global core.editor "'C:\Program Files\Vim\vim72\gvim.exe' --nofork '%*'"` (Also see note below) +|Helix |`git config --global core.editor "hx"` +|Kate (Linux) |`git config --global core.editor "kate --block"` +|nano |`git config --global core.editor "nano -w"` +|Notepad (Windows 64-bit) |`git config core.editor notepad` +|Notepad++ (Windows 64-bit) |`git config --global core.editor "'C:\Program Files\Notepad+\+\notepad++.exe' -multiInst -notabbar -nosession -noPlugin"` (Also see note below) +|Scratch (Linux)|`git config --global core.editor "scratch-text-editor"` +|Sublime Text (macOS) |`git config --global core.editor "/Applications/Sublime\ Text.app/Contents/SharedSupport/bin/subl --new-window --wait"` +|Sublime Text (Windows 64-bit) |`git config --global core.editor "'C:\Program Files\Sublime Text 3\sublime_text.exe' -w"` (Also see note below) +|TextEdit (macOS)|`git config --global core.editor "open --wait-apps --new -e"` +|Textmate |`git config --global core.editor "mate -w"` +|Textpad (Windows 64-bit) |`git config --global core.editor "'C:\Program Files\TextPad 5\TextPad.exe' -m"` (Also see note below) +|UltraEdit (Windows 64-bit) | `git config --global core.editor Uedit32` +|Vim |`git config --global core.editor "vim --nofork"` +|Visual Studio Code |`git config --global core.editor "code --wait"` +|VSCodium (Free/Libre Open Source Software Binaries of VSCode) | `git config --global core.editor "codium --wait"` +|WordPad |`git config --global core.editor "'C:\Program Files\Windows NT\Accessories\wordpad.exe'"` +|Xi | `git config --global core.editor "xi --wait"` +|============================== + +[NOTE] +==== +If you have a 32-bit editor on a Windows 64-bit system, the program will be installed in `C:\Program Files (x86)\` rather than `C:\Program Files\` as in the table above. +==== ==== git help The `git help` command is used to show you all the documentation shipped with Git about any command. While we're giving a rough overview of most of the more popular ones in this appendix, for a full listing of all of the possible options and flags for every command, you can always run `git help `. -We introduced the `git help` command in <> and showed you how to use it to find more information about the `git shell` in <>. - +We introduced the `git help` command in <> and showed you how to use it to find more information about the `git shell` in <>. === Getting and Creating Projects @@ -51,13 +95,13 @@ One is to copy it from an existing repository on the network or elsewhere and th To take a directory and turn it into a new Git repository so you can start version controlling it, you can simply run `git init`. -We first introduce this in <>, where we show creating a brand new repository to start working with. +We first introduce this in <>, where we show creating a brand new repository to start working with. -We talk briefly about how you can change the default branch from ``master'' in <>. +We talk briefly about how you can change the default branch name from "`master`" in <>. -We use this command to create an empty bare repository for a server in <>. +We use this command to create an empty bare repository for a server in <>. -Finally, we go through some of the details of what it actually does behind the scenes in <>. +Finally, we go through some of the details of what it actually does behind the scenes in <>. ==== git clone @@ -66,36 +110,35 @@ It creates a new directory, goes into it and runs `git init` to make it an empty The `git clone` command is used in dozens of places throughout the book, but we'll just list a few interesting places. -It's basically introduced and explained in <>, where we go through a few examples. +It's basically introduced and explained in <>, where we go through a few examples. -In <> we look at using the `--bare` option to create a copy of a Git repository with no working directory. +In <> we look at using the `--bare` option to create a copy of a Git repository with no working directory. -In <> we use it to unbundle a bundled Git repository. +In <> we use it to unbundle a bundled Git repository. -Finally, in <> we learn the `--recursive` option to make cloning a repository with submodules a little simpler. +Finally, in <> we learn the `--recurse-submodules` option to make cloning a repository with submodules a little simpler. Though it's used in many other places through the book, these are the ones that are somewhat unique or where it is used in ways that are a little different. - === Basic Snapshotting For the basic workflow of staging content and committing it to your history, there are only a few basic commands. ==== git add -The `git add` command adds content from the working directory into the staging area (or ``index'') for the next commit. +The `git add` command adds content from the working directory into the staging area (or "`index`") for the next commit. When the `git commit` command is run, by default it only looks at this staging area, so `git add` is used to craft what exactly you would like your next commit snapshot to look like. This command is an incredibly important command in Git and is mentioned or used dozens of times in this book. We'll quickly cover some of the unique uses that can be found. -We first introduce and explain `git add` in detail in <>. +We first introduce and explain `git add` in detail in <>. -We mention how to use it to resolve merge conflicts in <>. +We mention how to use it to resolve merge conflicts in <>. -We go over using it to interactively stage only specific parts of a modified file in <>. +We go over using it to interactively stage only specific parts of a modified file in <>. -Finally, we emulate it at a low level in <>, so you can get an idea of what it's doing behind the scenes. +Finally, we emulate it at a low level in <>, so you can get an idea of what it's doing behind the scenes. ==== git status @@ -103,7 +146,7 @@ The `git status` command will show you the different states of files in your wor Which files are modified and unstaged and which are staged but not yet committed. In its normal form, it also will show you some basic hints on how to move files between these stages. -We first cover `status` in <>, both in its basic and simplified forms. +We first cover `status` in <>, both in its basic and simplified forms. While we use it throughout the book, pretty much everything you can do with the `git status` command is covered there. ==== git diff @@ -111,36 +154,36 @@ While we use it throughout the book, pretty much everything you can do with the The `git diff` command is used when you want to see differences between any two trees. This could be the difference between your working environment and your staging area (`git diff` by itself), between your staging area and your last commit (`git diff --staged`), or between two commits (`git diff master branchB`). -We first look at the basic uses of `git diff` in <>, where we show how to see what changes are staged and which are not yet staged. +We first look at the basic uses of `git diff` in <>, where we show how to see what changes are staged and which are not yet staged. -We use it to look for possible whitespace issues before committing with the `--check` option in <>. +We use it to look for possible whitespace issues before committing with the `--check` option in <>. -We see how to check the differences between branches more effectively with the `git diff A...B` syntax in <>. +We see how to check the differences between branches more effectively with the `git diff A...B` syntax in <>. -We use it to filter out whitespace differences with `-b` and how to compare different stages of conflicted files with `--theirs`, `--ours` and `--base` in <>. +We use it to filter out whitespace differences with `-b` and how to compare different stages of conflicted files with `--theirs`, `--ours` and `--base` in <>. -Finally, we use it to effectively compare submodule changes with `--submodule` in <>. +Finally, we use it to effectively compare submodule changes with `--submodule` in <>. ==== git difftool The `git difftool` command simply launches an external tool to show you the difference between two trees in case you want to use something other than the built in `git diff` command. -We only briefly mention this in <>. +We only briefly mention this in <>. ==== git commit The `git commit` command takes all the file contents that have been staged with `git add` and records a new permanent snapshot in the database and then moves the branch pointer on the current branch up to it. -We first cover the basics of committing in <>. +We first cover the basics of committing in <>. There we also demonstrate how to use the `-a` flag to skip the `git add` step in daily workflows and how to use the `-m` flag to pass a commit message in on the command line instead of firing up an editor. -In <> we cover using the `--amend` option to redo the most recent commit. +In <> we cover using the `--amend` option to redo the most recent commit. -In <>, we go into much more detail about what `git commit` does and why it does it like that. +In <>, we go into much more detail about what `git commit` does and why it does it like that. -We looked at how to sign commits cryptographically with the `-S` flag in <>. +We looked at how to sign commits cryptographically with the `-S` flag in <>. -Finally, we take a look at what the `git commit` command does in the background and how it's actually implemented in <>. +Finally, we take a look at what the `git commit` command does in the background and how it's actually implemented in <>. ==== git reset @@ -148,34 +191,34 @@ The `git reset` command is primarily used to undo things, as you can possibly te It moves around the `HEAD` pointer and optionally changes the `index` or staging area and can also optionally change the working directory if you use `--hard`. This final option makes it possible for this command to lose your work if used incorrectly, so make sure you understand it before using it. -We first effectively cover the simplest use of `git reset` in <>, where we use it to unstage a file we had run `git add` on. +We first effectively cover the simplest use of `git reset` in <>, where we use it to unstage a file we had run `git add` on. -We then cover it in quite some detail in <>, which is entirely devoted to explaining this command. +We then cover it in quite some detail in <>, which is entirely devoted to explaining this command. -We use `git reset --hard` to abort a merge in <>, where we also use `git merge --abort`, which is a bit of a wrapper for the `git reset` command. +We use `git reset --hard` to abort a merge in <>, where we also use `git merge --abort`, which is a bit of a wrapper for the `git reset` command. ==== git rm The `git rm` command is used to remove files from the staging area and working directory for Git. It is similar to `git add` in that it stages a removal of a file for the next commit. -We cover the `git rm` command in some detail in <>, including recursively removing files and only removing files from the staging area but leaving them in the working directory with `--cached`. +We cover the `git rm` command in some detail in <>, including recursively removing files and only removing files from the staging area but leaving them in the working directory with `--cached`. -The only other differing use of `git rm` in the book is in <> where we briefly use and explain the `--ignore-unmatch` when running `git filter-branch`, which simply makes it not error out when the file we are trying to remove doesn't exist. +The only other differing use of `git rm` in the book is in <> where we briefly use and explain the `--ignore-unmatch` when running `git filter-branch`, which simply makes it not error out when the file we are trying to remove doesn't exist. This can be useful for scripting purposes. ==== git mv The `git mv` command is a thin convenience command to move a file and then run `git add` on the new file and `git rm` on the old file. -We only briefly mention this command in <>. +We only briefly mention this command in <>. ==== git clean The `git clean` command is used to remove unwanted files from your working directory. This could include removing temporary build artifacts or merge conflict files. -We cover many of the options and scenarios in which you might used the clean command in <>. +We cover many of the options and scenarios in which you might used the clean command in <>. === Branching and Merging @@ -187,47 +230,47 @@ The `git branch` command is actually something of a branch management tool. It can list the branches you have, create a new branch, delete branches and rename branches. Most of <> is dedicated to the `branch` command and it's used throughout the entire chapter. -We first introduce it in <> and we go through most of its other features (listing and deleting) in <>. +We first introduce it in <> and we go through most of its other features (listing and deleting) in <>. -In <> we use the `git branch -u` option to set up a tracking branch. +In <> we use the `git branch -u` option to set up a tracking branch. -Finally, we go through some of what it does in the background in <>. +Finally, we go through some of what it does in the background in <>. ==== git checkout The `git checkout` command is used to switch branches and check content out into your working directory. -We first encounter the command in <> along with the `git branch` command. +We first encounter the command in <> along with the `git branch` command. -We see how to use it to start tracking branches with the `--track` flag in <>. +We see how to use it to start tracking branches with the `--track` flag in <>. -We use it to reintroduce file conflicts with `--conflict=diff3` in <>. +We use it to reintroduce file conflicts with `--conflict=diff3` in <>. -We go into closer detail on its relationship with `git reset` in <>. +We go into closer detail on its relationship with `git reset` in <>. -Finally, we go into some implementation detail in <>. +Finally, we go into some implementation detail in <>. ==== git merge The `git merge` tool is used to merge one or more branches into the branch you have checked out. It will then advance the current branch to the result of the merge. -The `git merge` command was first introduced in <>. +The `git merge` command was first introduced in <>. Though it is used in various places in the book, there are very few variations of the `merge` command -- generally just `git merge ` with the name of the single branch you want to merge in. -We covered how to do a squashed merge (where Git merges the work but pretends like it's just a new commit without recording the history of the branch you're merging in) at the very end of <>. +We covered how to do a squashed merge (where Git merges the work but pretends like it's just a new commit without recording the history of the branch you're merging in) at the very end of <>. -We went over a lot about the merge process and command, including the `-Xignore-space-change` command and the `--abort` flag to abort a problem merge in <>. +We went over a lot about the merge process and command, including the `-Xignore-space-change` command and the `--abort` flag to abort a problem merge in <>. -We learned how to verify signatures before merging if your project is using GPG signing in <>. +We learned how to verify signatures before merging if your project is using GPG signing in <>. -Finally, we learned about Subtree merging in <>. +Finally, we learned about Subtree merging in <>. ==== git mergetool The `git mergetool` command simply launches an external merge helper in case you have issues with a merge in Git. -We mention it quickly in <> and go into detail on how to implement your own external merge tool in <>. +We mention it quickly in <> and go into detail on how to implement your own external merge tool in <>. ==== git log @@ -237,38 +280,37 @@ It is also often used to show differences between two or more branches at the co This command is used in nearly every chapter of the book to demonstrate the history of a project. -We introduce the command and cover it in some depth in <>. +We introduce the command and cover it in some depth in <>. There we look at the `-p` and `--stat` option to get an idea of what was introduced in each commit and the `--pretty` and `--oneline` options to view the history more concisely, along with some simple date and author filtering options. -In <> we use it with the `--decorate` option to easily visualize where our branch pointers are located and we also use the `--graph` option to see what divergent histories look like. +In <> we use it with the `--decorate` option to easily visualize where our branch pointers are located and we also use the `--graph` option to see what divergent histories look like. -In <> and <> we cover the `branchA..branchB` syntax to use the `git log` command to see what commits are unique to a branch relative to another branch. -In <> we go through this fairly extensively. +In <> and <> we cover the `branchA..branchB` syntax to use the `git log` command to see what commits are unique to a branch relative to another branch. +In <> we go through this fairly extensively. -In <> and <> we cover using the `branchA...branchB` format and the `--left-right` syntax to see what is in one branch or the other but not in both. -In <> we also look at how to use the `--merge` option to help with merge conflict debugging as well as using the `--cc` option to look at merge commit conflicts in your history. +In <> and <> we cover using the `branchA...branchB` format and the `--left-right` syntax to see what is in one branch or the other but not in both. +In <> we also look at how to use the `--merge` option to help with merge conflict debugging as well as using the `--cc` option to look at merge commit conflicts in your history. -In <> we use the `-g` option to view the Git reflog through this tool instead of doing branch traversal. +In <> we use the `-g` option to view the Git reflog through this tool instead of doing branch traversal. -In <> we look at using the `-S` and `-L` options to do fairly sophisticated searches for something that happened historically in the code such as seeing the history of a function. +In <> we look at using the `-S` and `-L` options to do fairly sophisticated searches for something that happened historically in the code such as seeing the history of a function. -In <> we see how to use `--show-signature` to add a validation string to each commit in the `git log` output based on if it was validly signed or not. +In <> we see how to use `--show-signature` to add a validation string to each commit in the `git log` output based on if it was validly signed or not. ==== git stash The `git stash` command is used to temporarily store uncommitted work in order to clean out your working directory without having to commit unfinished work on a branch. -This is basically entirely covered in <>. +This is basically entirely covered in <>. ==== git tag The `git tag` command is used to give a permanent bookmark to a specific point in the code history. Generally this is used for things like releases. -This command is introduced and covered in detail in <> and we use it in practice in <>. - -We also cover how to create a GPG signed tag with the `-s` flag and verify one with the `-v` flag in <>. +This command is introduced and covered in detail in <> and we use it in practice in <>. +We also cover how to create a GPG signed tag with the `-s` flag and verify one with the `-v` flag in <>. === Sharing and Updating Projects @@ -279,54 +321,54 @@ When you are ready to share your work or pull changes from elsewhere, there are The `git fetch` command communicates with a remote repository and fetches down all the information that is in that repository that is not in your current one and stores it in your local database. -We first look at this command in <> and we continue to see examples of it use in <>. +We first look at this command in <> and we continue to see examples of its use in <>. -We also use it in several of the examples in <>. +We also use it in several of the examples in <>. -We use it to fetch a single specific reference that is outside of the default space in <> and we see how to fetch from a bundle in <>. +We use it to fetch a single specific reference that is outside of the default space in <> and we see how to fetch from a bundle in <>. -We set up highly custom refspecs in order to make `git fetch` do something a little different than the default in <>. +We set up highly custom refspecs in order to make `git fetch` do something a little different than the default in <>. ==== git pull The `git pull` command is basically a combination of the `git fetch` and `git merge` commands, where Git will fetch from the remote you specify and then immediately try to merge it into the branch you're on. -We introduce it quickly in <> and show how to see what it will merge if you run it in <>. +We introduce it quickly in <> and show how to see what it will merge if you run it in <>. -We also see how to use it to help with rebasing difficulties in <>. +We also see how to use it to help with rebasing difficulties in <>. -We show how to use it with a URL to pull in changes in a one-off fashion in <>. +We show how to use it with a URL to pull in changes in a one-off fashion in <>. -Finally, we very quickly mention that you can use the `--verify-signatures` option to it in order to verify that commits you are pulling have been GPG signed in <>. +Finally, we very quickly mention that you can use the `--verify-signatures` option to it in order to verify that commits you are pulling have been GPG signed in <>. ==== git push The `git push` command is used to communicate with another repository, calculate what your local database has that the remote one does not, and then pushes the difference into the other repository. It requires write access to the other repository and so normally is authenticated somehow. -We first look at the `git push` command in <>. +We first look at the `git push` command in <>. Here we cover the basics of pushing a branch to a remote repository. -In <> we go a little deeper into pushing specific branches and in <> we see how to set up tracking branches to automatically push to. -In <> we use the `--delete` flag to delete a branch on the server with `git push`. +In <> we go a little deeper into pushing specific branches and in <> we see how to set up tracking branches to automatically push to. +In <> we use the `--delete` flag to delete a branch on the server with `git push`. -Throughout <> we see several examples of using `git push` to share work on branches through multiple remotes. +Throughout <> we see several examples of using `git push` to share work on branches through multiple remotes. -We see how to use it to share tags that you have made with the `--tags` option in <>. +We see how to use it to share tags that you have made with the `--tags` option in <>. -In <> we use the `--recurse-submodules` option to check that all of our submodules work has been published before pushing the superproject, which can be really helpful when using submodules. +In <> we use the `--recurse-submodules` option to check that all of our submodules work has been published before pushing the superproject, which can be really helpful when using submodules. -In <> we talk briefly about the `pre-push` hook, which is a script we can setup to run before a push completes to verify that it should be allowed to push. +In <> we talk briefly about the `pre-push` hook, which is a script we can setup to run before a push completes to verify that it should be allowed to push. -Finally, in <> we look at pushing with a full refspec instead of the general shortcuts that are normally used. +Finally, in <> we look at pushing with a full refspec instead of the general shortcuts that are normally used. This can help you be very specific about what work you wish to share. ==== git remote The `git remote` command is a management tool for your record of remote repositories. -It allows you to save long URLs as short handles, such as ``origin'' so you don't have to type them out all the time. +It allows you to save long URLs as short handles, such as "`origin`" so you don't have to type them out all the time. You can have several of these and the `git remote` command is used to add, change and delete them. -This command is covered in detail in <>, including listing, adding, removing and renaming them. +This command is covered in detail in <>, including listing, adding, removing and renaming them. It is used in nearly every subsequent chapter in the book too, but always in the standard `git remote add ` format. @@ -334,7 +376,7 @@ It is used in nearly every subsequent chapter in the book too, but always in the The `git archive` command is used to create an archive file of a specific snapshot of the project. -We use `git archive` to create a tarball of a project for sharing in <>. +We use `git archive` to create a tarball of a project for sharing in <>. ==== git submodule @@ -342,7 +384,7 @@ The `git submodule` command is used to manage external repositories within a nor This could be for libraries or other types of shared resources. The `submodule` command has several sub-commands (`add`, `update`, `sync`, etc) for managing these resources. -This command is only mentioned and entirely covered in <>. +This command is only mentioned and entirely covered in <>. === Inspection and Comparison @@ -351,26 +393,25 @@ This command is only mentioned and entirely covered in <>. +We first use it to show annotated tag information in <>. -Later we use it quite a bit in <> to show the commits that our various revision selections resolve to. +Later we use it quite a bit in <> to show the commits that our various revision selections resolve to. -One of the more interesting things we do with `git show` is in <> to extract specific file contents of various stages during a merge conflict. +One of the more interesting things we do with `git show` is in <> to extract specific file contents of various stages during a merge conflict. ==== git shortlog The `git shortlog` command is used to summarize the output of `git log`. It will take many of the same options that the `git log` command will but instead of listing out all of the commits it will present a summary of the commits grouped by author. -We showed how to use it to create a nice changelog in <>. +We showed how to use it to create a nice changelog in <>. ==== git describe The `git describe` command is used to take anything that resolves to a commit and produces a string that is somewhat human-readable and will not change. It's a way to get a description of a commit that is as unambiguous as a commit SHA-1 but more understandable. -We use `git describe` in <> and <> to get a string to name our release file after. - +We use `git describe` in <> and <> to get a string to name our release file after. === Debugging @@ -381,20 +422,20 @@ This ranges from figuring out where something was introduced to figuring out who The `git bisect` tool is an incredibly helpful debugging tool used to find which specific commit was the first one to introduce a bug or problem by doing an automatic binary search. -It is fully covered in <> and is only mentioned in that section. +It is fully covered in <> and is only mentioned in that section. ==== git blame The `git blame` command annotates the lines of any file with which commit was the last one to introduce a change to each line of the file and what person authored that commit. This is helpful in order to find the person to ask for more information about a specific section of your code. -It is covered in <> and is only mentioned in that section. +It is covered in <> and is only mentioned in that section. ==== git grep The `git grep` command can help you find any string or regular expression in any of the files in your source code, even older versions of your project. -It is covered in <> and is only mentioned in that section. +It is covered in <> and is only mentioned in that section. === Patching @@ -406,27 +447,27 @@ These commands help you manage your branches in this manner. The `git cherry-pick` command is used to take the change introduced in a single Git commit and try to re-introduce it as a new commit on the branch you're currently on. This can be useful to only take one or two commits from a branch individually rather than merging in the branch which takes all the changes. -Cherry picking is described and demonstrated in <>. +Cherry picking is described and demonstrated in <>. ==== git rebase The `git rebase` command is basically an automated `cherry-pick`. It determines a series of commits and then cherry-picks them one by one in the same order somewhere else. -Rebasing is covered in detail in <>, including covering the collaborative issues involved with rebasing branches that are already public. +Rebasing is covered in detail in <>, including covering the collaborative issues involved with rebasing branches that are already public. -We use it in practice during an example of splitting your history into two separate repositories in <>, using the `--onto` flag as well. +We use it in practice during an example of splitting your history into two separate repositories in <>, using the `--onto` flag as well. -We go through running into a merge conflict during rebasing in <>. +We go through running into a merge conflict during rebasing in <>. -We also use it in an interactive scripting mode with the `-i` option in <>. +We also use it in an interactive scripting mode with the `-i` option in <>. ==== git revert The `git revert` command is essentially a reverse `git cherry-pick`. It creates a new commit that applies the exact opposite of the change introduced in the commit you're targeting, essentially undoing or reverting it. -We use this in <> to undo a merge commit. +We use this in <> to undo a merge commit. === Email @@ -438,43 +479,43 @@ Git has a number of tools built into it that help make this process easier, from The `git apply` command applies a patch created with the `git diff` or even GNU diff command. It is similar to what the `patch` command might do with a few small differences. -We demonstrate using it and the circumstances in which you might do so in <>. +We demonstrate using it and the circumstances in which you might do so in <>. ==== git am The `git am` command is used to apply patches from an email inbox, specifically one that is mbox formatted. This is useful for receiving patches over email and applying them to your project easily. -We covered usage and workflow around `git am` in <> including using the `--resolved`, `-i` and `-3` options. +We covered usage and workflow around `git am` in <> including using the `--resolved`, `-i` and `-3` options. -There are also a number of hooks you can use to help with the workflow around `git am` and they are all covered in <>. +There are also a number of hooks you can use to help with the workflow around `git am` and they are all covered in <>. -We also use it to apply patch formatted GitHub Pull Request changes in <>. +We also use it to apply patch formatted GitHub Pull Request changes in <>. ==== git format-patch The `git format-patch` command is used to generate a series of patches in mbox format that you can use to send to a mailing list properly formatted. -We go through an example of contributing to a project using the `git format-patch` tool in <>. +We go through an example of contributing to a project using the `git format-patch` tool in <>. ==== git imap-send The `git imap-send` command uploads a mailbox generated with `git format-patch` into an IMAP drafts folder. -We go through an example of contributing to a project by sending patches with the `git imap-send` tool in <>. +We go through an example of contributing to a project by sending patches with the `git imap-send` tool in <>. ==== git send-email The `git send-email` command is used to send patches that are generated with `git format-patch` over email. -We go through an example of contributing to a project by sending patches with the `git send-email` tool in <>. +We go through an example of contributing to a project by sending patches with the `git send-email` tool in <>. ==== git request-pull The `git request-pull` command is simply used to generate an example message body to email to someone. If you have a branch on a public server and want to let someone know how to integrate those changes without sending the patches over email, you can run this command and send the output to the person you want to pull the changes in. -We demonstrate how to use `git request-pull` to generate a pull message in <>. +We demonstrate how to use `git request-pull` to generate a pull message in <>. === External Systems @@ -485,13 +526,13 @@ Git comes with a few commands to integrate with other version control systems. The `git svn` command is used to communicate with the Subversion version control system as a client. This means you can use Git to checkout from and commit to a Subversion server. -This command is covered in depth in <>. +This command is covered in depth in <>. ==== git fast-import For other version control systems or importing from nearly any format, you can use `git fast-import` to quickly map the other format to something Git can easily record. -This command is covered in depth in <>. +This command is covered in depth in <>. === Administration @@ -499,43 +540,42 @@ If you're administering a Git repository or need to fix something in a big way, ==== git gc -The `git gc` command runs ``garbage collection'' on your repository, removing unnecessary files in your database and packing up the remaining files into a more efficient format. +The `git gc` command runs "`garbage collection`" on your repository, removing unnecessary files in your database and packing up the remaining files into a more efficient format. This command normally runs in the background for you, though you can manually run it if you wish. -We go over some examples of this in <>. +We go over some examples of this in <>. ==== git fsck The `git fsck` command is used to check the internal database for problems or inconsistencies. -We only quickly use this once in <> to search for dangling objects. +We only quickly use this once in <> to search for dangling objects. ==== git reflog The `git reflog` command goes through a log of where all the heads of your branches have been as you work to find commits you may have lost through rewriting histories. -We cover this command mainly in <>, where we show normal usage to and how to use `git log -g` to view the same information with `git log` output. +We cover this command mainly in <>, where we show normal usage to and how to use `git log -g` to view the same information with `git log` output. -We also go through a practical example of recovering such a lost branch in <>. +We also go through a practical example of recovering such a lost branch in <>. ==== git filter-branch The `git filter-branch` command is used to rewrite loads of commits according to certain patterns, like removing a file everywhere or filtering the entire repository down to a single subdirectory for extracting a project. -In <> we explain the command and explore several different options such as `--commit-filter`, `--subdirectory-filter` and `--tree-filter`. - -In <> we use it to fix up imported external repositories. +In <> we explain the command and explore several different options such as `--commit-filter`, `--subdirectory-filter` and `--tree-filter`. +In <> we use it to fix up imported external repositories. === Plumbing Commands There were also quite a number of lower level plumbing commands that we encountered in the book. -The first one we encounter is `ls-remote` in <> which we use to look at the raw references on the server. +The first one we encounter is `ls-remote` in <> which we use to look at the raw references on the server. -We use `ls-files` in <>, <> and <> to take a more raw look at what your staging area looks like. +We use `ls-files` in <>, <> and <> to take a more raw look at what your staging area looks like. -We also mention `rev-parse` in <> to take just about any string and turn it into an object SHA-1. +We also mention `rev-parse` in <> to take just about any string and turn it into an object SHA-1. However, most of the low level plumbing commands we cover are in <>, which is more or less what the chapter is focused on. We tried to avoid use of them throughout most of the rest of the book. diff --git a/book-en/01-introduction/sections/about-version-control.asc b/book-en/01-introduction/sections/about-version-control.asc index 6970b8bc..182fcedc 100644 --- a/book-en/01-introduction/sections/about-version-control.asc +++ b/book-en/01-introduction/sections/about-version-control.asc @@ -19,21 +19,21 @@ It is easy to forget which directory you're in and accidentally write to the wro To deal with this issue, programmers long ago developed local VCSs that had a simple database that kept all the changes to files under revision control. -.Local version control +.Local version control diagram image::images/local.png[Local version control diagram] One of the most popular VCS tools was a system called RCS, which is still distributed with many computers today. -https://www.gnu.org/software/rcs/[RCS] works by keeping patch sets (that is, the differences between files) in a special format on disk; it can then re-create what any file looked like at any point in time by adding up all the patches. +https://www.gnu.org/software/rcs/[RCS^] works by keeping patch sets (that is, the differences between files) in a special format on disk; it can then re-create what any file looked like at any point in time by adding up all the patches. ==== Centralized Version Control Systems (((version control,centralized))) The next major issue that people encounter is that they need to collaborate with developers on other systems. To deal with this problem, Centralized Version Control Systems (CVCSs) were developed. -These systems (such as CVS, Subversion, and Perforce) have a single server that contains all the versioned files, and a number of clients that check out files from that central place. (((CVS)))(((Subversion)))(((Perforce))) +These systems (such as CVS, Subversion, and Perforce) have a single server that contains all the versioned files, and a number of clients that check out files from that central place.(((CVS)))(((Subversion)))(((Perforce))) For many years, this has been the standard for version control. -.Centralized version control +.Centralized version control diagram image::images/centralized.png[Centralized version control diagram] This setup offers many advantages, especially over local VCSs. @@ -50,11 +50,11 @@ Local VCSs suffer from this same problem -- whenever you have the entire history (((version control,distributed))) This is where Distributed Version Control Systems (DVCSs) step in. -In a DVCS (such as Git, Mercurial, Bazaar or Darcs), clients don't just check out the latest snapshot of the files; rather, they fully mirror the repository, including its full history. +In a DVCS (such as Git, Mercurial or Darcs), clients don't just check out the latest snapshot of the files; rather, they fully mirror the repository, including its full history. Thus, if any server dies, and these systems were collaborating via that server, any of the client repositories can be copied back up to the server to restore it. Every clone is really a full backup of all the data. -.Distributed version control +.Distributed version control diagram image::images/distributed.png[Distributed version control diagram] Furthermore, many of these systems deal pretty well with having several remote repositories they can work with, so you can collaborate with different groups of people in different ways simultaneously within the same project. diff --git a/book-en/01-introduction/sections/first-time-setup.asc b/book-en/01-introduction/sections/first-time-setup.asc index 4f5e29eb..10b7049c 100644 --- a/book-en/01-introduction/sections/first-time-setup.asc +++ b/book-en/01-introduction/sections/first-time-setup.asc @@ -21,8 +21,7 @@ Each level overrides values in the previous level, so values in `.git/config` tr On Windows systems, Git looks for the `.gitconfig` file in the `$HOME` directory (`C:\Users\$USER` for most people). It also still looks for `[path]/etc/gitconfig`, although it's relative to the MSys root, which is wherever you decide to install Git on your Windows system when you run the installer. -If you are using version 2.x or later of Git for Windows, there is also a system-level config file at -`C:\Documents and Settings\All Users\Application Data\Git\config` on Windows XP, and in `C:\ProgramData\Git\config` on Windows Vista and newer. +If you are using version 2.x or later of Git for Windows, there is also a system-level config file at `C:\Documents and Settings\All Users\Application Data\Git\config` on Windows XP, and in `C:\ProgramData\Git\config` on Windows Vista and newer. This config file can only be changed by `git config -f ` as an admin. You can view all of your settings and where they are coming from using: @@ -43,7 +42,7 @@ $ git config --global user.name "John Doe" $ git config --global user.email johndoe@example.com ---- -Again, you need to do this only once if you pass the `--global` option, because then Git will always use that information for anything you do on that system. +Again, you need to do this only once if you pass the `--global` option, because then Git will always use that information for your user on that system. If you want to override this with a different name or email address for specific projects, you can run the command without the `--global` option when you're in that project. Many of the GUI tools will help you do this when you first run them. @@ -84,6 +83,7 @@ You may find, if you don't setup your editor like this, you get into a really co An example on a Windows system may include a prematurely terminated Git operation during a Git initiated edit. ==== +[[_new_default_branch]] ==== Your default branch name By default Git will create a branch called _master_ when you create a new repository with `git init`. diff --git a/book-en/01-introduction/sections/help.asc b/book-en/01-introduction/sections/help.asc index 5c4392df..68d76a4c 100644 --- a/book-en/01-introduction/sections/help.asc +++ b/book-en/01-introduction/sections/help.asc @@ -18,7 +18,7 @@ $ git help config ---- These commands are nice because you can access them anywhere, even offline. -If the manpages and this book aren't enough and you need in-person help, you can try the `#git`, `#github`, or `#gitlab` channels on the Libera Chat IRC server, which can be found at https://libera.chat/[]. +If the manpages and this book aren't enough and you need in-person help, you can try the `#git`, `#github`, or `#gitlab` channels on the Libera Chat IRC server, which can be found at https://libera.chat/[^]. These channels are regularly filled with hundreds of people who are all very knowledgeable about Git and are often willing to help.(((IRC))) In addition, if you don't need the full-blown manpage help, but just need a quick refresher on the available options for a Git command, you can ask for the more concise "`help`" output with the `-h` option, as in: @@ -43,8 +43,8 @@ usage: git add [] [--] ... --refresh don't add, only refresh the index --ignore-errors just skip files which cannot be added because of errors --ignore-missing check if - even missing - files are ignored in dry run + --sparse allow updating entries outside of the sparse-checkout cone --chmod (+|-)x override the executable bit of the listed files --pathspec-from-file read pathspec from file --pathspec-file-nul with --pathspec-from-file, pathspec elements are separated with NUL character ---- - diff --git a/book-en/01-introduction/sections/history.asc b/book-en/01-introduction/sections/history.asc index 508fbe56..7ab05fd3 100644 --- a/book-en/01-introduction/sections/history.asc +++ b/book-en/01-introduction/sections/history.asc @@ -10,11 +10,11 @@ In 2005, the relationship between the community that developed the Linux kernel This prompted the Linux development community (and in particular Linus Torvalds, the creator of Linux) to develop their own tool based on some of the lessons they learned while using BitKeeper.(((Linus Torvalds))) Some of the goals of the new system were as follows: -* Speed -* Simple design -* Strong support for non-linear development (thousands of parallel branches) -* Fully distributed -* Able to handle large projects like the Linux kernel efficiently (speed and data size) +* Speed +* Simple design +* Strong support for non-linear development (thousands of parallel branches) +* Fully distributed +* Able to handle large projects like the Linux kernel efficiently (speed and data size) Since its birth in 2005, Git has evolved and matured to be easy to use and yet retain these initial qualities. -It's amazingly fast, it's very efficient with large projects, and it has an incredible branching system for non-linear development (See <>). +It's amazingly fast, it's very efficient with large projects, and it has an incredible branching system for non-linear development (see <>). diff --git a/book-en/01-introduction/sections/installing.asc b/book-en/01-introduction/sections/installing.asc index bd509397..d4f6dcbd 100644 --- a/book-en/01-introduction/sections/installing.asc +++ b/book-en/01-introduction/sections/installing.asc @@ -6,9 +6,9 @@ You can either install it as a package or via another installer, or download the [NOTE] ==== -This book was written using Git version *2.8.0*. -Though most of the commands we use should work even in ancient versions of Git, some of them might not or might act slightly differently if you're using an older version. -Since Git is quite excellent at preserving backwards compatibility, any version after 2.8 should work just fine. +This book was written using Git version 2. +Since Git is quite excellent at preserving backwards compatibility, any recent version should work just fine. +Though most of the commands we use should work even in ancient versions of Git, some of them might not or might act slightly differently. ==== ==== Installing on Linux @@ -29,12 +29,12 @@ If you're on a Debian-based distribution, such as Ubuntu, try `apt`: $ sudo apt install git-all ---- -For more options, there are instructions for installing on several different Unix distributions on the Git website, at https://git-scm.com/download/linux[]. +For more options, there are instructions for installing on several different Unix distributions on the Git website, at https://git-scm.com/download/linux[^]. ==== Installing on macOS (((macOS, installing))) -There are several ways to install Git on a Mac. +There are several ways to install Git on macOS. The easiest is probably to install the Xcode Command Line Tools.(((Xcode))) On Mavericks (10.9) or above you can do this simply by trying to run `git` from the Terminal the very first time. @@ -46,19 +46,19 @@ $ git --version If you don't have it installed already, it will prompt you to install it. If you want a more up to date version, you can also install it via a binary installer. -A macOS Git installer is maintained and available for download at the Git website, at https://git-scm.com/download/mac[]. +A macOS Git installer is maintained and available for download at the Git website, at https://git-scm.com/download/mac[^]. -.Git macOS Installer +.Git macOS installer image::images/git-osx-installer.png[Git macOS installer] ==== Installing on Windows There are also a few ways to install Git on Windows.(((Windows, installing))) The most official build is available for download on the Git website. -Just go to https://git-scm.com/download/win[] and the download will start automatically. -Note that this is a project called Git for Windows, which is separate from Git itself; for more information on it, go to https://gitforwindows.org[]. +Just go to https://git-scm.com/download/win[^] and the download will start automatically. +Note that this is a project called Git for Windows, which is separate from Git itself; for more information on it, go to https://gitforwindows.org[^]. -To get an automated installation you can use the https://chocolatey.org/packages/git[Git Chocolatey package]. +To get an automated installation you can use the https://community.chocolatey.org/packages/git[Git Chocolatey package^]. Note that the Chocolatey package is community maintained. ==== Installing from Source @@ -87,7 +87,7 @@ $ sudo apt-get install asciidoc xmlto docbook2x [NOTE] ==== -Users of RHEL and RHEL-derivatives like CentOS and Scientific Linux will have to https://fedoraproject.org/wiki/EPEL#How_can_I_use_these_extra_packages.3F[enable the EPEL repository] to download the `docbook2X` package. +Users of RHEL and RHEL-derivatives like CentOS and Scientific Linux will have to https://docs.fedoraproject.org/en-US/epel/#how_can_i_use_these_extra_packages[enable the EPEL repository^] to download the `docbook2X` package. ==== If you're using a Debian-based distribution (Debian/Ubuntu/Ubuntu-derivatives), you also need the `install-info` package: @@ -114,7 +114,7 @@ $ sudo ln -s /usr/bin/db2x_docbook2texi /usr/bin/docbook2x-texi due to binary name differences. When you have all the necessary dependencies, you can go ahead and grab the latest tagged release tarball from several places. -You can get it via the kernel.org site, at https://www.kernel.org/pub/software/scm/git[], or the mirror on the GitHub website, at https://github.com/git/git/releases[]. +You can get it via the kernel.org site, at https://www.kernel.org/pub/software/scm/git[^], or the mirror on the GitHub website, at https://github.com/git/git/tags[^]. It's generally a little clearer what the latest version is on the GitHub page, but the kernel.org page also has release signatures if you want to verify your download. Then, compile and install: @@ -133,5 +133,5 @@ After this is done, you can also get Git via Git itself for updates: [source,console] ---- -$ git clone git://git.kernel.org/pub/scm/git/git.git +$ git clone https://git.kernel.org/pub/scm/git/git.git ---- diff --git a/book-en/01-introduction/sections/what-is-git.asc b/book-en/01-introduction/sections/what-is-git.asc index 23769b95..466201b2 100644 --- a/book-en/01-introduction/sections/what-is-git.asc +++ b/book-en/01-introduction/sections/what-is-git.asc @@ -10,7 +10,7 @@ Even though Git's user interface is fairly similar to these other VCSs, Git stor The major difference between Git and any other VCS (Subversion and friends included) is the way Git thinks about its data. Conceptually, most other systems store information as a list of file-based changes. -These other systems (CVS, Subversion, Perforce, Bazaar, and so on) think of the information they store as a set of files and the changes made to each file over time (this is commonly described as _delta-based_ version control). +These other systems (CVS, Subversion, Perforce, and so on) think of the information they store as a set of files and the changes made to each file over time (this is commonly described as _delta-based_ version control). .Storing data as changes to a base version of each file image::images/deltas.png[Storing data as changes to a base version of each file] @@ -86,7 +86,7 @@ Git has three main states that your files can reside in: _modified_, _staged_, a This leads us to the three main sections of a Git project: the working tree, the staging area, and the Git directory. .Working tree, staging area, and Git directory -image::images/areas.png["Working tree, staging area, and Git directory."] +image::images/areas.png["Working tree, staging area, and Git directory"] The working tree is a single checkout of one version of the project. These files are pulled out of the compressed database in the Git directory and placed on disk for you to use or modify. diff --git a/book-en/02-git-basics/sections/recording-changes.asc b/book-en/02-git-basics/sections/recording-changes.asc index f863e1ee..8bcd785f 100644 --- a/book-en/02-git-basics/sections/recording-changes.asc +++ b/book-en/02-git-basics/sections/recording-changes.asc @@ -36,6 +36,15 @@ Finally, the command tells you which branch you're on and informs you that it ha For now, that branch is always `master`, which is the default; you won't worry about it here. <> will go over branches and references in detail. +[NOTE] +==== +GitHub changed the default branch name from `master` to `main` in mid-2020, and other Git hosts followed suit. +So you may find that the default branch name in some newly created repositories is `main` and not `master`. +In addition, the default branch name can be changed (as you have seen in <>), so you may see a different name for the default branch. + +However, Git itself still uses `master` as the default, so we will use it throughout the book. +==== + Let's say you add a new file to your project, a simple `README` file. If the file didn't exist before, and you run `git status`, you see your untracked file like so: @@ -219,11 +228,11 @@ Setting up a `.gitignore` file for your new repository before you get going is g The rules for the patterns you can put in the `.gitignore` file are as follows: -* Blank lines or lines starting with `#` are ignored. -* Standard glob patterns work, and will be applied recursively throughout the entire working tree. -* You can start patterns with a forward slash (`/`) to avoid recursivity. -* You can end patterns with a forward slash (`/`) to specify a directory. -* You can negate a pattern by starting it with an exclamation point (`!`). +* Blank lines or lines starting with `#` are ignored. +* Standard glob patterns work, and will be applied recursively throughout the entire working tree. +* You can start patterns with a forward slash (`/`) to avoid recursivity. +* You can end patterns with a forward slash (`/`) to specify a directory. +* You can negate a pattern by starting it with an exclamation point (`!`). Glob patterns are like simplified regular expressions that shells use. An asterisk (`\*`) matches zero or more characters; `[abc]` matches any character inside the brackets (in this case a, b, or c); a question mark (`?`) matches a single character; and brackets enclosing characters separated by a hyphen (`[0-9]`) matches any character between them (in this case 0 through 9). @@ -254,7 +263,7 @@ doc/**/*.pdf [TIP] ==== -GitHub maintains a fairly comprehensive list of good `.gitignore` file examples for dozens of projects and languages at https://github.com/github/gitignore[] if you want a starting point for your project. +GitHub maintains a fairly comprehensive list of good `.gitignore` file examples for dozens of projects and languages at https://github.com/github/gitignore[^] if you want a starting point for your project. ==== [NOTE] @@ -617,4 +626,4 @@ $ git add README Git figures out that it's a rename implicitly, so it doesn't matter if you rename a file that way or with the `mv` command. The only real difference is that `git mv` is one command instead of three -- it's a convenience function. -More importantly, you can use any tool you like to rename a file, and address the add/rm later, before you commit. +More importantly, you can use any tool you like to rename a file, and address the `add`/`rm` later, before you commit. diff --git a/book-en/02-git-basics/sections/remotes.asc b/book-en/02-git-basics/sections/remotes.asc index 85ab6c84..80e98250 100644 --- a/book-en/02-git-basics/sections/remotes.asc +++ b/book-en/02-git-basics/sections/remotes.asc @@ -87,7 +87,7 @@ pb https://github.com/paulboone/ticgit (fetch) pb https://github.com/paulboone/ticgit (push) ---- -Now you can use the string `pb` on the command line in lieu of the whole URL. +Now you can use the string `pb` on the command line instead of the whole URL. For example, if you want to fetch all the information that Paul has but that you don't yet have in your repository, you can run `git fetch pb`: [source,console] @@ -129,10 +129,10 @@ Running `git pull` generally fetches data from the server you originally cloned [NOTE] ==== -From git version 2.27 onward, `git pull` will give a warning if the `pull.rebase` variable is not set. +From Git version 2.27 onward, `git pull` will give a warning if the `pull.rebase` variable is not set. Git will keep warning you until you set the variable. -If you want the default behavior of git (fast-forward if possible, else create a merge commit): +If you want the default behavior of Git (fast-forward if possible, else create a merge commit): `git config --global pull.rebase "false"` If you want to rebase when pulling: diff --git a/book-en/02-git-basics/sections/viewing-history.asc b/book-en/02-git-basics/sections/viewing-history.asc index cfddeead..440c7f25 100644 --- a/book-en/02-git-basics/sections/viewing-history.asc +++ b/book-en/02-git-basics/sections/viewing-history.asc @@ -170,7 +170,7 @@ a11bef0 - Scott Chacon, 6 years ago : Initial commit | `%p` | Abbreviated parent hashes | `%an` | Author name | `%ae` | Author email -| `%ad` | Author date (format respects the --date=option) +| `%ad` | Author date (format respects the `--date=option`) | `%ar` | Author date, relative | `%cn` | Committer name | `%ce` | Committer email @@ -191,7 +191,7 @@ This option adds a nice little ASCII graph showing your branch and merge history ---- $ git log --pretty=format:"%h %s" --graph * 2d3acf9 Ignore errors from SIGCHLD on trap -* 5e3ee11 Merge branch 'master' of git://github.com/dustin/grit +* 5e3ee11 Merge branch 'master' of https://github.com/dustin/grit.git |\ | * 420eac9 Add method for getting the current branch * | 30e367c Timeout code and tests @@ -205,7 +205,7 @@ $ git log --pretty=format:"%h %s" --graph This type of output will become more interesting as we go through branching and merging in the next chapter. Those are only some simple output-formatting options to `git log` -- there are many more. -<> lists the options we've covered so far, as well as some other common formatting options that may be useful, along with how they change the output of the log command. +<> lists the options we've covered so far, as well as some other common formatting options that may be useful, along with how they change the output of the `log` command. [[log_options]] .Common options to `git log` @@ -214,13 +214,13 @@ Those are only some simple output-formatting options to `git log` -- there are m | Option | Description | `-p` | Show the patch introduced with each commit. | `--stat` | Show statistics for files modified in each commit. -| `--shortstat` | Display only the changed/insertions/deletions line from the --stat command. +| `--shortstat` | Display only the changed/insertions/deletions line from the `--stat` command. | `--name-only` | Show the list of files modified after the commit information. | `--name-status` | Show the list of files affected with added/modified/deleted information as well. | `--abbrev-commit` | Show only the first few characters of the SHA-1 checksum instead of all 40. | `--relative-date` | Display the date in a relative format (for example, "`2 weeks ago`") instead of using the full date format. | `--graph` | Display an ASCII graph of the branch and merge history beside the log output. -| `--pretty` | Show commits in an alternate format. Option values include oneline, short, full, fuller, and format (where you specify your own format). +| `--pretty` | Show commits in an alternate format. Option values include `oneline`, `short`, `full`, `fuller`, and `format` (where you specify your own format). | `--oneline` | Shorthand for `--pretty=oneline --abbrev-commit` used together. |================================ @@ -246,10 +246,7 @@ The `--author` option allows you to filter on a specific author, and the `--grep [NOTE] ==== -You can specify more than one instance of both the `--author` and `--grep` search criteria, which -will limit the commit output to commits that match _any_ of the `--author` patterns and _any_ -of the `--grep` patterns; however, adding the `--all-match` option further limits the output to -just those commits that match _all_ `--grep` patterns. +You can specify more than one instance of both the `--author` and `--grep` search criteria, which will limit the commit output to commits that match _any_ of the `--author` patterns and _any_ of the `--grep` patterns; however, adding the `--all-match` option further limits the output to just those commits that match _all_ `--grep` patterns. ==== Another really helpful filter is the `-S` option (colloquially referred to as Git's "`pickaxe`" option), which takes a string and shows only those commits that changed the number of occurrences of that string. @@ -276,13 +273,13 @@ In <> we'll list these and a few other common options for your re [cols="2,4",options="header"] |================================ | Option | Description -| `-` | Show only the last n commits +| `-` | Show only the last n commits. | `--since`, `--after` | Limit the commits to those made after the specified date. | `--until`, `--before` | Limit the commits to those made before the specified date. | `--author` | Only show commits in which the author entry matches the specified string. | `--committer` | Only show commits in which the committer entry matches the specified string. -| `--grep` | Only show commits with a commit message containing the string -| `-S` | Only show commits adding or removing code matching the string +| `--grep` | Only show commits with a commit message containing the string. +| `-S` | Only show commits adding or removing code matching the string. |================================ For example, if you want to see which commits modifying test files in the Git source code history were committed by Junio Hamano in the month of October 2008 and are not merge commits, you can run something like this:(((log filtering))) @@ -305,5 +302,5 @@ Of the nearly 40,000 commits in the Git source code history, this command shows .Preventing the display of merge commits ==== Depending on the workflow used in your repository, it's possible that a sizable percentage of the commits in your log history are just merge commits, which typically aren't very informative. -To prevent the display of merge commits cluttering up your log history, simply add the log option `--no-merges`. +To prevent the display of merge commits cluttering up your log history, simply add the `log` option `--no-merges`. ==== diff --git a/book-en/03-git-branching/sections/basic-branching-and-merging.asc b/book-en/03-git-branching/sections/basic-branching-and-merging.asc index a1aa0179..a894b670 100644 --- a/book-en/03-git-branching/sections/basic-branching-and-merging.asc +++ b/book-en/03-git-branching/sections/basic-branching-and-merging.asc @@ -265,7 +265,7 @@ Normal merge conflict for 'index.html': Hit return to start merge resolution tool (opendiff): ---- -If you want to use a merge tool other than the default (Git chose `opendiff` in this case because the command was run on a Mac), you can see all the supported tools listed at the top after "`one of the following tools.`" +If you want to use a merge tool other than the default (Git chose `opendiff` in this case because the command was run on macOS), you can see all the supported tools listed at the top after "`one of the following tools.`" Just type the name of the tool you'd rather use. [NOTE] diff --git a/book-en/03-git-branching/sections/branch-management.asc b/book-en/03-git-branching/sections/branch-management.asc index 5dcad611..ae81e89a 100644 --- a/book-en/03-git-branching/sections/branch-management.asc +++ b/book-en/03-git-branching/sections/branch-management.asc @@ -64,7 +64,7 @@ If you really do want to delete the branch and lose that work, you can force it ==== The options described above, `--merged` and `--no-merged` will, if not given a commit or branch name as an argument, show you what is, respectively, merged or not merged into your _current_ branch. -You can always provide an additional argument to ask about the merge state with respect to some other branch without checking that other branch out first, as in, what is not merged into the `master` branch? +You can always provide an additional argument to ask about the merge state with respect to some other branch without checking that other branch out first, as in, what is not merged into the `master` branch? [source,console] ---- $ git checkout testing @@ -79,7 +79,7 @@ $ git branch --no-merged master [CAUTION] ==== Do not rename branches that are still in use by other collaborators. -Do not rename a branch like master/main/mainline without having read the section "Changing the master branch name". +Do not rename a branch like master/main/mainline without having read the section <<_changing_master>>. ==== Suppose you have a branch that is called `bad-branch-name` and you want to change it to `corrected-branch-name`, while keeping all history. @@ -123,6 +123,7 @@ $ git push origin --delete bad-branch-name Now the bad branch name is fully replaced with the corrected branch name. +[[_changing_master]] ===== Changing the master branch name [WARNING] @@ -153,7 +154,7 @@ Now we end up with the following state: [source,console] ---- -git branch --all +$ git branch --all * main remotes/origin/HEAD -> origin/master remotes/origin/main diff --git a/book-en/03-git-branching/sections/nutshell.asc b/book-en/03-git-branching/sections/nutshell.asc index e4e983a1..2bffd5dd 100644 --- a/book-en/03-git-branching/sections/nutshell.asc +++ b/book-en/03-git-branching/sections/nutshell.asc @@ -110,7 +110,7 @@ Well, let's do another commit: [source,console] ---- $ vim test.rb -$ git commit -a -m 'made a change' +$ git commit -a -m 'Make a change' ---- .The HEAD branch moves forward when a commit is made @@ -157,7 +157,7 @@ Let's make a few changes and commit again: [source,console] ---- $ vim test.rb -$ git commit -a -m 'made other changes' +$ git commit -a -m 'Make other changes' ---- Now your project history has diverged (see <>). @@ -175,12 +175,12 @@ If you run `git log --oneline --decorate --graph --all` it will print out the hi [source,console] ---- $ git log --oneline --decorate --graph --all -* c2b9e (HEAD, master) Made other changes -| * 87ab2 (testing) Made a change +* c2b9e (HEAD, master) Make other changes +| * 87ab2 (testing) Make a change |/ * f30ab Add feature #32 - ability to add new formats to the central interface * 34ac2 Fix bug #1328 - stack overflow under certain conditions -* 98ca9 initial commit of my project +* 98ca9 Initial commit of my project ---- Because a branch in Git is actually a simple file that contains the 40 character SHA-1 checksum of the commit it points to, branches are cheap to create and destroy. @@ -204,6 +204,7 @@ It's typical to create a new branch and want to switch to that new branch at the From Git version 2.23 onwards you can use `git switch` instead of `git checkout` to: - Switch to an existing branch: `git switch testing-branch`. -- Create a new branch and switch to it: `git switch -c new-branch`. The `-c` flag stands for create, you can also use the full flag: `--create`. +- Create a new branch and switch to it: `git switch -c new-branch`. + The `-c` flag stands for create, you can also use the full flag: `--create`. - Return to your previously checked out branch: `git switch -`. ==== diff --git a/book-en/03-git-branching/sections/rebasing.asc b/book-en/03-git-branching/sections/rebasing.asc index dfc18dc5..c6653524 100644 --- a/book-en/03-git-branching/sections/rebasing.asc +++ b/book-en/03-git-branching/sections/rebasing.asc @@ -66,7 +66,7 @@ You can also have your rebase replay on something other than the rebase target b Take a history like <>, for example. You branched a topic branch (`server`) to add some server-side functionality to your project, and made a commit. Then, you branched off that to make the client-side changes (`client`) and committed a few times. -Finally, you went back to your server branch and did a few more commits. +Finally, you went back to your `server` branch and did a few more commits. [[rbdiag_e]] .A history with a topic branch off another topic branch @@ -95,10 +95,10 @@ $ git merge client ---- [[rbdiag_g]] -.Fast-forwarding your `master` branch to include the client branch changes -image::images/interesting-rebase-3.png[Fast-forwarding your `master` branch to include the client branch changes] +.Fast-forwarding your `master` branch to include the `client` branch changes +image::images/interesting-rebase-3.png[Fast-forwarding your `master` branch to include the `client` branch changes] -Let's say you decide to pull in your server branch as well. +Let's say you decide to pull in your `server` branch as well. You can rebase the `server` branch onto the `master` branch without having to check it out first by running `git rebase ` -- which checks out the topic branch (in this case, `server`) for you and replays it onto the base branch (`master`): [source,console] @@ -109,8 +109,8 @@ $ git rebase master server This replays your `server` work on top of your `master` work, as shown in <>. [[rbdiag_h]] -.Rebasing your server branch on top of your `master` branch -image::images/interesting-rebase-4.png[Rebasing your server branch on top of your `master` branch] +.Rebasing your `server` branch on top of your `master` branch +image::images/interesting-rebase-4.png[Rebasing your `server` branch on top of your `master` branch] Then, you can fast-forward the base branch (`master`): @@ -151,20 +151,20 @@ Suppose you clone from a central server and then do some work off that. Your commit history looks like this: .Clone a repository, and base some work on it -image::images/perils-of-rebasing-1.png["Clone a repository, and base some work on it."] +image::images/perils-of-rebasing-1.png["Clone a repository, and base some work on it"] Now, someone else does more work that includes a merge, and pushes that work to the central server. You fetch it and merge the new remote branch into your work, making your history look something like this: .Fetch more commits, and merge them into your work -image::images/perils-of-rebasing-2.png["Fetch more commits, and merge them into your work."] +image::images/perils-of-rebasing-2.png["Fetch more commits, and merge them into your work"] Next, the person who pushed the merged work decides to go back and rebase their work instead; they do a `git push --force` to overwrite the history on the server. You then fetch from that server, bringing down the new commits. [[_pre_merge_rebase_work]] .Someone pushes rebased commits, abandoning commits you've based your work on -image::images/perils-of-rebasing-3.png["Someone pushes rebased commits, abandoning commits you've based your work on."] +image::images/perils-of-rebasing-3.png["Someone pushes rebased commits, abandoning commits you've based your work on"] Now you're both in a pickle. If you do a `git pull`, you'll create a merge commit which includes both lines of history, and your repository will look like this: @@ -190,9 +190,9 @@ If you pull down work that was rewritten and rebase it on top of the new commits For instance, in the previous scenario, if instead of doing a merge when we're at <<_pre_merge_rebase_work>> we run `git rebase teamone/master`, Git will: -* Determine what work is unique to our branch (C2, C3, C4, C6, C7) -* Determine which are not merge commits (C2, C3, C4) -* Determine which have not been rewritten into the target branch (just C2 and C3, since C4 is the same patch as C4') +* Determine what work is unique to our branch (`C2`, `C3`, `C4`, `C6`, `C7`) +* Determine which are not merge commits (`C2`, `C3`, `C4`) +* Determine which have not been rewritten into the target branch (just `C2` and `C3`, since `C4` is the same patch as `C4'`) * Apply those commits to the top of `teamone/master` So instead of the result we see in <<_merge_rebase_work>>, we would end up with something more like <<_rebase_rebase_work>>. @@ -202,7 +202,7 @@ So instead of the result we see in <<_merge_rebase_work>>, we would end up with image::images/perils-of-rebasing-5.png[Rebase on top of force-pushed rebase work] This only works if `C4` and `C4'` that your partner made are almost exactly the same patch. -Otherwise the rebase won't be able to tell that it's a duplicate and will add another C4-like patch (which will probably fail to apply cleanly, since the changes would already be at least somewhat there). +Otherwise the rebase won't be able to tell that it's a duplicate and will add another `C4`-like patch (which will probably fail to apply cleanly, since the changes would already be at least somewhat there). You can also simplify this by running a `git pull --rebase` instead of a normal `git pull`. Or you could do it manually with a `git fetch` followed by a `git rebase teamone/master` in this case. @@ -230,7 +230,7 @@ That's how it happened, and the repository should preserve that for posterity. The opposing point of view is that the commit history is the *story of how your project was made.* You wouldn't publish the first draft of a book, so why show your messy work? When you're working on a project, you may need a record of all your missteps and dead-end paths, but when it's time to show your work to the world, you may want to tell a more coherent story of how to get from A to B. -People in this camp use tools like rebase and filter-branch to rewrite their commits before they're merged into the mainline branch. +People in this camp use tools like `rebase` and `filter-branch` to rewrite their commits before they're merged into the mainline branch. They use tools like `rebase` and `filter-branch`, to tell the story in the way that's best for future readers. Now, to the question of whether merging or rebasing is better: hopefully you'll see that it's not that simple. diff --git a/book-en/03-git-branching/sections/remote-branches.asc b/book-en/03-git-branching/sections/remote-branches.asc index 0701dbf9..adbb8735 100644 --- a/book-en/03-git-branching/sections/remote-branches.asc +++ b/book-en/03-git-branching/sections/remote-branches.asc @@ -28,7 +28,7 @@ If you run `git clone -o booyah` instead, then you will have `booyah/master` as ==== .Server and local repositories after cloning -image::images/remote-branches-1.png[Server and local repositories after cloning.] +image::images/remote-branches-1.png[Server and local repositories after cloning] If you do some work on your local `master` branch, and, in the meantime, someone else pushes to `git.ourcompany.com` and updates its `master` branch, then your histories move forward differently. Also, as long as you stay out of contact with your `origin` server, your `origin/master` pointer doesn't move. @@ -40,7 +40,7 @@ To synchronize your work with a given remote, you run a `git fetch ` com This command looks up which server "`origin`" is (in this case, it's `git.ourcompany.com`), fetches any data from it that you don't yet have, and updates your local database, moving your `origin/master` pointer to its new, more up-to-date position. .`git fetch` updates your remote-tracking branches -image::images/remote-branches-3.png[`git fetch` updates your remote references] +image::images/remote-branches-3.png[`git fetch` updates your remote-tracking branches] To demonstrate having multiple remote servers and what remote branches for those remote projects look like, let's assume you have another internal Git server that is used only for development by one of your sprint teams. This server is at `git.team1.ourcompany.com`. @@ -54,7 +54,7 @@ Now, you can run `git fetch teamone` to fetch everything the remote `teamone` se Because that server has a subset of the data your `origin` server has right now, Git fetches no data but sets a remote-tracking branch called `teamone/master` to point to the commit that `teamone` has as its `master` branch. .Remote-tracking branch for `teamone/master` -image::images/remote-branches-5.png[Remote tracking branch for `teamone/master`] +image::images/remote-branches-5.png[Remote-tracking branch for `teamone/master`] [[_pushing_branches]] ==== Pushing @@ -217,8 +217,6 @@ It will simply get the data for you and let you merge it yourself. However, there is a command called `git pull` which is essentially a `git fetch` immediately followed by a `git merge` in most cases. If you have a tracking branch set up as demonstrated in the last section, either by explicitly setting it or by having it created for you by the `clone` or `checkout` commands, `git pull` will look up what server and branch your current branch is tracking, fetch from that server and then try to merge in that remote branch. -Generally it's better to simply use the `fetch` and `merge` commands explicitly as the magic of `git pull` can often be confusing. - [[_delete_branches]] ==== Deleting Remote Branches @@ -234,5 +232,5 @@ To https://github.com/schacon/simplegit - [deleted] serverfix ---- -Basically all this does is remove the pointer from the server. +Basically all this does is to remove the pointer from the server. The Git server will generally keep the data there for a while until a garbage collection runs, so if it was accidentally deleted, it's often easy to recover. diff --git a/book-en/04-git-server/sections/generating-ssh-key.asc b/book-en/04-git-server/sections/generating-ssh-key.asc index d3429b32..d1a61daf 100644 --- a/book-en/04-git-server/sections/generating-ssh-key.asc +++ b/book-en/04-git-server/sections/generating-ssh-key.asc @@ -54,4 +54,4 @@ mZ+AW4OZPnTPI89ZPmVMLuayrD2cE86Z/il8b+gw3r3+1nKatmIkjn2so1d01QraTlMqVSsbx NrRFi9wrf+M7Q== schacon@mylaptop.local ---- -For a more in-depth tutorial on creating an SSH key on multiple operating systems, see the GitHub guide on SSH keys at https://docs.github.com/en/github/authenticating-to-github/generating-a-new-ssh-key-and-adding-it-to-the-ssh-agent[]. +For a more in-depth tutorial on creating an SSH key on multiple operating systems, see the GitHub guide on SSH keys at https://docs.github.com/en/authentication/connecting-to-github-with-ssh/generating-a-new-ssh-key-and-adding-it-to-the-ssh-agent[^]. diff --git a/book-en/04-git-server/sections/gitlab.asc b/book-en/04-git-server/sections/gitlab.asc index 51cfeb3e..97de7893 100644 --- a/book-en/04-git-server/sections/gitlab.asc +++ b/book-en/04-git-server/sections/gitlab.asc @@ -17,15 +17,16 @@ The other installation options are: * GitLab Helm chart, for use with Kubernetes. * Dockerized GitLab packages for use with Docker. * From the source files. -* Cloud provider such as AWS, Google Cloud Platform, Azure, OpenShift and Digital Ocean. +* Cloud providers such as AWS, Google Cloud Platform, Azure, OpenShift and Digital Ocean. -For more information read the https://gitlab.com/gitlab-org/gitlab-foss/-/blob/master/README.md[GitLab Community Edition (CE) readme]. +For more information read the https://gitlab.com/gitlab-org/gitlab-foss/-/blob/master/README.md[GitLab Community Edition (CE) readme^]. ==== Administration GitLab's administration interface is accessed over the web. -Simply point your browser to the hostname or IP address where GitLab is installed, and log in as the admin user. -The default username is `admin@local.host`, and the default password is `5iveL!fe` (which you must change right away). +Simply point your browser to the hostname or IP address where GitLab is installed, and log in as the `root` user. +The password will depend on your installation type but by default, Omnibus GitLab automatically generates a password for and stores it to /etc/gitlab/initial_root_password for at least 24 hours. +Follow the documentation for more details. After you've logged in, click the "`Admin area`" icon in the menu at the top right. [[gitlab_menu]] @@ -37,7 +38,7 @@ image::images/gitlab-menu.png[The “Admin area” item in the GitLab menu] Everybody using your GitLab server must have a user account. User accounts are quite simple, they mainly contain personal information attached to login data. Each user account has a *namespace*, which is a logical grouping of projects that belong to that user. -If the user +jane+ had a project named +project+, that project's url would be `http://server/jane/project`. +If the user +jane+ had a project named +project+, that project's URL would be `http://server/jane/project`. [[gitlab_users]] .The GitLab user administration screen @@ -54,7 +55,7 @@ This is obviously a much more permanent and destructive action, and you will rar ===== Groups A GitLab group is a collection of projects, along with data about how users can access those projects. -Each group has a project namespace (the same way that users do), so if the group +training+ has a project +materials+, its url would be `http://server/training/materials`. +Each group has a project namespace (the same way that users do), so if the group +training+ has a project +materials+, its URL would be `http://server/training/materials`. [[gitlab_groups]] .The GitLab group administration screen diff --git a/book-en/04-git-server/sections/gitweb.asc b/book-en/04-git-server/sections/gitweb.asc index c8d2df55..1565dc49 100644 --- a/book-en/04-git-server/sections/gitweb.asc +++ b/book-en/04-git-server/sections/gitweb.asc @@ -10,7 +10,7 @@ image::images/git-instaweb.png[The GitWeb web-based user interface] If you want to check out what GitWeb would look like for your project, Git comes with a command to fire up a temporary instance if you have a lightweight web server on your system like `lighttpd` or `webrick`. On Linux machines, `lighttpd` is often installed, so you may be able to get it to run by typing `git instaweb` in your project directory. -If you're running a Mac, Leopard comes preinstalled with Ruby, so `webrick` may be your best bet. +If you're running macOS, Leopard comes preinstalled with Ruby, so `webrick` may be your best bet. To start `instaweb` with a non-lighttpd handler, you can run it with the `--httpd` option.(((git commands, instaweb))) [source,console] @@ -36,7 +36,7 @@ First, you need to get the Git source code, which GitWeb comes with, and generat [source,console] ---- -$ git clone git://git.kernel.org/pub/scm/git/git.git +$ git clone https://git.kernel.org/pub/scm/git/git.git $ cd git/ $ make GITWEB_PROJECTROOT="/srv/git" prefix=/usr gitweb SUBDIR gitweb diff --git a/book-en/04-git-server/sections/hosted.asc b/book-en/04-git-server/sections/hosted.asc index c3ca6bc1..54eb7933 100644 --- a/book-en/04-git-server/sections/hosted.asc +++ b/book-en/04-git-server/sections/hosted.asc @@ -2,9 +2,9 @@ If you don't want to go through all of the work involved in setting up your own Git server, you have several options for hosting your Git projects on an external dedicated hosting site. Doing so offers a number of advantages: a hosting site is generally quick to set up and easy to start projects on, and no server maintenance or monitoring is involved. -Even if you set up and run your own server internally, you may still want to use a public hosting site for your open source code – it's generally easier for the open source community to find and help you with. +Even if you set up and run your own server internally, you may still want to use a public hosting site for your open source code -- it's generally easier for the open source community to find and help you with. These days, you have a huge number of hosting options to choose from, each with different advantages and disadvantages. -To see an up-to-date list, check out the GitHosting page on the main Git wiki at https://git.wiki.kernel.org/index.php/GitHosting[]. +To see an up-to-date list, check out the GitHosting page on the main Git wiki at https://archive.kernel.org/oldwiki/git.wiki.kernel.org/index.php/GitHosting.html[^]. We'll cover using GitHub in detail in <>, as it is the largest Git host out there and you may need to interact with projects hosted on it in any case, but there are dozens more to choose from should you not want to set up your own Git server. diff --git a/book-en/04-git-server/sections/protocols.asc b/book-en/04-git-server/sections/protocols.asc index be0f46e6..ff226d1e 100644 --- a/book-en/04-git-server/sections/protocols.asc +++ b/book-en/04-git-server/sections/protocols.asc @@ -7,7 +7,7 @@ Here we'll discuss what they are and in what basic circumstances you would want (((protocols, local))) The most basic is the _Local protocol_, in which the remote repository is in another directory on the same host. -This is often used if everyone on your team has access to a shared filesystem such as an https://en.wikipedia.org/wiki/Network_File_System[NFS] mount, or in the less likely case that everyone logs in to the same computer. +This is often used if everyone on your team has access to a shared filesystem such as an https://en.wikipedia.org/wiki/Network_File_System[NFS^] mount, or in the less likely case that everyone logs in to the same computer. The latter wouldn't be ideal, because all your code repository instances would reside on the same computer, making a catastrophic loss much more likely. If you have a shared mounted filesystem, then you can clone, push to, and pull from a local file-based repository. @@ -82,7 +82,7 @@ Instead of having to set up different URLs for these things, you can now use a s If you try to push and the repository requires authentication (which it normally should), the server can prompt for a username and password. The same goes for read access. -In fact, for services like GitHub, the URL you use to view the repository online (for example, https://github.com/schacon/simplegit[]) is the same URL you can use to clone and, if you have access, push over. +In fact, for services like GitHub, the URL you use to view the repository online (for example, https://github.com/schacon/simplegit[^]) is the same URL you can use to clone and, if you have access, push over. ===== Dumb HTTP @@ -90,7 +90,7 @@ In fact, for services like GitHub, the URL you use to view the repository online If the server does not respond with a Git HTTP smart service, the Git client will try to fall back to the simpler _Dumb_ HTTP protocol. The Dumb protocol expects the bare Git repository to be served like normal files from the web server. The beauty of Dumb HTTP is the simplicity of setting it up. -Basically, all you have to do is put a bare Git repository under your HTTP document root and set up a specific `post-update` hook, and you're done (See <>). +Basically, all you have to do is put a bare Git repository under your HTTP document root and set up a specific `post-update` hook, and you're done (see <>). At that point, anyone who can access the web server under which you put the repository can also clone your repository. To allow read access to your repository over HTTP, do something like this: @@ -181,7 +181,7 @@ If you want to allow anonymous read-only access to your projects and also want t (((protocols, git))) Finally, we have the Git protocol. -This is a special daemon that comes packaged with Git; it listens on a dedicated port (9418) that provides a service similar to the SSH protocol, but with absolutely no authentication. +This is a special daemon that comes packaged with Git; it listens on a dedicated port (9418) that provides a service similar to the SSH protocol, but with absolutely no authentication or cryptography. In order for a repository to be served over the Git protocol, you must create a `git-daemon-export-ok` file -- the daemon won't serve a repository without that file in it -- but, other than that, there is no security. Either the Git repository is available for everyone to clone, or it isn't. This means that there is generally no pushing over this protocol. @@ -196,9 +196,15 @@ It uses the same data-transfer mechanism as the SSH protocol but without the enc ===== The Cons -The downside of the Git protocol is the lack of authentication. -It's generally undesirable for the Git protocol to be the only access to your project. -Generally, you'll pair it with SSH or HTTPS access for the few developers who have push (write) access and have everyone else use `git://` for read-only access. +Due to the lack of TLS or other cryptography, cloning over `git://` might lead to an arbitrary code execution vulnerability, and should therefore be avoided unless you know what you are doing. + +* If you run `git clone git://example.com/project.git`, an attacker who controls e.g your router can modify the repo you just cloned, inserting malicious code into it. + If you then compile/run the code you just cloned, you will execute the malicious code. + Running `git clone http://example.com/project.git` should be avoided for the same reason. +* Running `git clone https://example.com/project.git` does not suffer from the same problem (unless the attacker can provide a TLS certificate for example.com). + Running `git clone git@example.com:project.git` only suffers from this problem if you accept a wrong SSH key fingerprint. + +It also has no authentication, i.e. anyone can clone the repo (although this is often exactly what you want). It's also probably the most difficult protocol to set up. It must run its own daemon, which requires `xinetd` or `systemd` configuration or the like, which isn't always a walk in the park. It also requires firewall access to port 9418, which isn't a standard port that corporate firewalls always allow. diff --git a/book-en/04-git-server/sections/smart-http.asc b/book-en/04-git-server/sections/smart-http.asc index 3e6cc877..753d34cd 100644 --- a/book-en/04-git-server/sections/smart-http.asc +++ b/book-en/04-git-server/sections/smart-http.asc @@ -68,5 +68,5 @@ You can do this with nearly any CGI-capable web server, so go with the one that [NOTE] ==== -For more information on configuring authentication in Apache, check out the Apache docs here: https://httpd.apache.org/docs/current/howto/auth.html[] +For more information on configuring authentication in Apache, check out the Apache docs here: https://httpd.apache.org/docs/current/howto/auth.html[^]. ==== diff --git a/book-en/05-distributed-git/sections/contributing.asc b/book-en/05-distributed-git/sections/contributing.asc index c74d2af2..2c6b0851 100644 --- a/book-en/05-distributed-git/sections/contributing.asc +++ b/book-en/05-distributed-git/sections/contributing.asc @@ -60,7 +60,7 @@ Getting in the habit of creating quality commit messages makes using and collabo As a general rule, your messages should start with a single line that's no more than about 50 characters and that describes the changeset concisely, followed by a blank line, followed by a more detailed explanation. The Git project requires that the more detailed explanation include your motivation for the change and contrast its implementation with previous behavior -- this is a good guideline to follow. Write your commit message in the imperative: "Fix bug" and not "Fixed bug" or "Fixes bug." -Here is a template you can follow, which we've lightly adapted from one https://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html[originally written by Tim Pope]: +Here is a template you can follow, which we've lightly adapted from one https://tbaggery.com/2008/04/19/a-note-about-git-commit-messages.html[originally written by Tim Pope^]: [source,text] ---- @@ -154,7 +154,7 @@ To jessica@githost:simplegit.git The last line of the output above shows a useful return message from the push operation. The basic format is `.. fromref -> toref`, where `oldref` means the old reference, `newref` means the new reference, `fromref` is the name of the local reference being pushed, and `toref` is the name of the remote reference being updated. You'll see similar output like this below in the discussions, so having a basic idea of the meaning will help in understanding the various states of the repositories. -More details are available in the documentation for https://git-scm.com/docs/git-push[git-push]. +More details are available in the documentation for https://git-scm.com/docs/git-push[git-push^]. Continuing with this example, shortly afterwards, John makes some changes, commits them to his local repository, and tries to push them to the same server: @@ -253,7 +253,7 @@ Date: Fri May 29 16:01:27 2009 -0700 Remove invalid default value ---- -The `issue54..origin/master` syntax is a log filter that asks Git to display only those commits that are on the latter branch (in this case `origin/master`) that are not on the first branch (in this case `issue54`). +The `issue54..origin/master` syntax is a log filter that asks Git to display only those commits that are on the latter branch (in this case `origin/master`) and that are not on the first branch (in this case `issue54`). We'll go over this syntax in detail in <>. From the above output, we can see that there is a single commit that John has made that Jessica has not merged into her local work. @@ -561,7 +561,7 @@ Jessica Smith (1): are available in the git repository at: - git://githost/simplegit.git featureA + https://githost/simplegit.git featureA Jessica Smith (2): Add limit to log function diff --git a/book-en/05-distributed-git/sections/distributed-workflows.asc b/book-en/05-distributed-git/sections/distributed-workflows.asc index 657692c3..b61289dc 100644 --- a/book-en/05-distributed-git/sections/distributed-workflows.asc +++ b/book-en/05-distributed-git/sections/distributed-workflows.asc @@ -92,7 +92,7 @@ Martin Fowler has made a guide "Patterns for Managing Source Code Branches". This guide covers all the common Git workflows, and explains how/when to use them. There's also a section comparing high and low integration frequencies. -https://martinfowler.com/articles/branching-patterns.html +https://martinfowler.com/articles/branching-patterns.html[^] ==== ==== Workflows Summary diff --git a/book-en/05-distributed-git/sections/maintaining.asc b/book-en/05-distributed-git/sections/maintaining.asc index b5762aaa..c377bb68 100644 --- a/book-en/05-distributed-git/sections/maintaining.asc +++ b/book-en/05-distributed-git/sections/maintaining.asc @@ -35,7 +35,7 @@ Now you're ready to add the contributed work that you received into this topic b If you receive a patch over email that you need to integrate into your project, you need to apply the patch in your topic branch to evaluate it. There are two ways to apply an emailed patch: with `git apply` or with `git am`. -===== Applying a Patch with apply +===== Applying a Patch with `apply` (((git commands, apply))) If you received the patch from someone who generated it with `git diff` or some variation of the Unix `diff` command (which is not recommended; see the next section), you can apply it with the `git apply` command. @@ -191,7 +191,7 @@ For instance, if Jessica sends you an email saying that she has a great new feat [source,console] ---- -$ git remote add jessica git://github.com/jessica/myproject.git +$ git remote add jessica https://github.com/jessica/myproject.git $ git fetch jessica $ git checkout -b rubyclient jessica/ruby-client ---- @@ -334,7 +334,7 @@ image::images/merging-workflows-4.png[After a topic branch merge] [[merwf_e]] .After a project release -image::images/merging-workflows-5.png[After a topic branch release] +image::images/merging-workflows-5.png[After a project release] This way, when people clone your project's repository, they can either check out `master` to build the latest stable version and keep up to date on that easily, or they can check out `develop`, which is the more cutting-edge content. You can also extend this concept by having an `integrate` branch where all the work is merged together. @@ -364,7 +364,7 @@ When a topic branch has finally been merged into `master`, it's removed from the The Git project also has a `maint` branch that is forked off from the last release to provide backported patches in case a maintenance release is required. Thus, when you clone the Git repository, you have four branches that you can check out to evaluate the project in different stages of development, depending on how cutting edge you want to be or how you want to contribute; and the maintainer has a structured workflow to help them vet new contributions. The Git project's workflow is specialized. -To clearly understand this you could check out the https://github.com/git/git/blob/master/Documentation/howto/maintain-git.txt[Git Maintainer's guide]. +To clearly understand this you could check out the https://github.com/git/git/blob/master/Documentation/howto/maintain-git.txt[Git Maintainer's guide^]. [[_rebase_cherry_pick]] ===== Rebasing and Cherry-Picking Workflows @@ -533,7 +533,7 @@ You now have a nice tarball and a zip archive of your project release that you c (((git commands, shortlog))) It's time to email your mailing list of people who want to know what's happening in your project. A nice way of quickly getting a sort of changelog of what has been added to your project since your last release or email is to use the `git shortlog` command. -It summarizes all the commits in the range you give it; for example, the following gives you a summary of all the commits since your last release, if your last release was named v1.0.1: +It summarizes all the commits in the range you give it; for example, the following gives you a summary of all the commits since your last release, if your last release was named `v1.0.1`: [source,console] ---- @@ -553,4 +553,4 @@ Tom Preston-Werner (4): Regenerated gemspec for version 1.0.2 ---- -You get a clean summary of all the commits since v1.0.1, grouped by author, that you can email to your list. +You get a clean summary of all the commits since `v1.0.1`, grouped by author, that you can email to your list. diff --git a/book-en/06-github/sections/1-setting-up-account.asc b/book-en/06-github/sections/1-setting-up-account.asc index 76a12a12..2ab023ec 100644 --- a/book-en/06-github/sections/1-setting-up-account.asc +++ b/book-en/06-github/sections/1-setting-up-account.asc @@ -2,7 +2,7 @@ (((GitHub, user accounts))) The first thing you need to do is set up a free user account. -Simply visit https://github.com[], choose a user name that isn't already taken, provide an email address and a password, and click the big green "`Sign up for GitHub`" button. +Simply visit https://github.com[^], choose a user name that isn't already taken, provide an email address and a password, and click the big green "`Sign up for GitHub`" button. .The GitHub sign-up form image::images/signup.png[The GitHub sign-up form] @@ -16,7 +16,7 @@ Go ahead and do this; it's pretty important (as we'll see later). GitHub provides almost all of its functionality with free accounts, except some advanced features. GitHub's paid plans include advanced tools and features as well as increased limits for free services, but we won't be covering those in this book. -To get more information about available plans and their comparison, visit https://github.com/pricing[]. +To get more information about available plans and their comparison, visit https://github.com/pricing[^]. ==== Clicking the Octocat logo at the top-left of the screen will take you to your dashboard page. @@ -37,7 +37,7 @@ image::images/account-settings.png[The “Account settings” link] Then select the "`SSH keys`" section along the left-hand side. -.The "`SSH keys`" link. +.The "`SSH keys`" link image::images/ssh-keys.png[The “SSH keys” link] From there, click the "`Add an SSH key`" button, give your key a name, paste the contents of your `~/.ssh/id_rsa.pub` (or whatever you named it) public-key file into the text area, and click "`Add key`". @@ -59,12 +59,12 @@ image::images/your-profile.png[The “Profile” link] We'll choose a copy of the Git logo that is on our hard drive and then we get a chance to crop it. -.Crop your avatar +.Crop your uploaded avatar image::images/avatar-crop.png[Crop your uploaded avatar] Now anywhere you interact on the site, people will see your avatar next to your username. -If you happen to have uploaded an avatar to the popular Gravatar service (often used for Wordpress accounts), that avatar will be used by default and you don't need to do this step. +If you happen to have uploaded an avatar to the popular Gravatar service (often used for WordPress accounts), that avatar will be used by default and you don't need to do this step. ==== Your Email Addresses @@ -72,7 +72,7 @@ The way that GitHub maps your Git commits to your user is by email address. If you use multiple email addresses in your commits and you want GitHub to link them up properly, you need to add all the email addresses you have used to the Emails section of the admin section. [[_add_email_addresses]] -.Add email addresses +.Add all your email addresses image::images/email-settings.png[Add all your email addresses] In <<_add_email_addresses>> we can see some of the different states that are possible. diff --git a/book-en/06-github/sections/2-contributing.asc b/book-en/06-github/sections/2-contributing.asc index 3f4a24cc..1dffbd9a 100644 --- a/book-en/06-github/sections/2-contributing.asc +++ b/book-en/06-github/sections/2-contributing.asc @@ -25,7 +25,6 @@ image::images/forkbutton.png[The “Fork” button] After a few seconds, you'll be taken to your new project page, with your own writeable copy of the code. - [[ch06-github_flow]] ==== The GitHub Flow @@ -43,7 +42,7 @@ Here's how it generally works: 5. Open a Pull Request on GitHub. 6. Discuss, and optionally continue committing. 7. The project owner merges or closes the Pull Request. -8. Sync the updated master back to your fork. +8. Sync the updated `master` back to your fork. This is basically the Integration Manager workflow covered in <>, but instead of using email to communicate and review changes, teams use GitHub's web based tools. @@ -52,13 +51,13 @@ Let's walk through an example of proposing a change to an open source project ho [TIP] ==== You can use the official *GitHub CLI* tool instead of the GitHub web interface for most things. -The tool can be used on Windows, MacOS, and Linux systems. -Go to the https://cli.github.com/[GitHub CLI homepage] for installation instructions and the manual. +The tool can be used on Windows, macOS, and Linux systems. +Go to the https://cli.github.com/[GitHub CLI homepage^] for installation instructions and the manual. ==== ===== Creating a Pull Request -Tony is looking for code to run on his Arduino programmable microcontroller and has found a great program file on GitHub at https://github.com/schacon/blink[]. +Tony is looking for code to run on his Arduino programmable microcontroller and has found a great program file on GitHub at https://github.com/schacon/blink[^]. .The project we want to contribute to image::images/blink-01-start.png[The project we want to contribute to] @@ -135,7 +134,7 @@ It is almost always worthwhile to put some effort into this, since a good descri We also see a list of the commits in our topic branch that are "`ahead`" of the `master` branch (in this case, just the one) and a unified diff of all the changes that will be made should this branch get merged by the project owner. .Pull Request creation page -image::images/blink-03-pull-request-open.png[Pull Request creation] +image::images/blink-03-pull-request-open.png[Pull Request creation page] When you hit the 'Create pull request' button on this screen, the owner of the project you forked will get a notification that someone is suggesting a change and will link to a page that has all of this information on it. @@ -154,14 +153,14 @@ Where this conversation may take place over email in the workflows presented in The project owner can review the unified diff and leave a comment by clicking on any of the lines. .Comment on a specific line of code in a Pull Request -image::images/blink-04-pr-comment.png[PR line comment] +image::images/blink-04-pr-comment.png[Comment on a specific line of code in a Pull Request] Once the maintainer makes this comment, the person who opened the Pull Request (and indeed, anyone else watching the repository) will get a notification. We'll go over customizing this later, but if he had email notifications turned on, Tony would get an email like this: [[_email_notification]] .Comments sent as email notifications -image::images/blink-04-email.png[Email notification] +image::images/blink-04-email.png[Comments sent as email notifications] Anyone can also leave general comments on the Pull Request. In <<_pr_discussion>> we can see an example of the project owner both commenting on a line of code and then leaving a general comment in the discussion section. @@ -169,7 +168,7 @@ You can see that the code comments are brought into the conversation as well. [[_pr_discussion]] .Pull Request discussion page -image::images/blink-05-general-comment.png[PR discussion page] +image::images/blink-05-general-comment.png[Pull Request discussion page] Now the contributor can see what they need to do in order to get their change accepted. Luckily this is very straightforward. @@ -180,7 +179,7 @@ Adding commits to an existing Pull Request doesn't trigger a notification, so on [[_pr_final]] .Pull Request final -image::images/blink-06-final.png[PR final] +image::images/blink-06-final.png[Pull Request final] An interesting thing to notice is that if you click on the "`Files Changed`" tab on this Pull Request, you'll get the "`unified`" diff -- that is, the total aggregate difference that would be introduced to your main branch if this topic branch was merged in. In `git diff` terms, it basically automatically shows you `git diff master...` for the branch this Pull Request is based on. @@ -229,7 +228,7 @@ GitHub will test this for you and let you know at the bottom of every Pull Reque [[_pr_fail]] .Pull Request does not merge cleanly -image::images/pr-01-fail.png[PR merge failure] +image::images/pr-01-fail.png[Pull Request does not merge cleanly] If you see something like <<_pr_fail>>, you'll want to fix your branch so that it turns green and the maintainer doesn't have to do extra work. @@ -287,7 +286,7 @@ Once you do that, the Pull Request will be automatically updated and re-checked [[_pr_merge_fix]] .Pull Request now merges cleanly -image::images/pr-02-merge-fix.png[PR fixed] +image::images/pr-02-merge-fix.png[Pull Request now merges cleanly] One of the great things about Git is that you can do that continuously. If you have a very long-running project, you can easily merge from the target branch over and over again and only have to deal with conflicts that have arisen since the last time that you merged, making the process very manageable. @@ -314,13 +313,13 @@ We can fill out the description just like <<_pr_references>>. [[_pr_references]] .Cross references in a Pull Request -image::images/mentions-01-syntax.png[PR references] +image::images/mentions-01-syntax.png[Cross references in a Pull Request] When we submit this pull request, we'll see all of that rendered like <<_pr_references_render>>. [[_pr_references_render]] .Cross references rendered in a Pull Request -image::images/mentions-02-render.png[PR references rendered] +image::images/mentions-02-render.png[Cross references rendered in a Pull Request] Notice that the full GitHub URL we put in there was shortened to just the information needed. @@ -330,7 +329,7 @@ The link will look something like <<_pr_closed>>. [[_pr_closed]] .Link back to the new Pull Request in the closed Pull Request timeline -image::images/mentions-03-closed.png[PR closed] +image::images/mentions-03-closed.png[Link back to the new Pull Request in the closed Pull Request timeline] In addition to issue numbers, you can also reference a specific commit by SHA-1. You have to specify a full 40 character SHA-1, but if GitHub sees that in a comment, it will link directly to the commit. @@ -339,14 +338,14 @@ Again, you can reference commits in forks or other repositories in the same way ==== GitHub Flavored Markdown Linking to other Issues is just the beginning of interesting things you can do with almost any text box on GitHub. -In Issue and Pull Request descriptions, comments, code comments and more, you can use what is called "`GitHub Flavored Markdown`". +In Issue and Pull Request descriptions, comments, code comments and more, you can use what is called "`GitHub Flavored Markdown`". Markdown is like writing in plain text but which is rendered richly. See <<_example_markdown>> for an example of how comments or text can be written and then rendered using Markdown. [[_example_markdown]] .An example of GitHub Flavored Markdown as written and as rendered -image::images/markdown-01-example.png[Example Markdown] +image::images/markdown-01-example.png[An example of GitHub Flavored Markdown as written and as rendered] The GitHub flavor of Markdown adds more things you can do beyond the basic Markdown syntax. These can all be really useful when creating useful Pull Request or Issue comments or descriptions. @@ -370,7 +369,7 @@ If we include this in the description of our Pull Request or Issue, we'll see it [[_eg_task_lists]] .Task lists rendered in a Markdown comment -image::images/markdown-02-tasks.png[Example Task List] +image::images/markdown-02-tasks.png[Task lists rendered in a Markdown comment] This is often used in Pull Requests to indicate what all you would like to get done on the branch before the Pull Request will be ready to merge. The really cool part is that you can simply click the checkboxes to update the comment -- you don't have to edit the Markdown directly to check tasks off. @@ -382,7 +381,7 @@ You can see an example of this in <<_task_list_progress>>. [[_task_list_progress]] .Task list summary in the Pull Request list -image::images/markdown-03-task-summary.png[Example Task List] +image::images/markdown-03-task-summary.png[Task list summary in the Pull Request list] These are incredibly useful when you open a Pull Request early and use it to track your progress through the implementation of the feature. @@ -409,7 +408,7 @@ In the case of the above example, it would end up rendering like <<_md_code>>. [[_md_code]] .Rendered fenced code example -image::images/markdown-04-fenced-code.png[Rendered fenced code] +image::images/markdown-04-fenced-code.png[Rendered fenced code example] ===== Quoting @@ -431,7 +430,7 @@ Once rendered, the comment will look like <<_md_quote>>. [[_md_quote]] .Rendered quoting example -image::images/markdown-05-quote.png[Rendered quoting] +image::images/markdown-05-quote.png[Rendered quoting example] ===== Emoji @@ -442,7 +441,7 @@ If you are typing a comment and you start with a `:` character, an autocompleter [[_md_emoji_auto]] .Emoji autocompleter in action -image::images/markdown-06-emoji-complete.png[Emoji autocompleter] +image::images/markdown-06-emoji-complete.png[Emoji autocompleter in action] Emojis take the form of `::` anywhere in the comment. For instance, you could write something like this: @@ -462,17 +461,16 @@ When rendered, it would look something like <<_md_emoji>>. [[_md_emoji]] .Heavy emoji commenting -image::images/markdown-07-emoji.png[Emoji] +image::images/markdown-07-emoji.png[Heavy emoji commenting] Not that this is incredibly useful, but it does add an element of fun and emotion to a medium that is otherwise hard to convey emotion in. - [NOTE] ==== There are actually quite a number of web services that make use of emoji characters these days. A great cheat sheet to reference to find emoji that expresses what you want to say can be found at: -https://www.webfx.com/tools/emoji-cheat-sheet/ +https://www.webfx.com/tools/emoji-cheat-sheet/[^] ==== ===== Images @@ -482,7 +480,7 @@ In addition to adding Markdown image links to comments, which can be difficult t [[_md_drag]] .Drag and drop images to upload them and auto-embed them -image::images/markdown-08-drag-drop.png[Drag and drop images] +image::images/markdown-08-drag-drop.png[Drag and drop images to upload them and auto-embed them] If you look at <<_md_drag>>, you can see a small "`Parsed as Markdown`" hint above the text area. Clicking on that will give you a full cheat sheet of everything you can do with Markdown on GitHub. diff --git a/book-en/06-github/sections/3-maintaining.asc b/book-en/06-github/sections/3-maintaining.asc index a73a545c..2505e86a 100644 --- a/book-en/06-github/sections/3-maintaining.asc +++ b/book-en/06-github/sections/3-maintaining.asc @@ -13,7 +13,7 @@ image::images/newrepo.png[The “Your repositories” area] [[_new_repo_dropdown]] .The "`New repository`" dropdown -image::images/new-repo.png[The “new repository” dropdown] +image::images/new-repo.png[The “New repository” dropdown] This takes you to the "`new repository`" form: @@ -21,7 +21,7 @@ This takes you to the "`new repository`" form: image::images/newrepoform.png[The “new repository” form] All you really have to do here is provide a project name; the rest of the fields are completely optional. -For now, just click the "`Create Repository`" button, and boom – you have a new repository on GitHub, named `/`. +For now, just click the "`Create Repository`" button, and boom -- you have a new repository on GitHub, named `/`. Since you have no code there yet, GitHub will show you instructions for how to create a brand-new Git repository, or connect an existing Git project. We won't belabor this here; if you need a refresher, check out <>. @@ -53,7 +53,7 @@ Then, just type a username into the box, and click "`Add collaborator.`" You can repeat this as many times as you like to grant access to everyone you like. If you need to revoke access, just click the "`X`" on the right-hand side of their row. -.Repository collaborators +.The repository collaborators box image::images/collaborators.png[The repository collaborators box] ==== Managing Pull Requests @@ -73,7 +73,7 @@ You should get an email notifying you about the new Pull Request and it should l [[_email_pr]] .Email notification of a new Pull Request -image::images/maint-01-email.png[Pull Request email notification] +image::images/maint-01-email.png[Email notification of a new Pull Request] There are a few things to notice about this email. It will give you a small diffstat -- a list of files that have changed in the Pull Request and by how much. @@ -101,7 +101,7 @@ Every time someone else comments on the Pull Request you will continue to get em They will each have a link to the Pull Request where the activity is happening and you can also directly respond to the email to comment on the Pull Request thread. .Responses to emails are included in the thread -image::images/maint-03-email-resp.png[Email response] +image::images/maint-03-email-resp.png[Responses to emails are included in the thread] Once the code is in a place you like and want to merge it in, you can either pull the code down and merge it locally, either with the `git pull ` syntax we saw earlier, or by adding the fork as a remote and fetching and merging. @@ -112,7 +112,7 @@ As you can see in <<_merge_button>>, GitHub gives you all of this information if [[_merge_button]] .Merge button and instructions for merging a Pull Request manually -image::images/maint-02-merge.png[Merge button] +image::images/maint-02-merge.png[Merge button and instructions for merging a Pull Request manually] If you decide you don't want to merge it, you can also just close the Pull Request and the person who opened it will be notified. @@ -218,7 +218,6 @@ The eagle-eyed among you would note the `head` on the end of the remote portion There's also a `refs/pull/#/merge` ref on the GitHub side, which represents the commit that would result if you push the "`merge`" button on the site. This can allow you to test the merge before even hitting the button. - ===== Pull Requests on Pull Requests Not only can you open Pull Requests that target the main or `master` branch, you can actually open a Pull Request targeting any branch in the network. @@ -231,7 +230,7 @@ If you hit the "`Edit`" button at the right of that box you can change not only [[_pr_targets]] .Manually change the Pull Request target fork and branch -image::images/maint-04-target.png[PR targets] +image::images/maint-04-target.png[Manually change the Pull Request target fork and branch] Here you can fairly easily specify to merge your new branch into another Pull Request or another fork of the project. @@ -242,7 +241,7 @@ GitHub also has a pretty nice notifications system built in that can come in han In any comment you can start typing a `@` character and it will begin to autocomplete with the names and usernames of people who are collaborators or contributors in the project. .Start typing @ to mention someone -image::images/maint-05-mentions.png[Mentions] +image::images/maint-05-mentions.png[Start typing @ to mention someone] You can also mention a user who is not in that dropdown, but often the autocompleter can make it faster. @@ -255,7 +254,7 @@ You will also be subscribed to something if you opened it, if you're watching th If you no longer wish to receive notifications, there is an "`Unsubscribe`" button on the page you can click to stop receiving updates on it. .Unsubscribe from an Issue or Pull Request -image::images/maint-06-unsubscribe.png[Unsubscribe] +image::images/maint-06-unsubscribe.png[Unsubscribe from an Issue or Pull Request] ===== The Notifications Page @@ -263,7 +262,7 @@ When we mention "`notifications`" here with respect to GitHub, we mean a specifi If you go to the "`Notification center`" tab from the settings page, you can see some of the options you have. .Notification center options -image::images/maint-07-notifications.png[Notification center] +image::images/maint-07-notifications.png[Notification center options] The two choices are to get notifications over "`Email`" and over "`Web`" and you can choose either, neither or both for when you actively participate in things and for activity on repositories you are watching. @@ -310,7 +309,7 @@ X-GitHub-Recipient-Address: tchacon@example.com There are a couple of interesting things here. If you want to highlight or re-route emails to this particular project or even Pull Request, the information in `Message-ID` gives you all the data in `///` format. -If this were an issue, for example, the `` field would have been "`issues`" rather than "`pull`". +If this was an issue, for example, the `` field would have been "`issues`" rather than "`pull`". The `List-Post` and `List-Unsubscribe` fields mean that if you have a mail client that understands those, you can easily post to the list or "`Unsubscribe`" from the thread. That would be essentially the same as clicking the "`mute`" button on the web version of the notification or "`Unsubscribe`" on the Issue or Pull Request page itself. @@ -325,7 +324,7 @@ There are a couple of special files that GitHub will notice if they are present The first is the `README` file, which can be of nearly any format that GitHub recognizes as prose. For example, it could be `README`, `README.md`, `README.asciidoc`, etc. -If GitHub sees a README file in your source, it will render it on the landing page of the project. +If GitHub sees a `README` file in your source, it will render it on the landing page of the project. Many teams use this file to hold all the relevant project information for someone who might be new to the repository or project. This generally includes things like: @@ -345,7 +344,7 @@ If you have a file named `CONTRIBUTING` with any file extension, GitHub will sho [[_contrib_file]] .Opening a Pull Request when a CONTRIBUTING file exists -image::images/maint-09-contrib.png[Contributing notice] +image::images/maint-09-contrib.png[Opening a Pull Request when a CONTRIBUTING file exists] The idea here is that you can specify specific things you want or don't want in a Pull Request sent to your project. This way people may actually read the guidelines before opening the Pull Request. @@ -360,7 +359,7 @@ If you are using a branch other than "`master`" as your default branch that you [[_default_branch]] .Change the default branch for a project -image::images/maint-10-default-branch.png[Default branch] +image::images/maint-10-default-branch.png[Change the default branch for a project] Simply change the default branch in the dropdown and that will be the default for all major operations from then on, including which branch is checked out by default when someone clones the repository. @@ -370,7 +369,7 @@ If you would like to transfer a project to another user or an organization in Gi [[_transfer_project]] .Transfer a project to another GitHub user or Organization -image::images/maint-11-transfer.png[Transfer] +image::images/maint-11-transfer.png[Transfer a project to another GitHub user or Organization] This is helpful if you are abandoning a project and someone wants to take it over, or if your project is getting bigger and want to move it into an organization. diff --git a/book-en/06-github/sections/5-scripting.asc b/book-en/06-github/sections/5-scripting.asc index 3ab8516a..c755afa1 100644 --- a/book-en/06-github/sections/5-scripting.asc +++ b/book-en/06-github/sections/5-scripting.asc @@ -17,7 +17,7 @@ Under the "`Webhooks and Services`" tab you will see something like <<_services_ [[_services_hooks]] .Services and Hooks configuration section -image::images/scripting-01-services.png[Services and hooks] +image::images/scripting-01-services.png[Services and Hooks configuration section] There are dozens of services you can choose from, most of them integrations into other commercial and open source systems. Most of them are for Continuous Integration services, bug and issue trackers, chat room systems and documentation systems. @@ -26,7 +26,7 @@ If you choose "`email`" from the "`Add Service`" dropdown, you'll get a configur [[_service_config]] .Email service configuration -image::images/scripting-02-email-service.png[Email service] +image::images/scripting-02-email-service.png[Email service configuration] In this case, if we hit the "`Add service`" button, the email address we specified will get an email every time someone pushes to the repository. Services can listen for lots of different types of events, but most only listen for push events and then do something with that data. @@ -47,7 +47,7 @@ This will bring you to a page that looks like <<_web_hook>>. [[_web_hook]] .Web hook configuration -image::images/scripting-03-webhook.png[Web hook] +image::images/scripting-03-webhook.png[Web hook configuration] The configuration for a web hook is pretty simple. In most cases you simply enter a URL and a secret key and hit "`Add webhook`". @@ -103,11 +103,11 @@ This makes it incredibly easy to test and debug your hooks. [[_web_hook_debug]] .Web hook debugging information -image::images/scripting-04-webhook-debug.png[Webhook debug] +image::images/scripting-04-webhook-debug.png[Web hook debugging information] The other great feature of this is that you can redeliver any of the payloads to test your service easily. -For more information on how to write webhooks and all the different event types you can listen for, go to the GitHub Developer documentation at https://developer.github.com/webhooks/[]. +For more information on how to write webhooks and all the different event types you can listen for, go to the GitHub Developer documentation at https://docs.github.com/en/webhooks-and-events/webhooks/about-webhooks[^]. ==== The GitHub API @@ -165,7 +165,6 @@ hs_err_pid* } ---- - ==== Commenting on an Issue However, if you want to do an action on the website such as comment on an Issue or Pull Request or if you want to view or interact with private content, you'll need to authenticate. @@ -176,7 +175,7 @@ You can generate this from the "`Applications`" tab of your settings page. [[_access_token]] .Generate your access token from the "`Applications`" tab of your settings page -image::images/scripting-05-access-token.png[Access Token] +image::images/scripting-05-access-token.png[Generate your access token from the “Applications” tab of your settings page] It will ask you which scopes you want for this token and a description. Make sure to use a good description so you feel comfortable removing the token when your script or application is no longer used. @@ -219,7 +218,7 @@ Now if you go to that issue, you can see the comment that we just successfully p [[_api_comment]] .A comment posted from the GitHub API -image::images/scripting-06-comment.png[API Comment] +image::images/scripting-06-comment.png[A comment posted from the GitHub API] You can use the API to do just about anything you can do on the website -- creating and setting milestones, assigning people to Issues and Pull Requests, creating and changing labels, accessing commit data, creating new commits and branches, opening, closing or merging Pull Requests, creating and editing teams, commenting on lines of code in a Pull Request, searching the site and on and on. @@ -286,7 +285,7 @@ If someone opens a new Pull Request on GitHub and this hook is set up, you may s [[_commit_status]] .Commit status via the API -image::images/scripting-07-status.png[Commit status] +image::images/scripting-07-status.png[Commit status via the API] You can now see a little green check mark next to the commit that has a "`Signed-off-by`" string in the message and a red cross through the one where the author forgot to sign off. You can also see that the Pull Request takes the status of the last commit on the branch and warns you if it is a failure. @@ -296,7 +295,7 @@ This is really useful if you're using this API for test results so you don't acc Though we've been doing nearly everything through `curl` and simple HTTP requests in these examples, several open-source libraries exist that make this API available in a more idiomatic way. At the time of this writing, the supported languages include Go, Objective-C, Ruby, and .NET. -Check out https://github.com/octokit[] for more information on these, as they handle much of the HTTP for you. +Check out https://github.com/octokit[^] for more information on these, as they handle much of the HTTP for you. Hopefully these tools can help you customize and modify GitHub to work better for your specific workflows. -For complete documentation on the entire API as well as guides for common tasks, check out https://developer.github.com[]. +For complete documentation on the entire API as well as guides for common tasks, check out https://docs.github.com/[^]. diff --git a/book-en/07-git-tools/git-credential-read-only b/book-en/07-git-tools/git-credential-read-only index b98833c4..9e984dca 100755 --- a/book-en/07-git-tools/git-credential-read-only +++ b/book-en/07-git-tools/git-credential-read-only @@ -11,7 +11,7 @@ OptionParser.new do |opts| end.parse! exit(0) unless ARGV[0].downcase == 'get' # <2> -exit(0) unless File.exists? path +exit(0) unless File.exist? path known = {} # <3> while line = STDIN.gets diff --git a/book-en/07-git-tools/sections/advanced-merging.asc b/book-en/07-git-tools/sections/advanced-merging.asc index 1fdf6d58..7ace27bc 100644 --- a/book-en/07-git-tools/sections/advanced-merging.asc +++ b/book-en/07-git-tools/sections/advanced-merging.asc @@ -164,7 +164,7 @@ What we really need to do is run the file we're trying to merge in through a `do So how would we do that? First, we get into the merge conflict state. -Then we want to get copies of my version of the file, their version (from the branch we're merging in) and the common version (from where both sides branched off). +Then we want to get copies of our version of the file, their version (from the branch we're merging in) and the common version (from where both sides branched off). Then we want to fix up either their side or our side and re-try the merge again for just this single file. Getting the three file versions is actually pretty easy. @@ -580,8 +580,8 @@ The history with the revert commit looks like this: .History after `git revert -m 1` image::images/undomerge-revert.png[History after `git revert -m 1`] -The new commit `^M` has exactly the same contents as `C6`, so starting from here it's as if the merge never happened, except that the now-unmerged commits are still in `HEAD`’s history. -Git will get confused if you try to merge `topic` into `master` again: +The new commit `^M` has exactly the same contents as `C6`, so starting from here it's as if the merge never happened, except that the now-unmerged commits are still in ``HEAD```'s history. +Git will get confused if you try to merge ``topic`` into ``master`` again: [source,console] ---- diff --git a/book-en/07-git-tools/sections/bundling.asc b/book-en/07-git-tools/sections/bundling.asc index f0752173..79cb1b8a 100644 --- a/book-en/07-git-tools/sections/bundling.asc +++ b/book-en/07-git-tools/sections/bundling.asc @@ -80,7 +80,7 @@ b1ec324 First commit First we need to determine the range of commits we want to include in the bundle. Unlike the network protocols which figure out the minimum set of data to transfer over the network for us, we'll have to figure this out manually. - Now, you could just do the same thing and bundle the entire repository, which will work, but it's better to just bundle up the difference - just the three commits we just made locally. +Now, you could just do the same thing and bundle the entire repository, which will work, but it's better to just bundle up the difference - just the three commits we just made locally. In order to do that, you'll have to calculate the difference. As we described in <>, you can specify a range of commits in a number of ways. diff --git a/book-en/07-git-tools/sections/credentials.asc b/book-en/07-git-tools/sections/credentials.asc index 820e9356..7c7bc6ed 100644 --- a/book-en/07-git-tools/sections/credentials.asc +++ b/book-en/07-git-tools/sections/credentials.asc @@ -4,7 +4,7 @@ (((credentials))) (((git commands, credential))) If you use the SSH transport for connecting to remotes, it's possible for you to have a key without a passphrase, which allows you to securely transfer data without typing in your username and password. -However, this isn't possible with the HTTP protocols – every connection needs a username and password. +However, this isn't possible with the HTTP protocols -- every connection needs a username and password. This gets even harder for systems with two-factor authentication, where the token you use for a password is randomly generated and unpronounceable. Fortunately, Git has a credentials system that can help with this. @@ -17,11 +17,12 @@ Git has a few options provided in the box: * The "`store`" mode saves the credentials to a plain-text file on disk, and they never expire. This means that until you change your password for the Git host, you won't ever have to type in your credentials again. The downside of this approach is that your passwords are stored in cleartext in a plain file in your home directory. -* If you're using a Mac, Git comes with an "`osxkeychain`" mode, which caches credentials in the secure keychain that's attached to your system account. +* If you're using macOS, Git comes with an "`osxkeychain`" mode, which caches credentials in the secure keychain that's attached to your system account. This method stores the credentials on disk, and they never expire, but they're encrypted with the same system that stores HTTPS certificates and Safari auto-fills. -* If you're using Windows, you can install a helper called "`Git Credential Manager for Windows.`" +* If you're using Windows, you can enable the *Git Credential Manager* feature when installing https://gitforwindows.org/[Git for Windows] or separately install https://github.com/git-ecosystem/git-credential-manager/releases/latest[the latest GCM] as a standalone service. This is similar to the "`osxkeychain`" helper described above, but uses the Windows Credential Store to control sensitive information. - It can be found at https://github.com/Microsoft/Git-Credential-Manager-for-Windows[]. + It can also serve credentials to WSL1 or WSL2. + See https://github.com/git-ecosystem/git-credential-manager#readme[GCM Install Instructions] for more information. You can choose one of these methods by setting a Git configuration value: @@ -115,7 +116,7 @@ For the `get` action, however, Git is very interested in what the helper has to If the helper doesn't know anything useful, it can simply exit with no output, but if it does know, it should augment the provided information with the information it has stored. The output is treated like a series of assignment statements; anything provided will replace what Git already knows. -Here's the same example from above, but skipping git-credential and going straight for git-credential-store: +Here's the same example from above, but skipping `git-credential` and going straight for `git-credential-store`: [source,console] ---- diff --git a/book-en/07-git-tools/sections/debugging.asc b/book-en/07-git-tools/sections/debugging.asc index bc9d4cad..dd615c1c 100644 --- a/book-en/07-git-tools/sections/debugging.asc +++ b/book-en/07-git-tools/sections/debugging.asc @@ -111,7 +111,7 @@ Bisecting: 1 revisions left to test after this ---- This commit is fine, and now Git has all the information it needs to determine where the issue was introduced. -It tells you the SHA-1 of the first bad commit and show some of the commit information and which files were modified in that commit so you can figure out what happened that may have introduced this bug: +It tells you the SHA-1 of the first bad commit and shows some of the commit information and which files were modified in that commit so you can figure out what happened that may have introduced this bug: [source,console] ---- diff --git a/book-en/07-git-tools/sections/replace.asc b/book-en/07-git-tools/sections/replace.asc index 5da498f3..fd7c8ecd 100644 --- a/book-en/07-git-tools/sections/replace.asc +++ b/book-en/07-git-tools/sections/replace.asc @@ -29,7 +29,8 @@ We want to break this up into two lines of history. One line goes from commit one to commit four - that will be the historical one. The second line will just be commits four and five - that will be the recent history. -image::images/replace1.png[] +.Example Git history +image::images/replace1.png[Example Git history] Well, creating the historical history is easy, we can just put a branch in the history and then push that branch to the `master` branch of a new remote repository. @@ -44,7 +45,8 @@ c6e1e95 (history) Fourth commit c1822cf First commit ---- -image::images/replace2.png[] +.Creating a new `history` branch +image::images/replace2.png[Creating a new `history` branch] Now we can push the new `history` branch to the `master` branch of our new repository: @@ -97,7 +99,8 @@ On occasions when we're doing weirder things like this, they allow us to do real You can read more about plumbing commands in <>. ===== -image::images/replace3.png[] +.Creating a base commit using `commit-tree` +image::images/replace3.png[Creating a base commit using `commit-tree`] OK, so now that we have a base commit, we can rebase the rest of our history on top of that with `git rebase --onto`. The `--onto` argument will be the SHA-1 we just got back from `commit-tree` and the rebase point will be the third commit (the parent of the first commit we want to keep, `9c68fdc`): @@ -110,7 +113,8 @@ Applying: fourth commit Applying: fifth commit ---- -image::images/replace4.png[] +.Rebasing the history on top of the base commit +image::images/replace4.png[Rebasing the history on top of the base commit] OK, so now we've re-written our recent history on top of a throw away base commit that now has instructions in it on how to reconstitute the entire history if we wanted to. We can push that new history to a new project and now when people clone that repository, they will only see the most recent two commits and then a base commit with instructions. @@ -172,7 +176,8 @@ c1822cf First commit Cool, right? Without having to change all the SHA-1s upstream, we were able to replace one commit in our history with an entirely different commit and all the normal tools (`bisect`, `blame`, etc) will work how we would expect them to. -image::images/replace5.png[] +.Combining the commits with `git replace` +image::images/replace5.png[Combining the commits with `git replace`] Interestingly, it still shows `81a708d` as the SHA-1, even though it's actually using the `c6e1e95` commit data that we replaced it with. Even if you run a command like `cat-file`, it will show you the replaced data: diff --git a/book-en/07-git-tools/sections/rerere.asc b/book-en/07-git-tools/sections/rerere.asc index 35a65d14..dd3e60ea 100644 --- a/book-en/07-git-tools/sections/rerere.asc +++ b/book-en/07-git-tools/sections/rerere.asc @@ -38,7 +38,8 @@ end In one branch we change the word "`hello`" to "`hola`", then in another branch we change the "`world`" to "`mundo`", just like before. -image::images/rerere1.png[] +.Two branches changing the same part of the same file differently +image::images/rerere1.png[Two branches changing the same part of the same file differently] When we merge the two branches together, we'll get a merge conflict: @@ -143,7 +144,8 @@ Recorded resolution for 'hello.rb'. You can see that it "Recorded resolution for FILE". -image::images/rerere2.png[] +.Recorded resolution for FILE +image::images/rerere2.png[Recorded resolution for FILE] Now, let's undo that merge and then rebase it on top of our `master` branch instead. We can move our branch back by using `git reset` as we saw in <>. @@ -205,7 +207,8 @@ index a440db6,54336ba..0000000 end ---- -image::images/rerere3.png[] +.Automatically resolved merge conflict using previous resolution +image::images/rerere3.png[Automatically resolved merge conflict using previous resolution] You can also recreate the conflicted file state with `git checkout`: diff --git a/book-en/07-git-tools/sections/reset.asc b/book-en/07-git-tools/sections/reset.asc index bb4c01b5..f5b95341 100644 --- a/book-en/07-git-tools/sections/reset.asc +++ b/book-en/07-git-tools/sections/reset.asc @@ -92,23 +92,27 @@ $ tree Git's typical workflow is to record snapshots of your project in successively better states, by manipulating these three trees. -image::images/reset-workflow.png[] +.Git's typical workflow +image::images/reset-workflow.png[Git's typical workflow] Let's visualize this process: say you go into a new directory with a single file in it. We'll call this *v1* of the file, and we'll indicate it in blue. Now we run `git init`, which will create a Git repository with a HEAD reference which points to the unborn `master` branch. -image::images/reset-ex1.png[] +.Newly-initialized Git repository with unstaged file in the working directory +image::images/reset-ex1.png[Newly-initialized Git repository with unstaged file in the working directory] At this point, only the working directory tree has any content. Now we want to commit this file, so we use `git add` to take content in the working directory and copy it to the index. -image::images/reset-ex2.png[] +.File is copied to index on `git add` +image::images/reset-ex2.png[File is copied to index on `git add`] Then we run `git commit`, which takes the contents of the index and saves it as a permanent snapshot, creates a commit object which points to that snapshot, and updates `master` to point to that commit. -image::images/reset-ex3.png[] +.The `git commit` step +image::images/reset-ex3.png[The `git commit` step] If we run `git status`, we'll see no changes, because all three trees are the same. @@ -116,17 +120,20 @@ Now we want to make a change to that file and commit it. We'll go through the same process; first, we change the file in our working directory. Let's call this *v2* of the file, and indicate it in red. -image::images/reset-ex4.png[] +.Git repository with changed file in the working directory +image::images/reset-ex4.png[Git repository with changed file in the working directory] If we run `git status` right now, we'll see the file in red as "`Changes not staged for commit`", because that entry differs between the index and the working directory. Next we run `git add` on it to stage it into our index. -image::images/reset-ex5.png[] +.Staging change to index +image::images/reset-ex5.png[Staging change to index] At this point, if we run `git status`, we will see the file in green under "`Changes to be committed`" because the index and HEAD differ -- that is, our proposed next commit is now different from our last commit. Finally, we run `git commit` to finalize the commit. -image::images/reset-ex6.png[] +.The `git commit` step with changed file +image::images/reset-ex6.png[The `git commit` step with changed file] Now `git status` will give us no output, because all three trees are the same again. @@ -140,7 +147,8 @@ The `reset` command makes more sense when viewed in this context. For the purposes of these examples, let's say that we've modified `file.txt` again and committed it a third time. So now our history looks like this: -image::images/reset-start.png[] +.Git repository with three commits +image::images/reset-start.png[Git repository with three commits] Let's now walk through exactly what `reset` does when you call it. It directly manipulates these three trees in a simple and predictable way. @@ -152,7 +160,8 @@ The first thing `reset` will do is move what HEAD points to. This isn't the same as changing HEAD itself (which is what `checkout` does); `reset` moves the branch that HEAD is pointing to. This means if HEAD is set to the `master` branch (i.e. you're currently on the `master` branch), running `git reset 9e5e6a4` will start by making `master` point to `9e5e6a4`. -image::images/reset-soft.png[] +.Soft reset +image::images/reset-soft.png[Soft reset] No matter what form of `reset` with a commit you invoke, this is the first thing it will always try to do. With `reset --soft`, it will simply stop there. @@ -162,13 +171,14 @@ When you run `git commit`, Git creates a new commit and moves the branch that HE When you `reset` back to `HEAD~` (the parent of HEAD), you are moving the branch back to where it was, without changing the index or working directory. You could now update the index and run `git commit` again to accomplish what `git commit --amend` would have done (see <<_git_amend>>). -===== Step 2: Updating the Index (--mixed) +===== Step 2: Updating the Index (`--mixed`) Note that if you run `git status` now you'll see in green the difference between the index and what the new HEAD is. The next thing `reset` will do is to update the index with the contents of whatever snapshot HEAD now points to. -image::images/reset-mixed.png[] +.Mixed reset +image::images/reset-mixed.png[Mixed reset] If you specify the `--mixed` option, `reset` will stop at this point. This is also the default, so if you specify no option at all (just `git reset HEAD~` in this case), this is where the command will stop. @@ -176,12 +186,13 @@ This is also the default, so if you specify no option at all (just `git reset HE Now take another second to look at that diagram and realize what happened: it still undid your last `commit`, but also _unstaged_ everything. You rolled back to before you ran all your `git add` and `git commit` commands. -===== Step 3: Updating the Working Directory (--hard) +===== Step 3: Updating the Working Directory (`--hard`) The third thing that `reset` will do is to make the working directory look like the index. If you use the `--hard` option, it will continue to this stage. -image::images/reset-hard.png[] +.Hard reset +image::images/reset-hard.png[Hard reset] So let's think about what just happened. You undid your last commit, the `git add` and `git commit` commands, *and* all the work you did in your working directory. @@ -213,19 +224,22 @@ This form (since you did not specify a commit SHA-1 or branch, and you didn't sp So it essentially just copies `file.txt` from HEAD to the index. -image::images/reset-path1.png[] +.Mixed reset with a path +image::images/reset-path1.png[Mixed reset with a path] This has the practical effect of _unstaging_ the file. If we look at the diagram for that command and think about what `git add` does, they are exact opposites. -image::images/reset-path2.png[] +.Staging file to index +image::images/reset-path2.png[Staging file to index] This is why the output of the `git status` command suggests that you run this to unstage a file (see <> for more on this). We could just as easily not let Git assume we meant "`pull the data from HEAD`" by specifying a specific commit to pull that file version from. We would just run something like `git reset eb43bf file.txt`. -image::images/reset-path3.png[] +.Soft reset with a path to a specific commit +image::images/reset-path3.png[Soft reset with a path to a specific commit] This effectively does the same thing as if we had reverted the content of the file to *v1* in the working directory, ran `git add` on it, then reverted it back to *v3* again (without actually going through all those steps). If we run `git commit` now, it will record a change that reverts that file back to *v1*, even though we never actually had it in our working directory again. @@ -244,18 +258,21 @@ You can use `reset` to quickly and easily squash them into a single commit that Let's say you have a project where the first commit has one file, the second commit added a new file and changed the first, and the third commit changed the first file again. The second commit was a work in progress and you want to squash it down. -image::images/reset-squash-r1.png[] +.Git repository +image::images/reset-squash-r1.png[Git repository] You can run `git reset --soft HEAD~2` to move the HEAD branch back to an older commit (the most recent commit you want to keep): -image::images/reset-squash-r2.png[] +.Moving HEAD with soft reset +image::images/reset-squash-r2.png[Moving HEAD with soft reset] And then simply run `git commit` again: -image::images/reset-squash-r3.png[] +.Git repository with squashed commit +image::images/reset-squash-r3.png[Git repository with squashed commit] -Now you can see that your reachable history, the history you would push, now looks like you had one commit with `file-a.txt` v1, then a second that both modified `file-a.txt` to v3 and added `file-b.txt`. -The commit with the v2 version of the file is no longer in the history. +Now you can see that your reachable history, the history you would push, now looks like you had one commit with `file-a.txt` *v1*, then a second that both modified `file-a.txt` to *v3* and added `file-b.txt`. +The commit with the *v2* version of the file is no longer in the history. ==== Check It Out @@ -281,7 +298,8 @@ HEAD will now point to `master`. So, in both cases we're moving HEAD to point to commit A, but _how_ we do so is very different. `reset` will move the branch HEAD points to, `checkout` moves HEAD itself. -image::images/reset-checkout.png[] +.`git checkout` and `git reset` +image::images/reset-checkout.png[`git checkout` and `git reset`] ===== With Paths diff --git a/book-en/07-git-tools/sections/revision-selection.asc b/book-en/07-git-tools/sections/revision-selection.asc index a32f0adf..95e8e830 100644 --- a/book-en/07-git-tools/sections/revision-selection.asc +++ b/book-en/07-git-tools/sections/revision-selection.asc @@ -74,17 +74,15 @@ If you try to check out that object again at some point, you'll always get the d However, you should be aware of how ridiculously unlikely this scenario is. The SHA-1 digest is 20 bytes or 160 bits. -The number of randomly hashed objects needed to ensure a 50% probability of a single collision is about 2^80^ -(the formula for determining collision probability is `p = (n(n-1)/2) * (1/2^160))`. 2^80^ -is 1.2 x 10^24^ -or 1 million billion billion. +The number of randomly hashed objects needed to ensure a 50% probability of a single collision is about 2^80^ (the formula for determining collision probability is `p = (n(n-1)/2) * (1/2^160)`). +2^80^ is 1.2 x 10^24^ or 1 million billion billion. That's 1,200 times the number of grains of sand on the earth. Here's an example to give you an idea of what it would take to get a SHA-1 collision. If all 6.5 billion humans on Earth were programming, and every second, each one was producing code that was the equivalent of the entire Linux kernel history (6.5 million Git objects) and pushing it into one enormous Git repository, it would take roughly 2 years until that repository contained enough objects to have a 50% probability of a single SHA-1 object collision. Thus, an organic SHA-1 collision is less likely than every member of your programming team being attacked and killed by wolves in unrelated incidents on the same night. -If you dedicate several thousands of dollars' worth of computing power to it, it is possible to synthesize two files with the same hash, as proven on https://shattered.io/[] in February 2017. +If you dedicate several thousands of dollars' worth of computing power to it, it is possible to synthesize two files with the same hash, as proven on https://shattered.io/[^] in February 2017. Git is moving towards using SHA256 as the default hashing algorithm, which is much more resilient to collision attacks, and has code in place to help mitigate this attack (although it cannot completely eliminate it). ==== @@ -147,7 +145,7 @@ For instance, to see where your `master` branch was yesterday, you can type: $ git show master@{yesterday} ---- -That would show you where tip of your `master` branch was yesterday. +That would show you where the tip of your `master` branch was yesterday. This technique only works for data that's still in your reflog, so you can't use it to look for commits older than a few months. To see reflog information formatted like the `git log` output, you can run `git log -g`: diff --git a/book-en/07-git-tools/sections/rewriting-history.asc b/book-en/07-git-tools/sections/rewriting-history.asc index 5e8d8d61..7fbb06d7 100644 --- a/book-en/07-git-tools/sections/rewriting-history.asc +++ b/book-en/07-git-tools/sections/rewriting-history.asc @@ -166,7 +166,7 @@ $ git rebase --continue ---- This command will apply the other two commits automatically, and then you're done. -If you change pick to edit on more lines, you can repeat these steps for each commit you change to edit. +If you change `pick` to `edit` on more lines, you can repeat these steps for each commit you change to `edit`. Each time, Git will stop, let you amend the commit, and continue when you're finished. ==== Reordering Commits @@ -323,7 +323,7 @@ See <> for more information on the `reflog` c [NOTE] ==== Drew DeVault made a practical hands-on guide with exercises to learn how to use `git rebase`. -You can find it at: https://git-rebase.io/[] +You can find it at: https://git-rebase.io/[^] ==== ==== The Nuclear Option: filter-branch @@ -337,7 +337,7 @@ You'll learn a few of the common uses so you can get an idea of some of the thin ==== `git filter-branch` has many pitfalls, and is no longer the recommended way to rewrite history. Instead, consider using `git-filter-repo`, which is a Python script that does a better job for most applications where you would normally turn to `filter-branch`. -Its documentation and source code can be found at https://github.com/newren/git-filter-repo[]. +Its documentation and source code can be found at https://github.com/newren/git-filter-repo[^]. ==== [[_removing_file_every_commit]] diff --git a/book-en/07-git-tools/sections/signing.asc b/book-en/07-git-tools/sections/signing.asc index 57292adb..0e74b981 100644 --- a/book-en/07-git-tools/sections/signing.asc +++ b/book-en/07-git-tools/sections/signing.asc @@ -29,7 +29,7 @@ Once you have a private key to sign with, you can configure Git to use it for si [source,console] ---- -$ git config --global user.signingkey 0A46826A +$ git config --global user.signingkey 0A46826A! ---- Now Git will use your key by default to sign tags and commits if you want. @@ -199,5 +199,6 @@ Merge made by the 'recursive' strategy. ==== Everyone Must Sign Signing tags and commits is great, but if you decide to use this in your normal workflow, you'll have to make sure that everyone on your team understands how to do so. +This can be achieved by asking everyone working with the repository to run `git config --local commit.gpgsign true` to automatically have all of their commits in the repository signed by default. If you don't, you'll end up spending a lot of time helping people figure out how to rewrite their commits with signed versions. Make sure you understand GPG and the benefits of signing things before adopting this as part of your standard workflow. diff --git a/book-en/07-git-tools/sections/stashing-cleaning.asc b/book-en/07-git-tools/sections/stashing-cleaning.asc index f15b7c0c..7337895c 100644 --- a/book-en/07-git-tools/sections/stashing-cleaning.asc +++ b/book-en/07-git-tools/sections/stashing-cleaning.asc @@ -114,7 +114,7 @@ Changes not staged for commit: modified: lib/simplegit.rb ---- -The apply option only tries to apply the stashed work -- you continue to have it on your stack. +The `apply` option only tries to apply the stashed work -- you continue to have it on your stack. To remove it, you can run `git stash drop` with the name of the stash to remove: [source,console] @@ -249,7 +249,7 @@ Would remove tmp/ By default, the `git clean` command will only remove untracked files that are not ignored. Any file that matches a pattern in your `.gitignore` or other ignore files will not be removed. -If you want to remove those files too, such as to remove all `.o` files generated from a build so you can do a fully clean build, you can add a `-x` to the clean command. +If you want to remove those files too, such as to remove all `.o` files generated from a build so you can do a fully clean build, you can add a `-x` to the `clean` command. [source,console] ---- @@ -271,7 +271,7 @@ Would remove tmp/ If you don't know what the `git clean` command is going to do, always run it with a `-n` first to double check before changing the `-n` to a `-f` and doing it for real. The other way you can be careful about the process is to run it with the `-i` or "`interactive`" flag. -This will run the clean command in an interactive mode. +This will run the `clean` command in an interactive mode. [source,console] ---- diff --git a/book-en/07-git-tools/sections/submodules.asc b/book-en/07-git-tools/sections/submodules.asc index 0d034d64..188ff640 100644 --- a/book-en/07-git-tools/sections/submodules.asc +++ b/book-en/07-git-tools/sections/submodules.asc @@ -166,7 +166,7 @@ $ ---- The `DbConnector` directory is there, but empty. -You must run two commands: `git submodule init` to initialize your local configuration file, and `git submodule update` to fetch all the data from that project and check out the appropriate commit listed in your superproject: +You must run two commands from the main project: `git submodule init` to initialize your local configuration file, and `git submodule update` to fetch all the data from that project and check out the appropriate commit listed in your superproject: [source,console] ---- @@ -262,9 +262,9 @@ From https://github.com/chaconinc/DbConnector Submodule path 'DbConnector': checked out 'd0354fc054692d3906c85c3af05ddce39a1c0644' ---- -This command will by default assume that you want to update the checkout to the `master` branch of the submodule repository. +This command will by default assume that you want to update the checkout to the default branch of the remote submodule repository (the one pointed to by `HEAD` on the remote). You can, however, set this to something different if you want. -For example, if you want to have the DbConnector submodule track that repository's "`stable`" branch, you can set it in either your `.gitmodules` file (so everyone else also tracks it), or just in your local `.git/config` file. +For example, if you want to have the `DbConnector` submodule track that repository's "`stable`" branch, you can set it in either your `.gitmodules` file (so everyone else also tracks it), or just in your local `.git/config` file. Let's set it in the `.gitmodules` file: [source,console] @@ -415,10 +415,10 @@ Submodules changed but not updated: no changes added to commit (use "git add" and/or "git commit -a") ---- -By default, the `git pull` command recursively fetches submodules changes, as we can see in the output of the first command above. +By default, the `git pull` command recursively fetches submodules changes, as we can see in the output of the first command above. However, it does not *update* the submodules. This is shown by the output of the `git status` command, which shows the submodule is "`modified`", and has "`new commits`". -What's more, the brackets showing the new commits point left (<), indicating that these commits are recorded in MainProject but are not present in the local DbConnector checkout. +What's more, the brackets showing the new commits point left (<), indicating that these commits are recorded in MainProject but are not present in the local `DbConnector` checkout. To finalize the update, you need to run `git submodule update`: [source,console] @@ -434,9 +434,9 @@ nothing to commit, working tree clean Note that to be on the safe side, you should run `git submodule update` with the `--init` flag in case the MainProject commits you just pulled added new submodules, and with the `--recursive` flag if any submodules have nested submodules. -If you want to automate this process, you can add the `--recurse-submodules` flag to the `git pull` command (since Git 2.14). +If you want to automate this process, you can add the `--recurse-submodules` flag to the `git pull` command (since Git 2.14). This will make Git run `git submodule update` right after the pull, putting the submodules in the correct state. -Moreover, if you want to make Git always pull with `--recurse-submodules`, you can set the configuration option `submodule.recurse` to true (this works for `git pull` since Git 2.15). +Moreover, if you want to make Git always pull with `--recurse-submodules`, you can set the configuration option `submodule.recurse` to `true` (this works for `git pull` since Git 2.15). This option will make Git use the `--recurse-submodules` flag for all commands that support it (except `clone`). There is a special situation that can happen when pulling superproject updates: it could be that the upstream repository has changed the URL of the submodule in the `.gitmodules` file in one of the commits you pull. @@ -466,7 +466,7 @@ You have to do some extra steps if you want changes in a submodule to be tracked In order to set up your submodule to be easier to go in and hack on, you need to do two things. You need to go into each submodule and check out a branch to work on. -Then you need to tell Git what to do if you have made changes and then `git submodule update --remote` pulls in new work from upstream. +Then you need to tell Git what to do if you have made changes and later `git submodule update --remote` pulls in new work from upstream. The options are that you can merge them into your local work, or you can try to rebase your local work on top of the new changes. First of all, let's go into our submodule directory and check out a branch. @@ -499,8 +499,8 @@ Fast-forward Submodule path 'DbConnector': merged in '92c7337b30ef9e0893e758dac2459d07362ab5ea' ---- -If we go into the DbConnector directory, we have the new changes already merged into our local `stable` branch. -Now let's see what happens when we make our own local change to the library and someone else pushes another change upstream at the same time. +If we go into the `DbConnector` directory, we have the new changes already merged into our local `stable` branch. +Now let's see what happens when we make our own local change to the library and someone else pushes another change to the upstream at the same time. [source,console] ---- @@ -532,7 +532,7 @@ Submodule path 'DbConnector': checked out '5d60ef9bbebf5a0c1c1050f242ceeb54ad58d If this happens, don't worry, you can simply go back into the directory and check out your branch again (which will still contain your work) and merge or rebase `origin/stable` (or whatever remote branch you want) manually. -If you haven't committed your changes in your submodule and you run a submodule update that would cause issues, Git will fetch the changes but not overwrite unsaved work in your submodule directory. +If you haven't committed your changes in your submodule and you run a `submodule update` that would cause issues, Git will fetch the changes but not overwrite unsaved work in your submodule directory. [source,console] ---- @@ -608,7 +608,7 @@ to push them to a remote. As you can see, it also gives us some helpful advice on what we might want to do next. The simple option is to go into each submodule and manually push to the remotes to make sure they're externally available and then try this push again. -If you want the check behavior to happen for all pushes, you can make this behavior the default by doing `git config push.recurseSubmodules check`. +If you want the "`check`" behavior to happen for all pushes, you can make this behavior the default by doing `git config push.recurseSubmodules check`. The other option is to use the "`on-demand`" value, which will try to do this for you. @@ -632,7 +632,7 @@ To https://github.com/chaconinc/MainProject 3d6d338..9a377d1 master -> master ---- -As you can see there, Git went into the DbConnector module and pushed it before pushing the main project. +As you can see there, Git went into the `DbConnector` module and pushed it before pushing the main project. If that submodule push fails for some reason, the main project push will also fail. You can make this behavior the default by doing `git config push.recurseSubmodules on-demand`. @@ -973,7 +973,7 @@ Indeed, if you switch between branches that record the submodule at different co That is because the submodule state is by default not carried over when switching branches. This can be really confusing, so it's a good idea to always `git checkout --recurse-submodules` when your project has submodules. -For older Git versions that do not have the `--recurse-submodules` flag, after the checkout you can use `git submodule update --init --recursive` to put the submodules in the right state. +For older Git versions that do not have the `--recurse-submodules` flag, after the checkout you can use `git submodule update --init --recursive` to put the submodules in the right state. Luckily, you can tell Git (>=2.14) to always use the `--recurse-submodules` flag by setting the configuration option `submodule.recurse`: `git config submodule.recurse true`. As noted above, this will also make Git recurse into submodules for every command that has a `--recurse-submodules` option (except `git clone`). @@ -1008,7 +1008,7 @@ Checking connectivity... done. ---- Now suppose you did that in a branch. -If you try to switch back to a branch where those files are still in the actual tree rather than a submodule – you get this error: +If you try to switch back to a branch where those files are still in the actual tree rather than a submodule -- you get this error: [source,console] ---- diff --git a/book-en/07-git-tools/sections/subtree-merges.asc b/book-en/07-git-tools/sections/subtree-merges.asc index 2659ec54..24bfa3ae 100644 --- a/book-en/07-git-tools/sections/subtree-merges.asc +++ b/book-en/07-git-tools/sections/subtree-merges.asc @@ -57,7 +57,7 @@ We just switched back to your `master` branch, and we pull the `rack_branch` bra $ git read-tree --prefix=rack/ -u rack_branch ---- -When we commit, it looks like we have all the Rack files under that subdirectory – as though we copied them in from a tarball. +When we commit, it looks like we have all the Rack files under that subdirectory -- as though we copied them in from a tarball. What gets interesting is that we can fairly easily merge changes from one of the branches to the other. So, if the Rack project updates, we can pull in upstream changes by switching to that branch and pulling: @@ -80,14 +80,14 @@ Automatic merge went well; stopped before committing as requested ---- All the changes from the Rack project are merged in and ready to be committed locally. -You can also do the opposite – make changes in the `rack` subdirectory of your `master` branch and then merge them into your `rack_branch` branch later to submit them to the maintainers or push them upstream. +You can also do the opposite -- make changes in the `rack` subdirectory of your `master` branch and then merge them into your `rack_branch` branch later to submit them to the maintainers or push them upstream. This gives us a way to have a workflow somewhat similar to the submodule workflow without using submodules (which we will cover in <>). We can keep branches with other related projects in our repository and subtree merge them into our project occasionally. It is nice in some ways, for example all the code is committed to a single place. However, it has other drawbacks in that it's a bit more complex and easier to make mistakes in reintegrating changes or accidentally pushing a branch into an unrelated repository. -Another slightly weird thing is that to get a diff between what you have in your `rack` subdirectory and the code in your `rack_branch` branch – to see if you need to merge them – you can't use the normal `diff` command. +Another slightly weird thing is that to get a diff between what you have in your `rack` subdirectory and the code in your `rack_branch` branch -- to see if you need to merge them -- you can't use the normal `diff` command. Instead, you must run `git diff-tree` with the branch you want to compare to: [source,console] diff --git a/book-en/08-customizing-git/sections/attributes.asc b/book-en/08-customizing-git/sections/attributes.asc index 2c3000a2..cbcad363 100644 --- a/book-en/08-customizing-git/sections/attributes.asc +++ b/book-en/08-customizing-git/sections/attributes.asc @@ -37,7 +37,6 @@ You can also use the Git attributes functionality to effectively diff binary fil You do this by telling Git how to convert your binary data to a text format that can be compared via the normal diff. First, you'll use this technique to solve one of the most annoying problems known to humanity: version-controlling Microsoft Word documents. -Everyone knows that Word is the most horrific editor around, but oddly, everyone still uses it. If you want to version-control Word documents, you can stick them in a Git repository and commit every once in a while; but what good does that do? If you run `git diff` normally, you only see something like this: @@ -63,7 +62,7 @@ What is the "`word`" filter? You have to set it up. Here you'll configure Git to use the `docx2txt` program to convert Word documents into readable text files, which it will then diff properly. -First, you'll need to install `docx2txt`; you can download it from https://sourceforge.net/projects/docx2txt[]. +First, you'll need to install `docx2txt`; you can download it from https://sourceforge.net/projects/docx2txt[^]. Follow the instructions in the `INSTALL` file to put it somewhere your shell can find it. Next, you'll write a wrapper script to convert output to the format Git expects. Create a file that's somewhere in your path called `docx2txt`, and add these contents: @@ -298,7 +297,7 @@ Now, when you run `git archive` to create a tarball of your project, that direct ===== `export-subst` -When exporting files for deployment you can apply `git log`'s formatting and keyword-expansion processing to selected portions of files marked with the `export-subst` attribute. +When exporting files for deployment you can apply ``git log```'s formatting and keyword-expansion processing to selected portions of files marked with the ``export-subst`` attribute. For instance, if you want to include a file named `LAST_COMMIT` in your project, and have metadata about the last commit automatically injected into it when `git archive` runs, you can for example set up your `.gitattributes` and `LAST_COMMIT` files like this: diff --git a/book-en/08-customizing-git/sections/config.asc b/book-en/08-customizing-git/sections/config.asc index 2c5e7356..16739692 100644 --- a/book-en/08-customizing-git/sections/config.asc +++ b/book-en/08-customizing-git/sections/config.asc @@ -45,7 +45,12 @@ $ man git-config ---- This command lists all the available options in quite a bit of detail. -You can also find this reference material at https://git-scm.com/docs/git-config[]. +You can also find this reference material at https://git-scm.com/docs/git-config[^]. + +[NOTE] +==== +For advanced use cases you may want to look up "Conditional includes" in the documentation mentioned above. +==== ===== `core.editor` @@ -124,7 +129,7 @@ You can set it to `more` or to your favorite pager (by default, it's `less`), or $ git config --global core.pager '' ---- -If you run that, Git will page the entire output of all commands, no matter how long they are. +If you run that, Git will print the entire output of all commands, no matter how long they are. ===== `user.signingkey` @@ -248,7 +253,7 @@ We'll demonstrate setting up the Perforce Visual Merge Tool (P4Merge) to do your If you want to try this out, P4Merge works on all major platforms, so you should be able to do so. We'll use path names in the examples that work on macOS and Linux systems; for Windows, you'll have to change `/usr/local/bin` to an executable path in your environment. -To begin, https://www.perforce.com/product/components/perforce-visual-merge-and-diff-tools[download P4Merge from Perforce]. +To begin, https://www.perforce.com/products/helix-core-apps/merge-diff-tool-p4merge[download P4Merge from Perforce^]. Next, you'll set up external wrapper scripts to run your commands. We'll use the macOS path for the executable; in other systems, it will be where your `p4merge` binary is installed. Set up a merge wrapper script named `extMerge` that calls your binary with all the arguments provided: @@ -297,6 +302,7 @@ $ git config --global mergetool.extMerge.cmd \ $ git config --global mergetool.extMerge.trustExitCode false $ git config --global diff.external extDiff ---- + or you can edit your `~/.gitconfig` file to add these lines: [source,ini] @@ -402,7 +408,7 @@ $ git config --global core.autocrlf true ---- If you're on a Linux or macOS system that uses LF line endings, then you don't want Git to automatically convert them when you check out files; however, if a file with CRLF endings accidentally gets introduced, then you may want Git to fix it. -You can tell Git to convert CRLF to LF on commit but not the other way around by setting `core.autocrlf` to input: +You can tell Git to convert CRLF to LF on commit but not the other way around by setting `core.autocrlf` to `input`: [source,console] ---- diff --git a/book-en/08-customizing-git/sections/hooks.asc b/book-en/08-customizing-git/sections/hooks.asc index a0140c01..285ba4ff 100644 --- a/book-en/08-customizing-git/sections/hooks.asc +++ b/book-en/08-customizing-git/sections/hooks.asc @@ -15,7 +15,7 @@ When you initialize a new repository with `git init`, Git populates the hooks di All the examples are written as shell scripts, with some Perl thrown in, but any properly named executable scripts will work fine – you can write them in Ruby or Python or whatever language you are familiar with. If you want to use the bundled hook scripts, you'll have to rename them; their file names all end with `.sample`. -To enable a hook script, put a file in the `hooks` subdirectory of your .git directory that is named appropriately (without any extension) and is executable. +To enable a hook script, put a file in the `hooks` subdirectory of your `.git` directory that is named appropriately (without any extension) and is executable. From that point forward, it should be called. We'll cover most of the major hook filenames here. @@ -114,9 +114,9 @@ You can use this hook to do things like make sure none of the updated references ===== `update` The `update` script is very similar to the `pre-receive` script, except that it's run once for each branch the pusher is trying to update. -If the pusher is trying to push to multiple branches, `pre-receive` runs only once, whereas update runs once per branch they're pushing to. +If the pusher is trying to push to multiple branches, `pre-receive` runs only once, whereas `update` runs once per branch they're pushing to. Instead of reading from stdin, this script takes three arguments: the name of the reference (branch), the SHA-1 that reference pointed to before the push, and the SHA-1 the user is trying to push. -If the update script exits non-zero, only that reference is rejected; other references can still be updated. +If the `update` script exits non-zero, only that reference is rejected; other references can still be updated. ===== `post-receive` diff --git a/book-en/09-git-and-other-scms/sections/client-hg.asc b/book-en/09-git-and-other-scms/sections/client-hg.asc index a992e1b6..4f794568 100644 --- a/book-en/09-git-and-other-scms/sections/client-hg.asc +++ b/book-en/09-git-and-other-scms/sections/client-hg.asc @@ -8,7 +8,7 @@ Apart from Git, the most popular is Mercurial, and the two are very similar in m The good news, if you prefer Git's client-side behavior but are working with a project whose source code is controlled with Mercurial, is that there's a way to use Git as a client for a Mercurial-hosted repository. Since the way Git talks to server repositories is through remotes, it should come as no surprise that this bridge is implemented as a remote helper. -The project's name is git-remote-hg, and it can be found at https://github.com/felipec/git-remote-hg[]. +The project's name is git-remote-hg, and it can be found at https://github.com/felipec/git-remote-hg[^]. ===== git-remote-hg @@ -31,10 +31,10 @@ If you have Python installed, this is as simple as: $ pip install mercurial ---- -If you don't have Python installed, visit https://www.python.org/[] and get it first. +If you don't have Python installed, visit https://www.python.org/[^] and get it first. The last thing you'll need is the Mercurial client. -Go to https://www.mercurial-scm.org/[] and install it if you haven't already. +Go to https://www.mercurial-scm.org/[^] and install it if you haven't already. Now you're ready to rock. All you need is a Mercurial repository you can push to. @@ -65,7 +65,7 @@ You'll notice that working with a Mercurial repository uses the standard `git cl That's because git-remote-hg is working at a fairly low level, using a similar mechanism to how Git's HTTP/S protocol is implemented (remote helpers). Since Git and Mercurial are both designed for every client to have a full copy of the repository history, this command makes a full clone, including all the project's history, and does it fairly quickly. -The log command shows two commits, the latest of which is pointed to by a whole slew of refs. +The `log` command shows two commits, the latest of which is pointed to by a whole slew of refs. It turns out some of these aren't actually there. Let's take a look at what's actually in the `.git` directory: @@ -74,18 +74,18 @@ Let's take a look at what's actually in the `.git` directory: $ tree .git/refs .git/refs ├── heads -│   └── master +│ └── master ├── hg -│   └── origin -│   ├── bookmarks -│   │   └── master -│   └── branches -│   └── default +│ └── origin +│ ├── bookmarks +│ │ └── master +│ └── branches +│ └── default ├── notes -│   └── hg +│ └── hg ├── remotes -│   └── origin -│   └── HEAD +│ └── origin +│ └── HEAD └── tags 9 directories, 5 files @@ -390,7 +390,6 @@ o 0 0a04b987be5a 2005-08-26 01:20 -0700 mpm Changesets _8_, _9_, and _10_ have been created and belong to the `permanent` branch, but the old changesets are still there. This can be *very* confusing for your teammates who are using Mercurial, so try to avoid it. - ===== Mercurial Summary Git and Mercurial are similar enough that working across the boundary is fairly painless. diff --git a/book-en/09-git-and-other-scms/sections/client-p4.asc b/book-en/09-git-and-other-scms/sections/client-p4.asc index 2cd03461..16708c11 100644 --- a/book-en/09-git-and-other-scms/sections/client-p4.asc +++ b/book-en/09-git-and-other-scms/sections/client-p4.asc @@ -15,12 +15,12 @@ The second is git-p4, a client-side bridge that lets you use Git as a Perforce c ===== Git Fusion (((Perforce, Git Fusion))) -Perforce provides a product called Git Fusion (available at http://www.perforce.com/git-fusion[]), which synchronizes a Perforce server with Git repositories on the server side. +Perforce provides a product called Git Fusion (available at https://www.perforce.com/manuals/git-fusion/[^]), which synchronizes a Perforce server with Git repositories on the server side. ====== Setting Up For our examples, we'll be using the easiest installation method for Git Fusion, which is downloading a virtual machine that runs the Perforce daemon and Git Fusion. -You can get the virtual machine image from http://www.perforce.com/downloads/Perforce/20-User[], and once it's finished downloading, import it into your favorite virtualization software (we'll use VirtualBox). +You can get the virtual machine image from https://www.perforce.com/downloads[^], and once it's finished downloading, import it into your favorite virtualization software (we'll use VirtualBox). Upon first starting the machine, it asks you to customize the password for three Linux users (`root`, `perforce`, and `git`), and provide an instance name, which can be used to distinguish this installation from others on the same network. When that has all completed, you'll see this: @@ -83,15 +83,15 @@ The file structure looks like this: $ tree . ├── objects -│   ├── repos -│   │   └── [...] -│   └── trees -│   └── [...] +│ ├── repos +│ │ └── [...] +│ └── trees +│ └── [...] │ ├── p4gf_config ├── repos -│   └── Talkhouse -│   └── p4gf_config +│ └── Talkhouse +│ └── p4gf_config └── users └── p4gf_usermap @@ -323,7 +323,7 @@ Git-p4 isn't as flexible or complete a solution as Git Fusion, but it does allow [NOTE] ====== You'll need the `p4` tool somewhere in your `PATH` to work with git-p4. -As of this writing, it is freely available at http://www.perforce.com/downloads/Perforce/20-User[]. +As of this writing, it is freely available at https://www.perforce.com/downloads/helix-command-line-client-p4[^]. ====== ====== Setting Up @@ -557,7 +557,7 @@ $ git log --oneline --all --graph --decorate * 70eaf78 Initial import of //depot/www/live/ from the state at revision #head ---- -The Git and Perforce history diverge after 775a46f. +The Git and Perforce history diverge after `775a46f`. The Git side has two commits, then a merge commit with the Perforce head, then another commit. We're going to try to submit these on top of a single changeset on the Perforce side. Let's see what would happen if we tried to submit now: diff --git a/book-en/09-git-and-other-scms/sections/client-svn.asc b/book-en/09-git-and-other-scms/sections/client-svn.asc index 502e4998..de330a1b 100644 --- a/book-en/09-git-and-other-scms/sections/client-svn.asc +++ b/book-en/09-git-and-other-scms/sections/client-svn.asc @@ -158,7 +158,7 @@ c3dcbe8488c6240392e8a5d7553bbffcb0f94ef0 refs/remotes/origin/master 6dcb09b5b57875f334f61aebed695e2e4193db5e refs/tags/v1.0.0 ---- -Git fetches the tags directly into `refs/tags`, rather than treating them remote branches. +Git fetches the tags directly into `refs/tags`, rather than treating them as remote branches. ===== Committing Back to Subversion diff --git a/book-en/09-git-and-other-scms/sections/import-custom.asc b/book-en/09-git-and-other-scms/sections/import-custom.asc index e3e58ff5..726f3d8f 100644 --- a/book-en/09-git-and-other-scms/sections/import-custom.asc +++ b/book-en/09-git-and-other-scms/sections/import-custom.asc @@ -155,7 +155,7 @@ Dir.glob("**/*").each do |file| end ---- -Note: Because many systems think of their revisions as changes from one commit to another, fast-import can also take commands with each commit to specify which files have been added, removed, or modified and what the new contents are. +Note: Because many systems think of their revisions as changes from one commit to another, fast-import can also take commands with each commit to specify which files have been added, removed, or modified and what the new contents are. You could calculate the differences between snapshots and provide only this data, but doing so is more complex – you may as well give Git all the data and let it figure it out. If this is better suited to your data, check the `fast-import` man page for details about how to provide your data in this manner. @@ -204,7 +204,6 @@ $stdout.binmode That's it. Here's the script in its entirety: - [source,ruby] ---- #!/usr/bin/env ruby diff --git a/book-en/09-git-and-other-scms/sections/import-hg.asc b/book-en/09-git-and-other-scms/sections/import-hg.asc index 132fa8c0..b6d1e194 100644 --- a/book-en/09-git-and-other-scms/sections/import-hg.asc +++ b/book-en/09-git-and-other-scms/sections/import-hg.asc @@ -39,7 +39,7 @@ Joe Smith In this example, the same person (Bob) has created changesets under four different names, one of which actually looks correct, and one of which would be completely invalid for a Git commit. Hg-fast-export lets us fix this by turning each line into a rule: `""=""`, mapping an `` to an ``. -Inside the `` and `` strings, all escape sequences understood by the python `string_escape` encoding are supported. +Inside the `` and `` strings, all escape sequences understood by the Python `string_escape` encoding are supported. If the author mapping file does not contain a matching ``, that author will be sent on to Git unmodified. If all the usernames look fine, we won't need this file at all. In this example, we want our file to look like this: diff --git a/book-en/09-git-and-other-scms/sections/import-svn.asc b/book-en/09-git-and-other-scms/sections/import-svn.asc index df306b3f..5ed4e8f5 100644 --- a/book-en/09-git-and-other-scms/sections/import-svn.asc +++ b/book-en/09-git-and-other-scms/sections/import-svn.asc @@ -33,7 +33,7 @@ Then, redirect that output into your `users.txt` file so you can add the equival [NOTE] ==== If you're trying this on a Windows machine, this is the point where you'll run into trouble. -Microsoft have provided some good advice and samples at https://docs.microsoft.com/en-us/azure/devops/repos/git/perform-migration-from-svn-to-git[]. +Microsoft have provided some good advice and samples at https://learn.microsoft.com/en-us/azure/devops/repos/git/perform-migration-from-svn-to-git[^]. ==== You can provide this file to `git svn` to help it map the author data more accurately. @@ -106,7 +106,7 @@ $ for b in $(git for-each-ref --format='%(refname:short)' refs/remotes); do git It may happen that you'll see some extra branches which are suffixed by `@xxx` (where xxx is a number), while in Subversion you only see one branch. This is actually a Subversion feature called "`peg-revisions`", which is something that Git simply has no syntactical counterpart for. -Hence, `git svn` simply adds the svn version number to the branch name just in the same way as you would have written it in svn to address the peg-revision of that branch. +Hence, `git svn` simply adds the SVN version number to the branch name just in the same way as you would have written it in SVN to address the peg-revision of that branch. If you do not care anymore about the peg-revisions, simply remove them: [source,console] diff --git a/book-en/10-git-internals/sections/environment.asc b/book-en/10-git-internals/sections/environment.asc index 1eab01fe..9b01781c 100644 --- a/book-en/10-git-internals/sections/environment.asc +++ b/book-en/10-git-internals/sections/environment.asc @@ -4,22 +4,21 @@ Git always runs inside a `bash` shell, and uses a number of shell environment va Occasionally, it comes in handy to know what these are, and how they can be used to make Git behave the way you want it to. This isn't an exhaustive list of all the environment variables Git pays attention to, but we'll cover the most useful. - ==== Global Behavior Some of Git's general behavior as a computer program depends on environment variables. *`GIT_EXEC_PATH`* determines where Git looks for its sub-programs (like `git-commit`, `git-diff`, and others). - You can check the current setting by running `git --exec-path`. +You can check the current setting by running `git --exec-path`. *`HOME`* isn't usually considered customizable (too many other things depend on it), but it's where Git looks for the global configuration file. - If you want a truly portable Git installation, complete with global configuration, you can override `HOME` in the portable Git's shell profile. +If you want a truly portable Git installation, complete with global configuration, you can override `HOME` in the portable Git's shell profile. *`PREFIX`* is similar, but for the system-wide configuration. - Git looks for this file at `$PREFIX/etc/gitconfig`. +Git looks for this file at `$PREFIX/etc/gitconfig`. *`GIT_CONFIG_NOSYSTEM`*, if set, disables the use of the system-wide configuration file. - This is useful if your system config is interfering with your commands, but you don't have access to change or remove it. +This is useful if your system config is interfering with your commands, but you don't have access to change or remove it. *`GIT_PAGER`* controls the program used to display multi-page output on the command line. If this is unset, `PAGER` will be used as a fallback. @@ -27,7 +26,6 @@ If this is unset, `PAGER` will be used as a fallback. *`GIT_EDITOR`* is the editor Git will launch when the user needs to edit some text (a commit message, for example). If unset, `EDITOR` will be used. - ==== Repository Locations Git uses several environment variables to determine how it interfaces with the current repository. @@ -48,7 +46,6 @@ If `--git-dir` or `GIT_DIR` is specified but none of `--work-tree`, `GIT_WORK_TR *`GIT_ALTERNATE_OBJECT_DIRECTORIES`* is a colon-separated list (formatted like `/dir/one:/dir/two:…`) which tells Git where to check for objects if they aren't in `GIT_OBJECT_DIRECTORY`. If you happen to have a lot of projects with large files that have the exact same contents, this can be used to avoid storing too many copies of them. - ==== Pathspecs A "`pathspec`" refers to how you specify paths to things in Git, including the use of wildcards. @@ -62,7 +59,6 @@ You can override this in individual cases by starting the pathspec with `:(glob) *`GIT_ICASE_PATHSPECS`* sets all pathspecs to work in a case-insensitive manner. - ==== Committing The final creation of a Git commit object is usually done by `git-commit-tree`, which uses these environment variables as its primary source of information, falling back to configuration values only if these aren't present. @@ -82,7 +78,6 @@ The final creation of a Git commit object is usually done by `git-commit-tree`, *`EMAIL`* is the fallback email address in case the `user.email` configuration value isn't set. If _this_ isn't set, Git falls back to the system user and host names. - ==== Networking Git uses the `curl` library to do network operations over HTTP, so *`GIT_CURL_VERBOSE`* tells Git to emit all the messages generated by that library. @@ -91,14 +86,12 @@ This is similar to doing `curl -v` on the command line. *`GIT_SSL_NO_VERIFY`* tells Git not to verify SSL certificates. This can sometimes be necessary if you're using a self-signed certificate to serve Git repositories over HTTPS, or you're in the middle of setting up a Git server but haven't installed a full certificate yet. - If the data rate of an HTTP operation is lower than *`GIT_HTTP_LOW_SPEED_LIMIT`* bytes per second for longer than *`GIT_HTTP_LOW_SPEED_TIME`* seconds, Git will abort that operation. These values override the `http.lowSpeedLimit` and `http.lowSpeedTime` configuration values. *`GIT_HTTP_USER_AGENT`* sets the user-agent string used by Git when communicating over HTTP. The default is a value like `git/2.0.0`. - ==== Diffing and Merging *`GIT_DIFF_OPTS`* is a bit of a misnomer. @@ -216,8 +209,11 @@ nothing to commit, working directory clean *`GIT_SSH`*, if specified, is a program that is invoked instead of `ssh` when Git tries to connect to an SSH host. It is invoked like `$GIT_SSH [username@]host [-p ] `. -Note that this isn't the easiest way to customize how `ssh` is invoked; it won't support extra command-line parameters, so you'd have to write a wrapper script and set `GIT_SSH` to point to it. -It's probably easier just to use the `~/.ssh/config` file for that. +Note that this isn't the easiest way to customize how `ssh` is invoked; it won't support extra command-line parameters. +To support extra command-line parameters, you can use *`GIT_SSH_COMMAND`*, write a wrapper script and set `GIT_SSH` to point to it or use the `~/.ssh/config` file. + +*`GIT_SSH_COMMAND`* sets the SSH command used when Git tries to connect to an SSH host. +The command is interpreted by the shell, and extra command-line arguments can be used with `ssh`, such as `GIT_SSH_COMMAND="ssh -i ~/.ssh/my_key" git clone git@example.com:my/repo`. *`GIT_ASKPASS`* is an override for the `core.askpass` configuration value. This is the program invoked whenever Git needs to ask the user for credentials, which can expect a text prompt as a command-line argument, and should return the answer on `stdout` (see <> for more on this subsystem). diff --git a/book-en/10-git-internals/sections/maintenance.asc b/book-en/10-git-internals/sections/maintenance.asc index de4a30d8..d4e53081 100644 --- a/book-en/10-git-internals/sections/maintenance.asc +++ b/book-en/10-git-internals/sections/maintenance.asc @@ -11,7 +11,7 @@ Most of the time, this command does nothing. However, if there are too many loose objects (objects not in a packfile) or too many packfiles, Git launches a full-fledged `git gc` command. The "`gc`" stands for garbage collect, and the command does a number of things: it gathers up all the loose objects and places them in packfiles, it consolidates packfiles into one big packfile, and it removes objects that aren't reachable from any commit and are a few months old. -You can run auto gc manually as follows: +You can run `auto gc` manually as follows: [source,console] ---- @@ -19,7 +19,7 @@ $ git gc --auto ---- Again, this generally does nothing. -You must have around 7,000 loose objects or more than 50 packfiles for Git to fire up a real gc command. +You must have around 7,000 loose objects or more than 50 packfiles for Git to fire up a real `gc` command. You can modify these limits with the `gc.auto` and `gc.autopacklimit` config settings, respectively. The other thing `gc` will do is pack up your references into a single file. @@ -68,7 +68,7 @@ First, let's review where your repository is at this point: [source,console] ---- $ git log --pretty=oneline -ab1afef80fac8e34258ff41fc1b867c702daa24b Modify repo a bit +ab1afef80fac8e34258ff41fc1b867c702daa24b Modify repo.rb a bit 484a59275031909e19aadb7c92262719cfcdf19a Create repo.rb 1a410efbd13591db07496601ebc7a059dd55cfe9 Third commit cac0cab538b970a37ea1e769cbbde608743bc96d Second commit diff --git a/book-en/10-git-internals/sections/objects.asc b/book-en/10-git-internals/sections/objects.asc index c04a695d..3182d9f9 100644 --- a/book-en/10-git-internals/sections/objects.asc +++ b/book-en/10-git-internals/sections/objects.asc @@ -150,7 +150,7 @@ $ git cat-file -p 99f1a6d12cb4b6f19c8655fca46c3ecf317074e0 Depending on what shell you use, you may encounter errors when using the `master^{tree}` syntax. In CMD on Windows, the `^` character is used for escaping, so you have to double it to avoid this: `git cat-file -p master^^{tree}`. -When using PowerShell, parameters using {} characters have to be quoted to avoid the parameter being parsed incorrectly: `git cat-file -p 'master^{tree}'`. +When using PowerShell, parameters using `{}` characters have to be quoted to avoid the parameter being parsed incorrectly: `git cat-file -p 'master^{tree}'`. If you're using ZSH, the `^` character is used for globbing, so you have to enclose the whole expression in quotes: `git cat-file -p "master^{tree}"`. ==== @@ -202,7 +202,7 @@ You'll now create a new tree with the second version of `test.txt` and a new fil [source,console] ---- $ echo 'new file' > new.txt -$ git update-index --add --cacheinfo 100644 \ +$ git update-index --cacheinfo 100644 \ 1f7a7a472abf3dd9643fd615f6da379c4acb3e3a test.txt $ git update-index --add new.txt ---- @@ -257,7 +257,6 @@ $ echo 'First commit' | git commit-tree d8329f fdf4fc3344e67ab068f836878b6c4951e3b15f3d ---- - [NOTE] ==== You will get a different hash value because of different creation time and author data. @@ -366,7 +365,7 @@ $ irb ---- Git first constructs a header which starts by identifying the type of object -- in this case, a blob. -To that first part of the header, Git adds a space followed by the size in bytes of the content, and adding a final null byte: +To that first part of the header, Git adds a space followed by the size in bytes of the content, and adding a final null byte: [source,console] ---- diff --git a/book-en/10-git-internals/sections/refs.asc b/book-en/10-git-internals/sections/refs.asc index 8ad1524d..c8319084 100644 --- a/book-en/10-git-internals/sections/refs.asc +++ b/book-en/10-git-internals/sections/refs.asc @@ -73,8 +73,8 @@ The answer is the HEAD file. Usually the HEAD file is a symbolic reference to the branch you're currently on. By symbolic reference, we mean that unlike a normal reference, it contains a pointer to another reference. -However in some rare cases the HEAD file may contain the SHA-1 value of a git object. -This happens when you checkout a tag, commit, or remote branch, which puts your repository in https://git-scm.com/docs/git-checkout#_detached_head["detached HEAD"] state. +However in some rare cases the HEAD file may contain the SHA-1 value of a Git object. +This happens when you checkout a tag, commit, or remote branch, which puts your repository in https://git-scm.com/docs/git-checkout#_detached_head["detached HEAD"^] state. If you look at the file, you'll normally see something like this: diff --git a/book-en/10-git-internals/sections/transfer-protocols.asc b/book-en/10-git-internals/sections/transfer-protocols.asc index 2a127ab6..44e6a39a 100644 --- a/book-en/10-git-internals/sections/transfer-protocols.asc +++ b/book-en/10-git-internals/sections/transfer-protocols.asc @@ -174,7 +174,7 @@ For instance, if you're updating the `master` branch and adding an `experiment` Git sends a line for each reference you're updating with the line's length, the old SHA-1, the new SHA-1, and the reference that is being updated. The first line also has the client's capabilities. -The SHA-1 value of all '0's means that nothing was there before – because you're adding the experiment reference. +The SHA-1 value of all '0's means that nothing was there before – because you're adding the `experiment` reference. If you were deleting a reference, you would see the opposite: all '0's on the right side. Next, the client sends a packfile of all the objects the server doesn't have yet. diff --git a/book-en/A-git-in-other-environments/sections/guis.asc b/book-en/A-git-in-other-environments/sections/guis.asc index c4d06d1e..3c2b6290 100644 --- a/book-en/A-git-in-other-environments/sections/guis.asc +++ b/book-en/A-git-in-other-environments/sections/guis.asc @@ -28,7 +28,7 @@ $ gitk [git log options] ---- Gitk accepts many command-line options, most of which are passed through to the underlying `git log` action. -Probably one of the most useful is the `--all` flag, which tells gitk to show commits reachable from _any_ ref, not just HEAD. +Probably one of the most useful is the `--all` flag, which tells `gitk` to show commits reachable from _any_ ref, not just HEAD. Gitk's interface looks like this: .The `gitk` history viewer @@ -96,7 +96,7 @@ While they're designed to highlight GitHub's service and recommended workflow, t ===== Installation -GitHub for Windows can be downloaded from https://windows.github.com[], and GitHub for macOS from https://mac.github.com[]. +GitHub for Windows and macOS can be downloaded from https://desktop.github.com/[^]. When the applications are first run, they walk you through all the first-time Git setup, such as configuring your name and email address, and both set up sane defaults for many common configuration options, such as credential caches and CRLF behavior. Both are "`evergreen`" – updates are downloaded and installed in the background while the applications are open. @@ -144,9 +144,8 @@ These tools are very well-suited for the workflow they're designed for. Developers and non-developers alike can be collaborating on a project within minutes, and many of the best practices for this kind of workflow are baked into the tools. However, if your workflow is different, or you want more control over how and when network operations are done, we recommend you use another client or the command line. - ==== Other GUIs There are a number of other graphical Git clients, and they run the gamut from specialized, single-purpose tools all the way to apps that try to expose everything Git can do. -The official Git website has a curated list of the most popular clients at https://git-scm.com/downloads/guis[]. -A more comprehensive list is available on the Git wiki site, at https://git.wiki.kernel.org/index.php/Interfaces,_frontends,_and_tools#Graphical_Interfaces[]. +The official Git website has a curated list of the most popular clients at https://git-scm.com/downloads/guis[^]. +A more comprehensive list is available on the Git wiki site, at https://archive.kernel.org/oldwiki/git.wiki.kernel.org/index.php/Interfaces,_frontends,_and_tools.html#Graphical_Interfaces[^]. diff --git a/book-en/A-git-in-other-environments/sections/jetbrainsides.asc b/book-en/A-git-in-other-environments/sections/jetbrainsides.asc index d6040ca7..1def4a3e 100644 --- a/book-en/A-git-in-other-environments/sections/jetbrainsides.asc +++ b/book-en/A-git-in-other-environments/sections/jetbrainsides.asc @@ -1,10 +1,11 @@ === Git in IntelliJ / PyCharm / WebStorm / PhpStorm / RubyMine +(((JetBrains))) JetBrains IDEs (such as IntelliJ IDEA, PyCharm, WebStorm, PhpStorm, RubyMine, and others) ship with a Git Integration plugin. It provides a dedicated view in the IDE to work with Git and GitHub Pull Requests. .Version Control ToolWindow in JetBrains IDEs image::images/jb.png[Version Control ToolWindow in JetBrains IDEs] -The integration relies on the command-line git client, and requires one to be installed. -The official documentation is available at https://www.jetbrains.com/help/idea/using-git-integration.html[]. +The integration relies on the command-line Git client, and requires one to be installed. +The official documentation is available at https://www.jetbrains.com/help/idea/using-git-integration.html[^]. diff --git a/book-en/A-git-in-other-environments/sections/powershell.asc b/book-en/A-git-in-other-environments/sections/powershell.asc index 66f7c3cc..e51fe0d5 100644 --- a/book-en/A-git-in-other-environments/sections/powershell.asc +++ b/book-en/A-git-in-other-environments/sections/powershell.asc @@ -5,7 +5,7 @@ (((posh-git))) The legacy command-line terminal on Windows (`cmd.exe`) isn't really capable of a customized Git experience, but if you're using PowerShell, you're in luck. This also works if you're running PowerShell Core on Linux or macOS. -A package called posh-git (https://github.com/dahlbyk/posh-git[]) provides powerful tab-completion facilities, as well as an enhanced prompt to help you stay on top of your repository status. +A package called posh-git (https://github.com/dahlbyk/posh-git[^]) provides powerful tab-completion facilities, as well as an enhanced prompt to help you stay on top of your repository status. It looks like this: .PowerShell with Posh-git @@ -21,9 +21,9 @@ With `RemoteSigned`, only scripts having the `ZoneIdentifier` set to `Internet` If you're an administrator and want to set it for all users on that machine, use `-Scope LocalMachine`. If you're a normal user, without administrative rights, you can use `-Scope CurrentUser` to set it only for you. -More about PowerShell Scopes: https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_scopes[]. +More about PowerShell Scopes: https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_scopes[^]. -More about PowerShell ExecutionPolicy: https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.security/set-executionpolicy[]. +More about PowerShell ExecutionPolicy: https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.security/set-executionpolicy[^]. To set the value of `ExecutionPolicy` to `RemoteSigned` for all users use the next command: @@ -36,7 +36,7 @@ To set the value of `ExecutionPolicy` to `RemoteSigned` for all users use the ne If you have at least PowerShell 5 or PowerShell 4 with PackageManagement installed, you can use the package manager to install posh-git for you. -More information about PowerShell Gallery: https://docs.microsoft.com/en-us/powershell/scripting/gallery/overview[]. +More information about PowerShell Gallery: https://learn.microsoft.com/en-us/powershell/scripting/gallery/overview[^]. [source,powershell] ---- @@ -57,11 +57,11 @@ This happens, because the modules that ship with Windows PowerShell are signed w ===== Update PowerShell Prompt -To include git information in your prompt, the posh-git module needs to be imported. +To include Git information in your prompt, the posh-git module needs to be imported. To have posh-git imported every time PowerShell starts, execute the `Add-PoshGitToProfile` command which will add the import statement into your `$profile` script. This script is executed everytime you open a new PowerShell console. Keep in mind, that there are multiple `$profile` scripts. -E. g. one for the console and a separate one for the ISE. +E.g. one for the console and a separate one for the ISE. [source,powershell] ---- @@ -71,7 +71,7 @@ E. g. one for the console and a separate one for the ISE. ===== From Source -Just download a posh-git release from https://github.com/dahlbyk/posh-git/releases[], and uncompress it. +Just download a posh-git release from https://github.com/dahlbyk/posh-git/releases[^], and uncompress it. Then import the module using the full path to the `posh-git.psd1` file: [source,powershell] @@ -82,5 +82,5 @@ Then import the module using the full path to the `posh-git.psd1` file: This will add the proper line to your `profile.ps1` file, and posh-git will be active the next time you open PowerShell. -For a description of the Git status summary information displayed in the prompt see: https://github.com/dahlbyk/posh-git/blob/master/README.md#git-status-summary-information[] -For more details on how to customize your posh-git prompt see: https://github.com/dahlbyk/posh-git/blob/master/README.md#customization-variables[]. +For a description of the Git status summary information displayed in the prompt see: https://github.com/dahlbyk/posh-git/blob/master/README.md#git-status-summary-information[^] +For more details on how to customize your posh-git prompt see: https://github.com/dahlbyk/posh-git/blob/master/README.md#customization-variables[^]. diff --git a/book-en/A-git-in-other-environments/sections/sublimetext.asc b/book-en/A-git-in-other-environments/sections/sublimetext.asc index eb774347..d62eff43 100644 --- a/book-en/A-git-in-other-environments/sections/sublimetext.asc +++ b/book-en/A-git-in-other-environments/sections/sublimetext.asc @@ -1,14 +1,16 @@ === Git in Sublime Text -From version 3.2 onwards, Sublime Text has git integration in the editor. +(((Sublime Text))) +From version 3.2 onwards, Sublime Text has Git integration in the editor. The features are: -* The sidebar will show the git status of files and folders with a badge/icon. -* Files and folders that are in your .gitignore file will be faded out in the sidebar. -* In the status bar, you can see the current git branch and how many modifications you have made. +* The sidebar will show the `git status` of files and folders with a badge/icon. +* Files and folders that are in your `.gitignore` file will be faded out in the sidebar. +* In the status bar, you can see the current Git branch and how many modifications you have made. * All changes to a file are now visible via markers in the gutter. -* You can use part of the Sublime Merge git client functionality from within Sublime Text. - This requires that Sublime Merge is installed. See: https://www.sublimemerge.com/[]. +* You can use part of the Sublime Merge Git client functionality from within Sublime Text. + This requires that Sublime Merge is installed. + See: https://www.sublimemerge.com/[^]. -The official documentation for Sublime Text can be found here: https://www.sublimetext.com/docs/3/git_integration.html[]. +The official documentation for Sublime Text can be found here: https://www.sublimetext.com/docs/git_integration.html[^]. diff --git a/book-en/A-git-in-other-environments/sections/visualstudio.asc b/book-en/A-git-in-other-environments/sections/visualstudio.asc index bfd30785..f46d575d 100644 --- a/book-en/A-git-in-other-environments/sections/visualstudio.asc +++ b/book-en/A-git-in-other-environments/sections/visualstudio.asc @@ -15,5 +15,4 @@ The tooling supports the following Git functionality: * View diffs. * ... and more! -Read the https://docs.microsoft.com/visualstudio/version-control[official documentation^] to learn more. - +Read the https://learn.microsoft.com/en-us/visualstudio/version-control/[official documentation^] to learn more. diff --git a/book-en/A-git-in-other-environments/sections/visualstudiocode.asc b/book-en/A-git-in-other-environments/sections/visualstudiocode.asc index 1a53cb17..7a646c3b 100644 --- a/book-en/A-git-in-other-environments/sections/visualstudiocode.asc +++ b/book-en/A-git-in-other-environments/sections/visualstudiocode.asc @@ -1,7 +1,8 @@ === Git in Visual Studio Code -Visual Studio Code has git support built in. -You will need to have git version 2.0.0 (or newer) installed. +(((Visual Studio Code))) +Visual Studio Code has Git support built in. +You will need to have Git version 2.0.0 (or newer) installed. The main features are: @@ -16,6 +17,6 @@ The main features are: ** Resolve merge conflicts. ** View diffs. * With an extension, you can also handle GitHub Pull Requests: - https://marketplace.visualstudio.com/items?itemName=GitHub.vscode-pull-request-github[]. + https://marketplace.visualstudio.com/items?itemName=GitHub.vscode-pull-request-github[^]. -The official documentation can be found here: https://code.visualstudio.com/Docs/editor/versioncontrol[]. +The official documentation can be found here: https://code.visualstudio.com/docs/sourcecontrol/overview[^]. diff --git a/book-en/A-git-in-other-environments/sections/zsh.asc b/book-en/A-git-in-other-environments/sections/zsh.asc index 5395d262..c0578a95 100644 --- a/book-en/A-git-in-other-environments/sections/zsh.asc +++ b/book-en/A-git-in-other-environments/sections/zsh.asc @@ -34,20 +34,20 @@ zstyle ':vcs_info:git:*' formats '%b' ---- This results in a display of the current branch on the right-hand side of the terminal window, whenever your shell is inside a Git repository. -The left side is supported as well, of course; just uncomment the assignment to PROMPT. +The left side is supported as well, of course; just uncomment the assignment to `PROMPT`. It looks a bit like this: .Customized `zsh` prompt image::images/zsh-prompt.png[Customized `zsh` prompt] -For more information on `vcs_info`, check out its documentation in the `zshcontrib(1)` manual page, or online at http://zsh.sourceforge.net/Doc/Release/User-Contributions.html#Version-Control-Information[]. +For more information on `vcs_info`, check out its documentation in the `zshcontrib(1)` manual page, or online at https://zsh.sourceforge.io/Doc/Release/User-Contributions.html#Version-Control-Information[^]. -Instead of `vcs_info`, you might prefer the prompt customization script that ships with Git, called `git-prompt.sh`; see https://github.com/git/git/blob/master/contrib/completion/git-prompt.sh[] for details. +Instead of `vcs_info`, you might prefer the prompt customization script that ships with Git, called `git-prompt.sh`; see https://github.com/git/git/blob/master/contrib/completion/git-prompt.sh[^] for details. `git-prompt.sh` is compatible with both Bash and Zsh. Zsh is powerful enough that there are entire frameworks dedicated to making it better. -One of them is called "oh-my-zsh", and it can be found at https://github.com/robbyrussell/oh-my-zsh[]. -oh-my-zsh's plugin system comes with powerful git tab-completion, and it has a variety of prompt "themes", many of which display version-control data. +One of them is called "oh-my-zsh", and it can be found at https://github.com/ohmyzsh/ohmyzsh[^]. +oh-my-zsh's plugin system comes with powerful Git tab-completion, and it has a variety of prompt "themes", many of which display version-control data. <> is just one example of what can be done with this system. [[oh_my_zsh_git]] diff --git a/book-en/B-embedding-git/sections/dulwich.asc b/book-en/B-embedding-git/sections/dulwich.asc index 9a238699..62cab950 100644 --- a/book-en/B-embedding-git/sections/dulwich.asc +++ b/book-en/B-embedding-git/sections/dulwich.asc @@ -2,11 +2,11 @@ (((Dulwich)))(((Python))) There is also a pure-Python Git implementation - Dulwich. -The project is hosted under https://www.dulwich.io/ -It aims to provide an interface to git repositories (both local and remote) that doesn't call out to git directly but instead uses pure Python. +The project is hosted under https://www.dulwich.io/[^]. +It aims to provide an interface to Git repositories (both local and remote) that doesn't call out to Git directly but instead uses pure Python. It has an optional C extensions though, that significantly improve the performance. -Dulwich follows git design and separate two basic levels of API: plumbing and porcelain. +Dulwich follows Git design and separate two basic levels of API: plumbing and porcelain. Here is an example of using the lower level API to access the commit message of the last commit: @@ -37,7 +37,6 @@ porcelain.log('.', max_entries=1) #Date: Sat Apr 29 2017 23:57:34 +0000 ---- - ==== Further Reading -The API documentation, tutorial, and many examples of how to do specific tasks with Dulwich are available on the official website https://www.dulwich.io[]. +The API documentation, tutorial, and many examples of how to do specific tasks with Dulwich are available on the official website https://www.dulwich.io[^]. diff --git a/book-en/B-embedding-git/sections/go-git.asc b/book-en/B-embedding-git/sections/go-git.asc index 3335802b..a477cf1b 100644 --- a/book-en/B-embedding-git/sections/go-git.asc +++ b/book-en/B-embedding-git/sections/go-git.asc @@ -5,7 +5,7 @@ In case you want to integrate Git into a service written in Golang, there also i This implementation does not have any native dependencies and thus is not prone to manual memory management errors. It is also transparent for the standard Golang performance analysis tooling like CPU, Memory profilers, race detector, etc. -go-git is focused on extensibility, compatibility and supports most of the plumbing APIs, which is documented at https://github.com/go-git/go-git/blob/master/COMPATIBILITY.md[]. +go-git is focused on extensibility, compatibility and supports most of the plumbing APIs, which is documented at https://github.com/go-git/go-git/blob/master/COMPATIBILITY.md[^]. Here is a basic example of using Go APIs: @@ -51,12 +51,12 @@ r, err := git.Clone(memory.NewStorage(), nil, &git.CloneOptions{ ---- Pluggable storage provides many interesting options. -For instance, https://github.com/go-git/go-git/tree/master/_examples/storage[] allows you to store references, objects, and configuration in an Aerospike database. +For instance, https://github.com/go-git/go-git/tree/master/_examples/storage[^] allows you to store references, objects, and configuration in an Aerospike database. Another feature is a flexible filesystem abstraction. -Using https://pkg.go.dev/github.com/go-git/go-billy/v5?tab=doc#Filesystem[] it is easy to store all the files in different way i.e by packing all of them to a single archive on disk or by keeping them all in-memory. +Using https://pkg.go.dev/github.com/go-git/go-billy/v5?tab=doc#Filesystem[^] it is easy to store all the files in different way i.e by packing all of them to a single archive on disk or by keeping them all in-memory. -Another advanced use-case includes a fine-tunable HTTP client, such as the one found at https://github.com/go-git/go-git/blob/master/_examples/custom_http/main.go[]. +Another advanced use-case includes a fine-tunable HTTP client, such as the one found at https://github.com/go-git/go-git/blob/master/_examples/custom_http/main.go[^]. [source, go] ---- @@ -80,4 +80,4 @@ r, err := git.Clone(memory.NewStorage(), nil, &git.CloneOptions{URL: url}) ==== Further Reading A full treatment of go-git's capabilities is outside the scope of this book. -If you want more information on go-git, there's API documentation at https://pkg.go.dev/github.com/go-git/go-git/v5[], and a set of usage examples at https://github.com/go-git/go-git/tree/master/_examples[]. +If you want more information on go-git, there's API documentation at https://pkg.go.dev/github.com/go-git/go-git/v5[^], and a set of usage examples at https://github.com/go-git/go-git/tree/master/_examples[^]. diff --git a/book-en/B-embedding-git/sections/jgit.asc b/book-en/B-embedding-git/sections/jgit.asc index 9e416173..74ae05a3 100644 --- a/book-en/B-embedding-git/sections/jgit.asc +++ b/book-en/B-embedding-git/sections/jgit.asc @@ -3,12 +3,12 @@ (((jgit)))(((Java))) If you want to use Git from within a Java program, there is a fully featured Git library called JGit. JGit is a relatively full-featured implementation of Git written natively in Java, and is widely used in the Java community. -The JGit project is under the Eclipse umbrella, and its home can be found at https://www.eclipse.org/jgit/[]. +The JGit project is under the Eclipse umbrella, and its home can be found at https://projects.eclipse.org/projects/technology.jgit[^]. ==== Getting Set Up There are a number of ways to connect your project with JGit and start writing code against it. -Probably the easiest is to use Maven – the integration is accomplished by adding the following snippet to the `` tag in your pom.xml file: +Probably the easiest is to use Maven – the integration is accomplished by adding the following snippet to the `` tag in your `pom.xml` file: [source,xml] ---- @@ -19,10 +19,10 @@ Probably the easiest is to use Maven – the integration is accomplished by addi ---- -The `version` will most likely have advanced by the time you read this; check https://mvnrepository.com/artifact/org.eclipse.jgit/org.eclipse.jgit[] for updated repository information. +The `version` will most likely have advanced by the time you read this; check https://mvnrepository.com/artifact/org.eclipse.jgit/org.eclipse.jgit[^] for updated repository information. Once this step is done, Maven will automatically acquire and use the JGit libraries that you'll need. -If you would rather manage the binary dependencies yourself, pre-built JGit binaries are available from https://www.eclipse.org/jgit/download[]. +If you would rather manage the binary dependencies yourself, pre-built JGit binaries are available from https://projects.eclipse.org/projects/technology.jgit/downloads[^]. You can build them into your project by running a command like this: [source,console] @@ -155,6 +155,6 @@ Many other commands are available through the Git class, including but not limit This is only a small sampling of JGit's full capabilities. If you're interested and want to learn more, here's where to look for information and inspiration: -* The official JGit API documentation can be found at https://www.eclipse.org/jgit/documentation[]. +* The official JGit API documentation can be found at https://help.eclipse.org/latest/topic/org.eclipse.egit.doc/help/JGit/User_Guide/User-Guide.html[^]. These are standard Javadoc, so your favorite JVM IDE will be able to install them locally, as well. -* The JGit Cookbook at https://github.com/centic9/jgit-cookbook[] has many examples of how to do specific tasks with JGit. +* The JGit Cookbook at https://github.com/centic9/jgit-cookbook[^] has many examples of how to do specific tasks with JGit. diff --git a/book-en/B-embedding-git/sections/libgit2.asc b/book-en/B-embedding-git/sections/libgit2.asc index 9edca885..2e006fdc 100644 --- a/book-en/B-embedding-git/sections/libgit2.asc +++ b/book-en/B-embedding-git/sections/libgit2.asc @@ -3,7 +3,7 @@ (((libgit2)))((("C"))) Another option at your disposal is to use Libgit2. Libgit2 is a dependency-free implementation of Git, with a focus on having a nice API for use within other programs. -You can find it at https://libgit2.org[]. +You can find it at https://libgit2.org[^]. First, let's take a look at what the C API looks like. Here's a whirlwind tour: @@ -54,7 +54,7 @@ From this sample, a couple of patterns have started to emerge: (((Ruby))) That last one means it isn't very probable that you'll be writing C when using Libgit2. Fortunately, there are a number of language-specific bindings available that make it fairly easy to work with Git repositories from your specific language and environment. -Let's take a look at the above example written using the Ruby bindings for Libgit2, which are named Rugged, and can be found at https://github.com/libgit2/rugged[]. +Let's take a look at the above example written using the Ruby bindings for Libgit2, which are named Rugged, and can be found at https://github.com/libgit2/rugged[^]. [source,ruby] ---- @@ -115,7 +115,7 @@ One example is pluggability: Libgit2 allows you to provide custom "`backends`" f Libgit2 allows custom backends for configuration, ref storage, and the object database, among other things. Let's take a look at how this works. -The code below is borrowed from the set of backend examples provided by the Libgit2 team (which can be found at https://github.com/libgit2/libgit2-backends[]). +The code below is borrowed from the set of backend examples provided by the Libgit2 team (which can be found at https://github.com/libgit2/libgit2-backends[^]). Here's how a custom backend for the object database is set up: [source,c] @@ -172,7 +172,7 @@ int git_odb_backend_mine(git_odb_backend **backend_out, /*…*/) } ---- -The subtlest constraint here is that `my_backend_struct`'s first member must be a `git_odb_backend` structure; this ensures that the memory layout is what the Libgit2 code expects it to be. +The subtlest constraint here is that ``my_backend_struct```'s first member must be a ``git_odb_backend`` structure; this ensures that the memory layout is what the Libgit2 code expects it to be. The rest of it is arbitrary; this structure can be as large or small as you need it to be. The initialization function allocates some memory for the structure, sets up the custom context, and then fills in the members of the `parent` structure that it supports. @@ -183,13 +183,13 @@ Take a look at the `include/git2/sys/odb_backend.h` file in the Libgit2 source f Libgit2 has bindings for many languages. Here we show a small example using a few of the more complete bindings packages as of this writing; libraries exist for many other languages, including C++, Go, Node.js, Erlang, and the JVM, all in various stages of maturity. -The official collection of bindings can be found by browsing the repositories at https://github.com/libgit2[]. +The official collection of bindings can be found by browsing the repositories at https://github.com/libgit2[^]. The code we'll write will return the commit message from the commit eventually pointed to by HEAD (sort of like `git log -1`). ===== LibGit2Sharp (((.NET)))(((C#)))(((Mono))) -If you're writing a .NET or Mono application, LibGit2Sharp (https://github.com/libgit2/libgit2sharp[]) is what you're looking for. +If you're writing a .NET or Mono application, LibGit2Sharp (https://github.com/libgit2/libgit2sharp[^]) is what you're looking for. The bindings are written in C#, and great care has been taken to wrap the raw Libgit2 calls with native-feeling CLR APIs. Here's what our example program looks like: @@ -204,7 +204,7 @@ For desktop Windows applications, there's even a NuGet package that will help yo (((Apple)))(((Objective-C)))(((Cocoa))) If your application is running on an Apple platform, you're likely using Objective-C as your implementation language. -Objective-Git (https://github.com/libgit2/objective-git[]) is the name of the Libgit2 bindings for that environment. +Objective-Git (https://github.com/libgit2/objective-git[^]) is the name of the Libgit2 bindings for that environment. The example program looks like this: [source,objc] @@ -219,7 +219,7 @@ Objective-git is fully interoperable with Swift, so don't fear if you've left Ob ===== pygit2 (((Python))) -The bindings for Libgit2 in Python are called Pygit2, and can be found at https://www.pygit2.org[]. +The bindings for Libgit2 in Python are called Pygit2, and can be found at https://www.pygit2.org[^]. Our example program: [source,python] @@ -233,5 +233,5 @@ pygit2.Repository("/path/to/repo") # open repository ==== Further Reading Of course, a full treatment of Libgit2's capabilities is outside the scope of this book. -If you want more information on Libgit2 itself, there's API documentation at https://libgit2.github.com/libgit2[], and a set of guides at https://libgit2.github.com/docs[]. +If you want more information on Libgit2 itself, there's API documentation at https://libgit2.github.com/libgit2[^], and a set of guides at https://libgit2.github.com/docs[^]. For the other bindings, check the bundled README and tests; there are often small tutorials and pointers to further reading there. diff --git a/book-en/contributors.asc b/book-en/contributors.asc index 8bfa48a7..32acb1e0 100644 --- a/book-en/contributors.asc +++ b/book-en/contributors.asc @@ -9,4 +9,3 @@ Thank you everyone for helping make this a better book for everyone. ---- include::contributors.txt[] ---- - diff --git a/book-en/dedication.asc b/book-en/dedication.asc index d7d826b8..0c75ccb4 100644 --- a/book-en/dedication.asc +++ b/book-en/dedication.asc @@ -4,5 +4,4 @@ _To my wife, Becky, without whom this adventure never would have begun. — Ben_ _This edition is dedicated to my girls. -To my wife Jessica who has supported me for all of these years and to my daughter Josephine, -who will support me when I'm too old to know what's going on. — Scott_ +To my wife Jessica who has supported me for all of these years and to my daughter Josephine, who will support me when I'm too old to know what's going on. — Scott_ diff --git a/book-en/introduction.asc b/book-en/introduction.asc index b2981600..23b261dc 100644 --- a/book-en/introduction.asc +++ b/book-en/introduction.asc @@ -40,8 +40,7 @@ A lot of organizations still use SVN and are not about to change, but by this po We also cover how to import projects from several different systems in case you do convince everyone to make the plunge. *Chapter 10* delves into the murky yet beautiful depths of Git internals. -Now that you know all about Git and can wield it with power and grace, you can move on to discuss how Git stores its objects, -what the object model is, details of packfiles, server protocols, and more. +Now that you know all about Git and can wield it with power and grace, you can move on to discuss how Git stores its objects, what the object model is, details of packfiles, server protocols, and more. Throughout the book, we will refer to sections of this chapter in case you feel like diving deep at that point; but if you are like us and want to dive into the technical details, you may want to read Chapter 10 first. We leave that up to you. diff --git a/book-en/license.asc b/book-en/license.asc index 490603e1..090996ab 100644 --- a/book-en/license.asc +++ b/book-en/license.asc @@ -1,4 +1,4 @@ [preface] -== Licence +== License include::../LICENSE.asc[] diff --git a/book-en/preface_schacon.asc b/book-en/preface_schacon.asc index 29d78e5e..bf31c08c 100644 --- a/book-en/preface_schacon.asc +++ b/book-en/preface_schacon.asc @@ -33,4 +33,3 @@ It's been amazing to watch Git grow over the past few years from a relatively ob I'm happy that Pro Git has done so well and has also been able to be one of the few technical books on the market that is both quite successful and fully open source. I hope you enjoy this updated edition of Pro Git. - diff --git a/book/01-introduction/sections/first-time-setup.asc b/book/01-introduction/sections/first-time-setup.asc index 55a5092c..2b65d5e1 100644 --- a/book/01-introduction/sections/first-time-setup.asc +++ b/book/01-introduction/sections/first-time-setup.asc @@ -1,4 +1,4 @@ -[[r_first_time]] +[[_first_time]] === Configuração Inicial do Git Agora que você tem o Git em seu sistema, você deve fazer algumas coisas para personalizar o ambiente Git. @@ -35,6 +35,7 @@ Se você quiser substituir essa informação com nome diferente para um projeto Muitas ferramentas GUI o ajudarão com isso quando forem usadas pela primeira vez. +[[_editor]] ==== Seu Editor Agora que a sua identidade está configurada, você pode escolher o editor de texto padrão que será chamado quando Git precisar que você entre uma mensagem. diff --git a/book/01-introduction/sections/help.asc b/book/01-introduction/sections/help.asc index f74a1be3..2676274a 100644 --- a/book/01-introduction/sections/help.asc +++ b/book/01-introduction/sections/help.asc @@ -1,4 +1,4 @@ -[[r_git_help]] +[[_git_help]] === Pedindo Ajuda Se você precisar de ajuda para usar o Git, há três formas de acessar a página do manual de ajuda (_manpage_) para qualquer um dos comandos Git: diff --git a/book/01-introduction/sections/basics.asc b/book/01-introduction/sections/what-is-git.asc similarity index 97% rename from book/01-introduction/sections/basics.asc rename to book/01-introduction/sections/what-is-git.asc index a32f0b5d..4f9477e8 100644 --- a/book/01-introduction/sections/basics.asc +++ b/book/01-introduction/sections/what-is-git.asc @@ -71,7 +71,7 @@ Quando você faz algo no Git, quase sempre dados são adicionados no banco de da Como em qualquer VCS, você pode perder alterações que ainda não tenham sido adicionadas em um _commit_; mas depois de fazer o _commit_ no Git do estado atual das alterações, é muito difícil que haja alguma perda, especialmente se você enviar regularmente o seu banco de dados para outro repositório. Isso faz com que o uso do Git seja somente alegria, porque sabemos que podemos experimentar sem o perigo de estragar algo. -Para um olhar mais aprofundado de como o Git armazena seus dados e como você pode recuperar dados que parecem perdidos, consulte <>. +Para um olhar mais aprofundado de como o Git armazena seus dados e como você pode recuperar dados que parecem perdidos, consulte <>. ==== Os Três Estados @@ -105,4 +105,4 @@ O fluxo de trabalho básico Git é algo assim: Se uma versão específica de um arquivo está no diretório Git, é considerado _commited_. Se for modificado, mas foi adicionado à área de preparo, é considerado preparado. E se ele for alterado depois de ter sido carregado, mas não foi preparado, ele é considerado modificado. -Em <>, você vai aprender mais sobre esses estados e como você pode tirar proveito deles ou pular a parte de preparação inteiramente. +Em <>, você vai aprender mais sobre esses estados e como você pode tirar proveito deles ou pular a parte de preparação inteiramente. diff --git a/book/02-git-basics/sections/aliases.asc b/book/02-git-basics/sections/aliases.asc index f6a7bbb0..a3684a37 100644 --- a/book/02-git-basics/sections/aliases.asc +++ b/book/02-git-basics/sections/aliases.asc @@ -1,4 +1,4 @@ -[[r_git_aliases]] +[[_git_aliases]] === Apelidos Git (((aliases))) diff --git a/book/02-git-basics/sections/getting-a-repository.asc b/book/02-git-basics/sections/getting-a-repository.asc index 38bdddc8..2eabb535 100644 --- a/book/02-git-basics/sections/getting-a-repository.asc +++ b/book/02-git-basics/sections/getting-a-repository.asc @@ -1,4 +1,4 @@ -[[r_getting_a_repo]] +[[_getting_a_repo]] === Obtendo um Repositório Git Você pode obter um projeto Git utilizando duas formas principais. @@ -49,14 +49,14 @@ $ git commit -m 'initial project version' Nós já veremos o que esses comandos fazem. Mas neste ponto você já tem um repositório Git com arquivos monitorados e um _commit_ inicial. -[[r_git_cloning]] +[[_git_cloning]] ==== Clonando um Repositório Existente Caso você queira obter a cópia de um repositório Git existente – por exemplo, um projeto que você queira contribuir – o comando para isso é `git clone`. Se você estiver familiarizado com outros sistemas VCS, tal como Subversion, você vai notar que o comando é `clone` e não `checkout`. Essa é uma diferença importante – em vez de receber apenas uma cópia para trabalho, o Git recebe uma cópia completa de praticamente todos os dados que o servidor possui. Cada versão de cada arquivo no histórico do projeto é obtida por padrão quando você executa `git clone`. -De fato, se o disco do servidor ficar corrompido, em geral você pode usar qualquer uma das cópias de qualquer um dos clientes para reverter o servidor ao estado em que estava quando foi clonado (talvez você perca algumas configurações do servidor, mas todos os dados versionados estarão lá — veja <> para mais detalhes). +De fato, se o disco do servidor ficar corrompido, em geral você pode usar qualquer uma das cópias de qualquer um dos clientes para reverter o servidor ao estado em que estava quando foi clonado (talvez você perca algumas configurações do servidor, mas todos os dados versionados estarão lá — veja <> para mais detalhes). Você clona um repositório com `git clone [url]`.(((git commands, clone))) Por exemplo, caso você queria clonar a biblioteca Git Linkable chamada libgit2, você pode fazer da seguinte forma: @@ -79,4 +79,4 @@ Este comando faz exatamente a mesma coisa que o anterior, mas o diretório de de O Git possui diversos protocolos de transferência que você pode utilizar. O exemplo anterior usa o protocolo `https://`, mas você também pode ver `git://` ou `user@server:path/to/repo.git`, que usam o protocolo de transferência SSH. -Em <> é apresentado todas as opções disponíveis com as quais o servidor pode ser configurado para acessar o seu repositório Git, e os prós e contras de cada uma. +Em <> é apresentado todas as opções disponíveis com as quais o servidor pode ser configurado para acessar o seu repositório Git, e os prós e contras de cada uma. diff --git a/book/02-git-basics/sections/recording-changes.asc b/book/02-git-basics/sections/recording-changes.asc index 8d096d77..d843c25a 100644 --- a/book/02-git-basics/sections/recording-changes.asc +++ b/book/02-git-basics/sections/recording-changes.asc @@ -16,7 +16,7 @@ Você prepara os arquivos editados e então faz commit das suas alterações, e .O ciclo de vida dos status de seus arquivos. image::images/lifecycle.png[The lifecycle of the status of your files.] -[[r_checking_status]] +[[_checking_status]] ==== Verificando os Status de Seus Arquivos A principal ferramenta que você vai usar para determinar quais arquivos estão em qual estado é o comando `git status`.(((git commands, status))) @@ -58,7 +58,7 @@ Você pode ver que o seu novo arquivo README é um arquivo não rastreado, porqu O comportamento do Git é dessa forma para que você não inclua acidentalmente arquivos binários gerados automaticamente ou outros arquivos que você não deseja incluir. Você _quer_ incluir o arquivo README, então vamos comeaçar a rastreá-lo. -[[r_tracking_files]] +[[_tracking_files]] ==== Rastreando Arquivos Novos Para começar a rastrear um novo arquivo, você deve usar o comando `git add`.(((git commands, add))) @@ -197,7 +197,7 @@ Há duas colunas de status na saída: a coluna da esquerda indica o status da á No exemplo anterior, o arquivo `README` foi modificado no diretório de trabalho mas ainda não foi para o _stage_, enquanto o arquivo `lib/simplegit.rb` foi modificado e foi para o _stage_. O arquivo `Rakefile` foi modificado, foi para o _stage_ e foi modificado de novo, de maneira que há alterações para ele tanto no estado preparado quanto no estado não-preparado. -[[r_ignoring]] +[[_ignoring]] ==== Ignorando Arquivos Frequentemente você terá uma classe de arquivos que não quer que sejam adicionados automaticamente pelo Git e nem mesmo que ele os mostre como não-rastreados. @@ -267,7 +267,7 @@ As regras definidas nesses `.gitignore` internos se aplicam somente aos arquivos Está fora do escopo deste livro explicar os detalhes de múltiplos arquivos `.gitignore`; veja `man gitignore` para mais informações. ==== -[[r_git_diff_staged]] +[[_git_diff_staged]] ==== Visualizando Suas Alterações Dentro e Fora do Stage Se o comando `git status` for vago demais para você -- você quer saber exatamente o que você alterou, não apenas quais arquivos foram alterados -- você pode usar o comando `git diff`.(((git commands, diff))) @@ -405,7 +405,7 @@ Se você executar `git difftool` em vez de `git diff`, você pode ver qualquer d Execute `git difftool --tool-help` para ver o que há disponível em seu sistema. ==== -[[r_committing_changes]] +[[_committing_changes]] ==== Fazendo Commit das Suas Alterações Agora que sua área de _stage_ está preparada do jeito que você quer, você pode fazer _commit_ das suas alterações. @@ -423,7 +423,7 @@ Fazendo isso, será aberto o editor de sua escolha. [NOTE] ==== -O editor é determinado pela variável de ambiente `EDITOR` -- normalmente o vim ou emacs, mas você pode escolher qualquer editor que quiser usando o comando `git config --global core.editor` como você viu em <>.(((editor, changing default)))(((git commands, config))) +O editor é determinado pela variável de ambiente `EDITOR` -- normalmente o vim ou emacs, mas você pode escolher qualquer editor que quiser usando o comando `git config --global core.editor` como você viu em <>.(((editor, changing default)))(((git commands, config))) ==== O editor mostra o seguinte texto (este é um exemplo da tela do Vim): @@ -502,7 +502,7 @@ Perceba que, nesse caso, você não tem que executar `git add` antes, para adici Isso ocorre porque a opção `-a` inclui todos os arquivos alterados. Isso é conveniente, mas cuidado; algumas vezes esta opção fará você incluir alterações indesejadas. -[[r_removing_files]] +[[_removing_files]] ==== Removendo Arquivos (((files, removing))) @@ -575,7 +575,7 @@ $ git rm \*~ Esse comando remove todos os arquivos cujos nomes terminem com um `~`. -[[r_git_mv]] +[[_git_mv]] ==== Movendo Arquivos (((files, moving))) diff --git a/book/02-git-basics/sections/remotes.asc b/book/02-git-basics/sections/remotes.asc index e988aacf..84b649bc 100644 --- a/book/02-git-basics/sections/remotes.asc +++ b/book/02-git-basics/sections/remotes.asc @@ -1,4 +1,4 @@ -[[r_remote_repos]] +[[_remote_repos]] === Trabalhando de Forma Remota Para colaborar com qualquer projeto Git, você precisará saber como gerenciar seus repositórios remotos. Repositórios remotos são versões de seu repositório hospedado na Internet ou em uma rede qualquer. @@ -53,7 +53,7 @@ origin git@github.com:mojombo/grit.git (push) Isto significa que nós podemos obter(_pull_) contribuições de qualquer um desses usuários muito facilmente. Nós podemos, adicionalmente, ter a permissão de atualizar(_push_) um ou mais destes, embora não possamos dizer isso nesse caso. -Note que estes repositórios remotos usam uma variedade de protocolos e nós falaremos mais sobre isso em <>. +Note que estes repositórios remotos usam uma variedade de protocolos e nós falaremos mais sobre isso em <>. ==== Adicionando Repositórios Remotos @@ -87,7 +87,7 @@ From https://github.com/paulboone/ticgit O _master branch_(ramo mestre) do Paul agora está acessível localmente como `pb/master` – você pode fundí-lo(_merge_) dentro de uma de suas ramificações(_branches_) ou você pode checar fora da ramificação local se você quiser inspecioná-lo. (Nós abordaremos o que são ramificações(_branches_) e como usá-las mais detalhadamente em <>. ) -[[r_fetching_and_pulling]] +[[_fetching_and_pulling]] ==== Buscando e Obtendo de seus Repositórios Remotos Como você viu, para obter dados de seus projetos remotos, você pode executar:(((git commands, fetch))) @@ -103,7 +103,7 @@ Se você clonar um repositório, o comando automaticamente adiciona àquele repo Se o `branch` atual é configurando para rastrear um `branch` remoto (veja a próxima seção e <> para mais informação), você pode usar o comando `git pull` para buscar(_fetch_) e então mesclar(_merge_) automaticamente aquele `branch` remoto dentro do seu `branch` atual.(((git commands, pull))) Este pode ser um fluxo de trabalho mais fácil e mais confortável para você, e por padrão, o comando `git clone` automaticamente configura a sua `master branch` local para rastrear a `master branch` remota ou qualquer que seja o nome do `branch` padrão no servidor de onde você o clonou. Executar `git pull` comumente busca os dados do servidor de onde você originalmente clonou e automaticamente tenta mesclá-lo dentro do código que você está atualmente trabalhando. -[[r_pushing_remotes]] +[[_pushing_remotes]] ==== Pushing to Your Remotes Quando você tem seu projeto em um ponto que deseja compartilhar, é necessário enviá-lo para o servidor remoto. @@ -120,7 +120,7 @@ Se você e outra pessoa clonarem o repositório ao mesmo tempo e ela utilizar o Primeiro você terá que atualizar localmente, incorporando o trabalho dela ao seu, só assim você poderá utilizar o comando push. Veja <> para informações mais detalhadas sobre como enviar para servidores remotos. -[[r_inspecting_remote]] +[[_inspecting_remote]] ==== Inspecionando o Servidor Remoto Se você quiser ver mais informações sobre um servidor remoto em particular, você pode usar o comando `git remote show [nome-remoto]`.(((git commands, remote))) diff --git a/book/02-git-basics/sections/tagging.asc b/book/02-git-basics/sections/tagging.asc index 50e80272..fde4a5c6 100644 --- a/book/02-git-basics/sections/tagging.asc +++ b/book/02-git-basics/sections/tagging.asc @@ -1,4 +1,4 @@ -[[r_git_tagging]] +[[_git_tagging]] === Criando Tags (((tags))) @@ -49,7 +49,7 @@ Tags anotadas, entretanto, são um armazenamento completo de objetos no banco de Elas têm checksum, contem marcações de nome, email e data; têm uma mensagem de tag; e podem ser assinadas e asseguradas pela GPG (GNU Privacy Guard). É geralmente recomendado que você crie tags anotadas assim você tem todas as informações; mas se você quer um tag temporária ou por alguma razão não quer manter todas as informações, tags do tipo leve esta disponíveis para isso. -[[r_annotated_tags]] +[[_annotated_tags]] ==== Tags Anotadas (((tags, annotated))) @@ -174,7 +174,7 @@ Date: Sun Apr 27 20:43:35 2008 -0700 ... ---- -[[r_sharing_tags]] +[[_sharing_tags]] ==== Compartilhando Tags Por padrão, o comando `git push` não envia as tags para os servidores remoto.(((git commands, push))) diff --git a/book/02-git-basics/sections/undoing.asc b/book/02-git-basics/sections/undoing.asc index 00742528..21473481 100644 --- a/book/02-git-basics/sections/undoing.asc +++ b/book/02-git-basics/sections/undoing.asc @@ -1,4 +1,4 @@ -[[r_undoing]] +[[_undoing]] === Desfazendo coisas Em qualquer estágio, você talvez queira desfazer algo. @@ -31,7 +31,7 @@ $ git commit --amend No final das contas você termina com um único commit – O segundo commit substitui o resultante do primeiro. -[[r_unstaging]] +[[_unstaging]] ==== Retirando um arquivo do Stage A próxima sessão demonstra como trabalhar com modificações na área stage e work directory. @@ -84,7 +84,7 @@ Entretanto, no cenário descrito acima, o arquivo no working directory está ina ===== Essa mágica usando o `git reset` é tudo que você precisa saber por enquanto sobre este comando. -Nós vamos entra mais no detalhe sobre o que o comando `reset` faz e como usá-lo de forma a fazer coisas realmente interessantes em <>. +Nós vamos entra mais no detalhe sobre o que o comando `reset` faz e como usá-lo de forma a fazer coisas realmente interessantes em <>. ==== Desfazendo as Modificações de um Arquivo @@ -129,5 +129,5 @@ Nunca use este comando a não ser que você saiba com certeza que não quer salv Se você gostaria de manter as modificações que fez no arquivo, porem precisa tirá-lo do caminho por enquanto, sugerimos que pule para a documentação sobre Branches<>; esta geralmente é a melhor forma de fazer isso. Lembre-se, qualquer coisa que sobre commit com Git pode quase sempre ser recuperada. -Até mesmo commits que estava em algum branches que foram deletados ou commits que forma sobre escritos através de um `--amend` podem ser recuperados (veja<> para recuperação de dados). +Até mesmo commits que estava em algum branches que foram deletados ou commits que forma sobre escritos através de um `--amend` podem ser recuperados (veja<> para recuperação de dados). Contudo, qualquer coisa que você perder que nunca sofreu commit pode ser considerada praticamente perdida. diff --git a/book/02-git-basics/sections/viewing-history.asc b/book/02-git-basics/sections/viewing-history.asc index 39b18a7a..f2d6b5e2 100644 --- a/book/02-git-basics/sections/viewing-history.asc +++ b/book/02-git-basics/sections/viewing-history.asc @@ -1,4 +1,4 @@ -[[r_viewing_history]] +[[_viewing_history]] === Vendo o histórico de Commits Depois de você ter criado vários commits ou se você clonou um repositório com um histórico de commits pré-existente, você vai provavelmente querer olhar para trás e ver o que aconteceu. diff --git a/book/03-git-branching/sections/basic-branching-and-merging.asc b/book/03-git-branching/sections/basic-branching-and-merging.asc index e693906b..3f8513ac 100644 --- a/book/03-git-branching/sections/basic-branching-and-merging.asc +++ b/book/03-git-branching/sections/basic-branching-and-merging.asc @@ -15,7 +15,7 @@ fazer a correção. Você fará o seguinte: . Após testar, fazer o merge do branch de correção, e fazer push para produção. . Voltar para sua história de usuário original e continuar trabalhando. -[[r_basic_branching]] +[[_basic_branching]] ==== Ramificação Básica (((branches, basic workflow))) @@ -63,7 +63,7 @@ Tudo o que você precisa fazer é voltar para o seu branch `master`. Entretanto, antes de fazer isso, note que se seu diretório de trabalho ou stage possui alterações ainda não commitadas que conflitam com o branch que você quer usar, o Git não deixará que você troque de branch. O melhor é que seu estado de trabalho atual esteja limpo antes de trocar de branches. -Há maneiras de contornar isso (a saber, o comando stash e commit com a opção --ammend) que iremos cobrir mais tarde, em <>. +Há maneiras de contornar isso (a saber, o comando stash e commit com a opção --ammend) que iremos cobrir mais tarde, em <>. Por agora, vamos considerar que você fez commit de todas as suas alterações, de forma que você pode voltar para o branch `master`: [source,console] @@ -143,7 +143,7 @@ image::images/basic-branching-6.png[Continuando o trabalho no branch `iss53`.] É importante frisar que o trabalho que você fez no seu branch `hotfix` não está contido nos arquivos do seu branch `iss53`. Caso você precise dessas alterações, você pode fazer o merge do branch `master` no branch `iss53` executando `git merge master`, ou você pode esperar para integrar essas alterações até que você decida mesclar o branch `iss53` de volta para `master` mais tarde. -[[r_basic_merging]] +[[_basic_merging]] ==== Mesclagem Básica (((branches, merging)))(((merging))) @@ -185,7 +185,7 @@ Você pode encerrar o chamado no seu sistema e excluir o branch: $ git branch -d iss53 ---- -[[r_basic_merge_conflicts]] +[[_basic_merge_conflicts]] ==== Conflitos Básicos de Merge (((merging, conflicts))) @@ -274,7 +274,7 @@ Você só tem que digitar o nome da ferramenta que você prefere usar. [NOTE] ==== -Se você precisa de ferramentas mais avançadas para resolver conflitos mais complicados, nós abordamos mais sobre merge em <>. +Se você precisa de ferramentas mais avançadas para resolver conflitos mais complicados, nós abordamos mais sobre merge em <>. ==== Após você sair da ferramenta, o Git pergunta se a operação foi bem sucedida. diff --git a/book/03-git-branching/sections/branch-management.asc b/book/03-git-branching/sections/branch-management.asc index 40d1e820..87b481d7 100644 --- a/book/03-git-branching/sections/branch-management.asc +++ b/book/03-git-branching/sections/branch-management.asc @@ -1,4 +1,4 @@ -[[r_branch_management]] +[[_branch_management]] === Gestão de Branches (((branches, managing))) diff --git a/book/03-git-branching/sections/nutshell.asc b/book/03-git-branching/sections/nutshell.asc index 354f62ee..93d456f6 100644 --- a/book/03-git-branching/sections/nutshell.asc +++ b/book/03-git-branching/sections/nutshell.asc @@ -1,4 +1,4 @@ -[[r_git_branches_overview]] +[[_git_branches_overview]] === Branches em poucas palavras Para realmente entender como o Git trabalha com Branches, precisamos dar um passo atrás e examinar como o Git armazena seus dados. @@ -46,7 +46,7 @@ A única razão pela qual quase todo repositório tem um é que o comando `git i .Um branch e seu histórico de commits image::images/branch-and-history.png[A branch and its commit history.] -[[r_create_new_branch]] +[[_create_new_branch]] ==== Criando um Novo Branch (((branches, creating))) @@ -88,7 +88,7 @@ f30ab (HEAD -> master, testing) add feature #32 - ability to add new formats to Você pode ver os branches `master` e `testing` que estão bem ali ao lado do commit `f30ab`. -[[r_switching_branches]] +[[_switching_branches]] ==== Alternando entre Branches (((branches, switching))) diff --git a/book/03-git-branching/sections/rebasing.asc b/book/03-git-branching/sections/rebasing.asc index 8432fd7c..5bdfc0f5 100644 --- a/book/03-git-branching/sections/rebasing.asc +++ b/book/03-git-branching/sections/rebasing.asc @@ -1,4 +1,4 @@ -[[r_rebasing]] +[[_rebasing]] === Rebase (((rebasing))) @@ -7,7 +7,7 @@ Nesta seção, você aprenderá o que é o rebase, como fazê-lo, por que é uma ==== O básico do Rebase -Se você voltar a um exemplo anterior de <>, você pode ver que o seu trabalho divergiu e fez commits em dois branches diferentes. +Se você voltar a um exemplo anterior de <<_basic_merging>>, você pode ver que o seu trabalho divergiu e fez commits em dois branches diferentes. .Um simples histórico de divergência image::images/basic-rebase-1.png[Simple divergent history.] @@ -131,7 +131,7 @@ $ git branch -d server .Histórico final de commits image::images/interesting-rebase-5.png[Final commit history.] -[[r_rebase_peril]] +[[_rebase_peril]] ==== Os perigos do Rebase (((rebasing, perils of))) @@ -161,14 +161,14 @@ image::images/perils-of-rebasing-2.png["Fetch more commits, and merge them into Em seguida, a pessoa que enviou o trabalho mesclado decide voltar atrás e realizar um rebase no trabalho em vez disso; ele faz um `git push --force` para sobrescrever o histórico no servidor. Você então busca daquele servidor, derrubando os novos commits. -[[r_pre_merge_rebase_work]] +[[_pre_merge_rebase_work]] .Alguém empurra commits que foram feitos rebase, abandonando commits nos quais você baseou seu trabalho image::images/perils-of-rebasing-3.png["Someone pushes rebased commits, abandoning commits you've based your work on."] Agora você está em apuros. Se você fizer um `git pull`, você criará um commit de merge que inclui as duas linhas do histórico, e seu repositório ficará assim: -[[r_merge_rebase_work]] +[[_merge_rebase_work]] .Você faz o merge do mesmo trabalho novamente em um novo commit de merge image::images/perils-of-rebasing-4.png[You merge in the same work again into a new merge commit.] @@ -176,7 +176,7 @@ Se você executar um `git log` quando seu histórico estiver assim, você verá Além disso, se você enviar esse histórico de volta ao servidor, reintroduzirá todos os commits realocados no servidor central, o que pode confundir ainda mais as pessoas. É bastante seguro assumir que o outro desenvolvedor não quer que `C4` e `C6` apareçam na história; é por isso que eles fizeram um rebase antes. -[[r_rebase_rebase]] +[[_rebase_rebase]] ==== Rebase quando vocês faz Rebase Se você *realmente* se encontrar em uma situação como essa, o Git tem mais alguma mágica que pode te ajudar. @@ -187,16 +187,16 @@ Isso é chamado de ``patch-id''. Se você puxar o trabalho que foi reescrito e fazer o rebase sobre os novos commits de seu parceiro, o Git pode muitas vezes descobrir o que é exclusivamente seu e aplicá-lo de volta ao novo branch. -Por exemplo, no cenário anterior, se em vez de fazer uma fusão quando estamos em <> executarmos `git rebase teamone/master`, Git irá: +Por exemplo, no cenário anterior, se em vez de fazer uma fusão quando estamos em <<_pre_merge_rebase_work>> executarmos `git rebase teamone/master`, Git irá: * Determinar qual trabalho é exclusivo para nosso branch (C2, C3, C4, C6, C7) * Determinar quais não são confirmações de merge (C2, C3, C4) * Determinar quais não foram reescritos no branch de destino (apenas C2 e C3, uma vez que C4 é o mesmo patch que C4') * Aplicar esses commits no topo de `teamone/master` -Então, em vez do resultado que vemos em <>, acabaríamos com algo mais parecido com <>. +Então, em vez do resultado que vemos em <<_merge_rebase_work>>, acabaríamos com algo mais parecido com <<_rebase_rebase_work>>. -[[r_rebase_rebase_work]] +[[_rebase_rebase_work]] .Rebase on top of force-pushed rebase work. image::images/perils-of-rebasing-5.png[Rebase on top of force-pushed rebase work.] diff --git a/book/03-git-branching/sections/remote-branches.asc b/book/03-git-branching/sections/remote-branches.asc index 42b9e117..b28c75f8 100644 --- a/book/03-git-branching/sections/remote-branches.asc +++ b/book/03-git-branching/sections/remote-branches.asc @@ -1,4 +1,4 @@ -[[r_remote_branches]] +[[_remote_branches]] === Branches remotos (((branches, remote)))(((references, remote))) @@ -44,7 +44,7 @@ image::images/remote-branches-3.png[`git fetch` updates your remote references.] Para demonstrar a existência de vários servidores remotos e como as branches remotas desses projetos remotos se parecem, vamos supor que você tenha outro servidor Git interno usado apenas para desenvolvimento por uma de suas equipes. Este servidor está em `git.team1.ourcompany.com`. -Você pode adicioná-lo como uma nova referência remota ao projeto em que está trabalhando atualmente executando o comando `git remote add` conforme abordamos em <>. +Você pode adicioná-lo como uma nova referência remota ao projeto em que está trabalhando atualmente executando o comando `git remote add` conforme abordamos em <>. Nomeie este servidor remoto como `teamone`, que será o seu apelido para toda a URL. .Adicionando outro servidor como remoto @@ -56,7 +56,7 @@ Porque esse servidor tem um subconjunto dos dados que seu servidor `origin` tem .Branch remoto de rastreamento para `teamone/master` image::images/remote-branches-5.png[Remote tracking branch for `teamone/master`.] -[[r_pushing_branches]] +[[_pushing_branches]] ==== Empurrando (Push) (((pushing))) @@ -95,7 +95,7 @@ Por padrão, ele solicitará essas informações no terminal para que o servidor Se você não quiser digitá-lo toda vez que for fazer o push, você pode configurar um ``credential cache''. O mais simples é mantê-lo na memória por alguns minutos, o que você pode configurar facilmente executando `git config --global credential.helper cache`. -Para obter mais informações sobre as várias opções de ``credential cache'' disponíveis, consulte <>. +Para obter mais informações sobre as várias opções de ``credential cache'' disponíveis, consulte <>. ==== Na próxima vez que um de seus colaboradores buscar no servidor, eles obterão uma referência de onde a versão do servidor do `serverfix` está no branch remoto `origin/serverfix`: @@ -126,7 +126,7 @@ Switched to a new branch 'serverfix' Isso lhe dá um branch local no qual você pode trabalhar que inicia onde está o `origin/serverfix`. -[[r_tracking_branches]] +[[_tracking_branches]] ==== Rastreando Branches (((branches, tracking)))(((branches, upstream))) @@ -218,7 +218,7 @@ Se você tiver um branch de rastreamento configurado conforme demonstrado na úl Geralmente é melhor usar os comandos `fetch` e `merge` explicitamente, já que o `git pull` muitas vezes pode ser confuso. -[[r_delete_branches]] +[[_delete_branches]] ==== Removendo Branches remotos (((branches, deleting remote))) diff --git a/book/03-git-branching/sections/workflows.asc b/book/03-git-branching/sections/workflows.asc index 482d4446..ca6404ce 100644 --- a/book/03-git-branching/sections/workflows.asc +++ b/book/03-git-branching/sections/workflows.asc @@ -30,7 +30,7 @@ Alguns projetos maiores também têm um ramo `proposto` ou `pu` (proposed update A ideia é que seus ramos estejam em vários níveis de estabilidade; quando eles atingem um nível mais estável, eles são mesclados no ramo acima deles. Novamente, não é necessário ter vários branches de longa duração, mas geralmente é útil, especialmente quando você está lidando com projetos muito grandes ou complexos. -[[r_topic_branch]] +[[_topic_branch]] ==== Branches por tópicos (((branches, topic))) diff --git a/book/04-git-server/sections/generating-ssh-key.asc b/book/04-git-server/sections/generating-ssh-key.asc index e03fbbf8..153fb420 100644 --- a/book/04-git-server/sections/generating-ssh-key.asc +++ b/book/04-git-server/sections/generating-ssh-key.asc @@ -1,4 +1,4 @@ -[[r_generate_ssh_key]] +[[_generate_ssh_key]] === Gerando Sua Chave Pública SSH (((Chaves SSH))) diff --git a/book/04-git-server/sections/git-on-a-server.asc b/book/04-git-server/sections/git-on-a-server.asc index 9fa0af55..6c757210 100644 --- a/book/04-git-server/sections/git-on-a-server.asc +++ b/book/04-git-server/sections/git-on-a-server.asc @@ -1,4 +1,4 @@ -[[r_git_on_the_server]] +[[_getting_git_on_a_server]] === Getting Git on a Server Now we'll cover setting up a Git service running these protocols on your own server. @@ -33,7 +33,7 @@ $ cp -Rf my_project/.git my_project.git There are a couple of minor differences in the configuration file; but for your purpose, this is close to the same thing. It takes the Git repository by itself, without a working directory, and creates a directory specifically for it alone. -[[r_bare_repo]] +[[_bare_repo]] ==== Putting the Bare Repository on a Server Now that you have a bare copy of your repository, all you need to do is put it on a server and set up your protocols. diff --git a/book/04-git-server/sections/gitlab.asc b/book/04-git-server/sections/gitlab.asc index 870d7a19..a5216f0e 100644 --- a/book/04-git-server/sections/gitlab.asc +++ b/book/04-git-server/sections/gitlab.asc @@ -51,7 +51,7 @@ Remoção de um usuário pode ser feito de duas formas. Todos os projetos e dados no namespace são removidos, e qualquer outro grupo que ele possua também será removido. Isso é obviamente uma ação muito mais permanete e destrutiva, e o uso disso é raro. -[[r_gitlab_groups_section]] +[[_gitlab_groups_section]] ===== Grupos Um grupo GitLab é um conjunto de projetos, juntamente com dados sobre como os usuários podem acessar esses projetos. @@ -113,7 +113,7 @@ A página inicial de cada projeto mostra as atividades recentes e os links ao lo ==== Trabalhando juntos A maneira mais simples de trabalhar juntos em um projeto GitLab é dar a outro usuário acesso direto de push (envio de commits) ao repositório Git. -Você pode adicionar um usuário a um projeto indo para a seção ``Membros'' das configurações desse projeto e associando o novo usuário com um nível de acesso (os diferentes níveis de acesso estão um pouco descritos em <>). +Você pode adicionar um usuário a um projeto indo para a seção ``Membros'' das configurações desse projeto e associando o novo usuário com um nível de acesso (os diferentes níveis de acesso estão um pouco descritos em <<_gitlab_groups_section>>). Ao fornecer a um usuário um nível de acesso de ``Desenvolvedor'' ou superior, esse usuário pode empurrar branches e ramificações diretamente para o repositório. Outra maneira mais dissociada de colaboração é usar solicitações de mesclagem. diff --git a/book/04-git-server/sections/protocols.asc b/book/04-git-server/sections/protocols.asc index a29b0c7b..74699a84 100644 --- a/book/04-git-server/sections/protocols.asc +++ b/book/04-git-server/sections/protocols.asc @@ -49,7 +49,7 @@ Os prós dos repositórios baseados em arquivos são que eles são simples e usa Se você já tem um sistema de arquivos compartilhado que seu time inteiro tem acesso, configurar um repositório é muito fácil. Você cola a cópia do repositório vazio (bare repository) em algum lugar que todos tem acesso para ler/escrever permissões como você faria com qualquer outro diretório. -Nós discutiremos como exportar uma cópia de um repositório vazio (bare repository) para esse propósito em <>. +Nós discutiremos como exportar uma cópia de um repositório vazio (bare repository) para esse propósito em <<_getting_git_on_a_server>>. Esta é uma boa opção para rapidamente pegar o trabalho do repositório de trabalho de outra pessoa. Se você ou seu colega de trabalho estão trabalhando no mesmo projeto e ele quiser que você verifique alguma coisa, executar um comando como `git pull /home/john/project` geralmente é mais fácil que enviar para um servidor remoto e baixar. @@ -93,7 +93,7 @@ De fato, para serviços como GitHub, a URL que você vê o repositório online ( (((protocols, dumb HTTP))) -Se o servidor não responder com serviço Git HTTP Smart, o cliente Git vai tentar voltar para o protocolo mais simples, o HTTP "Dumb". O protocolo Dumb espera que o repositório vazio (bare repository) do Git sirva os arquivos como um servidor web normal. A beleza do protocolo HTTP Dumb é sua simplicidade de configuração. Basicamente, tudo que você tem que fazer é colocar o repositório vazio (bare repository) sob o documento raiz do seu HTTP e configurar um hook `post-update` específico, e você está pronto (Veja <>). Nesse ponto, qualquer um que possa acessar o servidor web no qual você colocou o repositório também pode cloná-lo. Para acessos de leitura para seu repositório por HTTP, faça algo como: +Se o servidor não responder com serviço Git HTTP Smart, o cliente Git vai tentar voltar para o protocolo mais simples, o HTTP "Dumb". O protocolo Dumb espera que o repositório vazio (bare repository) do Git sirva os arquivos como um servidor web normal. A beleza do protocolo HTTP Dumb é sua simplicidade de configuração. Basicamente, tudo que você tem que fazer é colocar o repositório vazio (bare repository) sob o documento raiz do seu HTTP e configurar um hook `post-update` específico, e você está pronto (Veja <>). Nesse ponto, qualquer um que possa acessar o servidor web no qual você colocou o repositório também pode cloná-lo. Para acessos de leitura para seu repositório por HTTP, faça algo como: [source,console] ---- @@ -139,7 +139,7 @@ Fora isso, há muitas pequenas vantagens que outros protocolos tem sobre o proto Se você está usando HTTP para envios autenticados, inserir suas credenciais é algumas vezes mais complicado que usar chaves por SSH. Há contudo várias ferramentas para armazenar credenciais que você pode usar, incluindo o acesso por Keychain no OSX e o Gerenciados de Credenciais no Windows, para fazer isso bastante indolor. -Leia <> para ver como configurar um gerenciador de credenciais no seu sistema. +Leia <> para ver como configurar um gerenciador de credenciais no seu sistema. ==== O Protocolo SSH diff --git a/book/04-git-server/sections/setting-up-server.asc b/book/04-git-server/sections/setting-up-server.asc index e24c27ba..345b17bc 100644 --- a/book/04-git-server/sections/setting-up-server.asc +++ b/book/04-git-server/sections/setting-up-server.asc @@ -1,4 +1,4 @@ -[[r_setting_up_server]] +[[_setting_up_server]] === Setting Up the Server Let's walk through setting up SSH access on the server side. diff --git a/book/05-distributed-git/sections/contributing.asc b/book/05-distributed-git/sections/contributing.asc index c237b4ba..c0778c34 100644 --- a/book/05-distributed-git/sections/contributing.asc +++ b/book/05-distributed-git/sections/contributing.asc @@ -1,4 +1,4 @@ -[[r_contributing_project]] +[[_contributing_project]] === Contribuindo com um Projeto (((contributing))) @@ -30,7 +30,7 @@ Com que frequência? Todas estas questões podem afetar como você contribui efetivamente para o projeto e que fluxos de trabalho são adequados ou possíveis para você. Iremos abordar aspectos de cada uma delas em uma série de estudos de caso, indo do simples ao mais complexo; você deve ser capaz de construir fluxos de trabalho específicos para suas necessidades com estes exemplos. -[[r_commit_guidelines]] +[[_commit_guidelines]] ==== Diretrizes para Fazer Commites Antes de vermos estudos de casos específicos, uma observação rápida sobre mensagens de commit. @@ -49,11 +49,11 @@ Se você executar este comando antes do commit, você perceberá se está preste Depois tente fazer cada commit como um conjunto lógico de mudanças. Se possível, tente digerir suas modificações -- não programe o final de semana inteiro em cinco diferentes problemas e então publique tudo em um commit massivo na segunda-feira. Mesmo que você não publique durante o fim de semana, use a área de stage na segunda-feira para dividir seu trabalho em ao menos um commit por assunto, com uma mensagem útil em cada commit. -Se algumas alterações modificarem o mesmo arquivo, tente executar `git add --patch` para colocar na área de stage os arquivos parcialmente (explicado em detalhes em <>). +Se algumas alterações modificarem o mesmo arquivo, tente executar `git add --patch` para colocar na área de stage os arquivos parcialmente (explicado em detalhes em <>). O retrato do projeto no final do branch é idêntico você fazendo um commit ou cinco, desde que todas as mudanças forem eventualmente adicionadas, então tente fazer as coisas mais fáceis para seus colegas desenvolvedores quando eles tiverem que revisar suas mudanças. Esta abordagem também facilita retirar ou reverter uma das alterações se você precisar depois. -<> descreve vários truques úteis do Git para reescrever o histórico e colocar interativamente arquivos na área de stage -- utilize estas ferramentas para criar um histórico limpo e compreensível antes de enviar o trabalho para alguém. +<> descreve vários truques úteis do Git para reescrever o histórico e colocar interativamente arquivos na área de stage -- utilize estas ferramentas para criar um histórico limpo e compreensível antes de enviar o trabalho para alguém. A última coisa para ter em mente é a mensagem do commit. Manter o hábito de criar boas mensagens de commit facilita muito usar e colaborar com o Git. @@ -98,7 +98,7 @@ Para o bem da concisão, muitos dos exemplos neste livro não tem mensagens de c Resumindo, faça o que digo, não faça o que faço. ==== -[[r_private_team]] +[[_private_team]] ==== Time Pequeno Privado (((contributing, private small team))) @@ -254,7 +254,7 @@ Date: Fri May 29 16:01:27 2009 -0700 ---- A sintaxe `issue54..origin/master` é um filtro de log que pede ao Git mostrar apenas estes commites que estão no branch seguinte (neste caso `origin/master`) e não estão no primeiro branch (neste caso `issue54`). -Iremos cobrir esta sintaxe em detalhes em <>. +Iremos cobrir esta sintaxe em detalhes em <>. Do resultado acima, podemos ver que há um único commit que John fez e Jessica não mesclou no trabalho local dela. Se ela mesclar `origin/master`, aquele é o único commit que irá modificar seu trabalho local. @@ -426,7 +426,7 @@ To jessica@githost:simplegit.git ---- Isto é chamado de _refspec_. -Veja <> para uma discussão mais detalhada sobre os refspecs do Git e as diferentes coisas que você pode fazer com eles. +Veja <> para uma discussão mais detalhada sobre os refspecs do Git e as diferentes coisas que você pode fazer com eles. Também perceba a flag `-u`; isto é abreviação de `--set-upstream`, que configura os branches para facilitar publicar e baixar depois. De repente, Jessica recebe um email de John, contando que publicou algumas modificações no branch `featureA` no qual eles estavam colaborando, e ele pede a Jessica para dar uma olhada. @@ -496,7 +496,7 @@ A sequência do fluxo de trabalho que você viu aqui é parecida com isto: .Sequencia básica deste fluxo de trabalho coordenado image::images/managed-team-flow.png[Basic sequence of this managed-team workflow] -[[r_public_project]] +[[_public_project]] ==== Fork de Projeto Público (((contributing, public small project))) @@ -522,7 +522,7 @@ $ git commit [NOTE] ==== -Você pode querer usar `rebase -i` para resumir seu trabalho a um único commit, ou rearranjar o trabalho em commites que deixarão o trabalho mais fácil para os mantenedores revisarem -- veja <> para mais informações sobre rebase interativo. +Você pode querer usar `rebase -i` para resumir seu trabalho a um único commit, ou rearranjar o trabalho em commites que deixarão o trabalho mais fácil para os mantenedores revisarem -- veja <> para mais informações sobre rebase interativo. ==== Quando seu trabalho no branch é finalizado e você está pronto para mandá-lo para os mantenedores, vá para a página original do projeto e clique no botão ``Fork'', criando seu próprio fork editável do projeto. @@ -535,7 +535,7 @@ $ git remote add meufork Você então precisa publicar seu trabalho neste repositório. É mais fácil publicar o branch em que você está trabalhando no seu repositório fork, ao invés de mesclar este trabalho no seu branch `master` e publicar assim. -A razão é que se o seu trabalho não for aceito ou for selecionado a dedo (_cherry-pick_), você não tem que voltar seu branch `master` (a operação do Git `cherry-pick` é vista em mais detalhes em <>). +A razão é que se o seu trabalho não for aceito ou for selecionado a dedo (_cherry-pick_), você não tem que voltar seu branch `master` (a operação do Git `cherry-pick` é vista em mais detalhes em <>). Se os mantenedores executarem um `merge`, `rebase` ou `cherry-pick` no seu trabalho, você irá eventualmente receber seu trabalho de novo através do repositório deles de qualquer jeito. Em qualquer um dos casos, você pode publicar seu trabalho com: @@ -635,7 +635,7 @@ Neste ponto, você pode notificar os mantenedores que você já fez as mudanças .Histórico de commit depois do trabalho em `featureBv2` image::images/public-small-3.png[Commit history after `featureBv2` work] -[[r_project_over_email]] +[[_project_over_email]] ==== Projeto Público através de Email (((contributing, public large project))) diff --git a/book/05-distributed-git/sections/distributed-workflows.asc b/book/05-distributed-git/sections/distributed-workflows.asc index 634d5d07..e3720457 100644 --- a/book/05-distributed-git/sections/distributed-workflows.asc +++ b/book/05-distributed-git/sections/distributed-workflows.asc @@ -33,7 +33,7 @@ Este fluxo de trabalho atrai várias pessoas pois já é um modelo familiar e co Isto não é limitado apenas a equipes pequenas. Com o modelo de ramificações do Git, é possível para centenas de desenvolvedores conseguirem trabalhar em um único projeto através de dúzias de ramos (_branches_) simultaneamente. -[[r_integration_manager]] +[[_integration_manager]] ==== Fluxo de Trabalho Coordenado (((workflows, integration manager))) diff --git a/book/05-distributed-git/sections/maintaining.asc b/book/05-distributed-git/sections/maintaining.asc index 3309758c..a4e5469a 100644 --- a/book/05-distributed-git/sections/maintaining.asc +++ b/book/05-distributed-git/sections/maintaining.asc @@ -28,7 +28,7 @@ $ git checkout -b sc/ruby_client master Now you're ready to add the contributed work that you received into this topic branch and determine if you want to merge it into your longer-term branches. -[[r_patches_from_email]] +[[_patches_from_email]] ==== Applying Patches from Email (((email, applying patches from))) @@ -65,7 +65,7 @@ error: ticgit.gemspec: patch does not apply If there is no output, then the patch should apply cleanly. This command also exits with a non-zero status if the check fails, so you can use it in scripts if you want. -[[r_git_am]] +[[_git_am]] ===== Applying a Patch with `am` (((git commands, am))) @@ -181,7 +181,7 @@ This is nice if you have a number of patches saved, because you can view the pat When all the patches for your topic are applied and committed into your branch, you can choose whether and how to integrate them into a longer-running branch. -[[r_checking_out_remotes]] +[[_checking_out_remotes]] ==== Checking Out Remote Branches (((branches, remote))) @@ -217,7 +217,7 @@ From https://github.com/onetimeguy/project Merge made by the 'recursive' strategy. ---- -[[r_what_is_introduced]] +[[_what_is_introduced]] ==== Determining What Is Introduced (((branches, diffing))) @@ -366,7 +366,7 @@ Thus, when you clone the Git repository, you have four branches that you can che The Git project's workflow is specialized. To clearly understand this you could check out the https://github.com/git/git/blob/master/Documentation/howto/maintain-git.txt[Git Maintainer's guide]. -[[r_rebase_cherry_pick]] +[[_rebase_cherry_pick]] ===== Rebasing and Cherry-Picking Workflows (((workflows, rebasing and cherry-picking))) @@ -423,14 +423,14 @@ Now, whenever you do a merge that resolves conflicts, the resolution will be rec If you need to, you can interact with the rerere cache using the `git rerere` command. When it's invoked alone, Git checks its database of resolutions and tries to find a match with any current merge conflicts and resolve them (although this is done automatically if `rerere.enabled` is set to `true`). There are also subcommands to see what will be recorded, to erase specific resolution from the cache, and to clear the entire cache. -We will cover rerere in more detail in <>. +We will cover rerere in more detail in <>. -[[r_tagging_releases]] +[[_tagging_releases]] ==== Tagging Your Releases (((tags)))(((tags, signing))) When you've decided to cut a release, you'll probably want to assign a tag so you can re-create that release at any point going forward. -You can create a new tag as discussed in <>. +You can create a new tag as discussed in <>. If you decide to sign the tag as the maintainer, the tagging may look something like this: [source,console] @@ -481,7 +481,7 @@ $ git show maintainer-pgp-pub | gpg --import They can use that key to verify all your signed tags. Also, if you include instructions in the tag message, running `git show ` will let you give the end user more specific instructions about tag verification. -[[r_build_number]] +[[_build_number]] ==== Generating a Build Number (((build numbers)))(((git commands, describe))) @@ -502,7 +502,7 @@ By default, the `git describe` command requires annotated tags (tags created wit You can also use this string as the target of a `git checkout` or `git show` command, although it relies on the abbreviated SHA-1 value at the end, so it may not be valid forever. For instance, the Linux kernel recently jumped from 8 to 10 characters to ensure SHA-1 object uniqueness, so older `git describe` output names were invalidated. -[[r_preparing_release]] +[[_preparing_release]] ==== Preparing a Release (((releasing)))(((git commands, archive))) @@ -527,7 +527,7 @@ $ git archive master --prefix='project/' --format=zip > `git describe master`.zi You now have a nice tarball and a zip archive of your project release that you can upload to your website or email to people. -[[r_the_shortlog]] +[[_the_shortlog]] ==== The Shortlog (((git commands, shortlog))) diff --git a/book/06-github/sections/1-setting-up-account.asc b/book/06-github/sections/1-setting-up-account.asc index 35c75e02..b3409204 100644 --- a/book/06-github/sections/1-setting-up-account.asc +++ b/book/06-github/sections/1-setting-up-account.asc @@ -29,7 +29,7 @@ A partir de agora, você é completamente capaz de se conectar aos repositórios Entretanto, para simplesmente clonar repositórios públicos, você não precisa nem mesmo estar logado - a conta que criamos vem à tona quando fazemos fork nos nossos projetos e dermos push em nossos forks mais para frente. Se você quiser usar repositórios remotos via SSH, você precisa configurar uma chave pública. -Se você ainda não tiver uma, veja <>. +Se você ainda não tiver uma, veja <>. Abra as configurações da sua conta usando o link no canto superior direito da janela: .Link para ``Account settings''. @@ -49,7 +49,7 @@ Certifique-se de colocar um nome que possa lembrar para sua chave SSH. Você pode nomear cada uma das suas chaves (e.g. "Meu laptop" or "Conta atual") então se você precisar fazer revoke de uma chave você pode facilmente dizer qual você está procurando. ==== -[[r_personal_avatar]] +[[_personal_avatar]] ==== Seu Avatar A seguir, caso queira, você pode substituir o avatar que é gerado para você com uma imagem de sua escolha. Primeiro vá para a aba ``Profile'' (acima da aba SSH Keys) e clique em ``Upload new picture''. @@ -71,11 +71,11 @@ Se de repente você tiver carregado um avatar para um serviço Gravatar (geralme A maneira que o GitHub mapeia seus commits do Git para seu usuário é pelo endereço de email. Se você utiliza múltiplos endereços de email nos seus commits e deseja que o GitHub os conecte adequadamente, você precisa adicionar todos os endereços de email que você usou na seção Email da seção admin. -[[r_add_email_addresses]] +[[_add_email_addresses]] .Adicionar endereços de email image::images/email-settings.png[Add all your email addresses.] -Em <> podemos ver alguns dos diferentes estados possíveis. +Em <<_add_email_addresses>> podemos ver alguns dos diferentes estados possíveis. O endereço no topo é verificado e definido como endereço padrão, o que significa que é onde você vai receber quaisquer notificações e convites. O segundo endereço é verificado e então pode ser definido como endereço padrão caso você queira trocá-los. O último endereço não é verficado, o que significa que você não pode torná-lo seu endereço padrão. diff --git a/book/06-github/sections/2-contributing.asc b/book/06-github/sections/2-contributing.asc index 8d753ec1..03e8aaf3 100644 --- a/book/06-github/sections/2-contributing.asc +++ b/book/06-github/sections/2-contributing.asc @@ -26,13 +26,13 @@ image::images/forkbutton.png[The ``Fork'' button.] Depois de alguns segundos, você vai para a página do seu novo projeto, com sua própria cópia alterável do código. -[[r_github_flow]] +[[_github_flow]] ==== O fluxo do GitHub (((GitHub, Flow))) O GitHub é desenhado ao redor de uma fluxo particular de colaboção, centrado nas Pull Requests. Este fluxo funciona se você está colaborando com um time integrado em uma único repositório compartilhado, com uma empresa distribuída globalmente ou com uma rede de estranhos contribuindo para o projeto com dúzias de forks. -É centrado no fluxo <> abordado em <>. +É centrado no fluxo <> abordado em <>. Aqui está como geralmente funciona: @@ -44,7 +44,7 @@ Aqui está como geralmente funciona: 6. Discusta e opicionalmente continue commitando. 7. O proprietário do projeto faz merge ou fecha o Pull Request. -Isto é basicamente o fluxo de trabalho de um Integration Manager abordado em <>, mas em vez de usar o email para se comunicarem e revisarem mudanças, os times usam ferramentas do GitHub basedas na web. +Isto é basicamente o fluxo de trabalho de um Integration Manager abordado em <>, mas em vez de usar o email para se comunicarem e revisarem mudanças, os times usam ferramentas do GitHub basedas na web. Vamos observar um exemplo de como propor uma alteração para um projeto open source hospedado no GitHub usando esse fluxo. @@ -144,28 +144,28 @@ image::images/blink-04-pr-comment.png[PR line comment] Uma vez que o mantenedor faça este comentário, a pessoa que abriu o Pull Request (na verdade qualquer um que estiver observando o repositório) receberá uma notificação. Vamos customizar isso depois, mas se ele tivesse ativado suas configurações de email, Tony receberia um email como este: -[[r_email_notification]] +[[_email_notification]] .Comentários enviados como notificações pelo email image::images/blink-04-email.png[Email notification] -Qualquer um pode deixar um comentário geral no Pull Request. Em <> podemos ver um exemplo no qual o proprietário do projeto comenta uma linha de código e deixa um comentário geral na seção de discussão. Você pode ver que os comentários aparecem na discussão também. +Qualquer um pode deixar um comentário geral no Pull Request. Em <<_pr_discussion>> podemos ver um exemplo no qual o proprietário do projeto comenta uma linha de código e deixa um comentário geral na seção de discussão. Você pode ver que os comentários aparecem na discussão também. -[[r_pr_discussion]] +[[_pr_discussion]] .Página de discussão de um Pull Request image::images/blink-05-general-comment.png[PR discussion page] Agora o contribuinte pode ver o que ele precisa fazer para ter sua alteração aceita. Felizmente isso é muito simples. Além do email, onde você tem que fazer re-roll das suas series e reenviar para a lista de email, com o GitHub você simplesmente commita no tópico de branch de novo e faz um push que automaticamente atualiza o Pull Request. -Em <> você também pode ver que o comentário do código antigo foi colapsado no Pull Request atualizado, desde que seja de uma linha que foi alterada. +Em <<_pr_final>> você também pode ver que o comentário do código antigo foi colapsado no Pull Request atualizado, desde que seja de uma linha que foi alterada. Adicionar commits para um Pull Request não ativa uma notificação, então uma vez que Tony fez push de suas correções ele decide deixar um comentário para informar ao proprietário do projeto que ele fez as alterações requeridas. -[[r_pr_final]] +[[_pr_final]] .Pull Request final image::images/blink-06-final.png[PR final] -Uma coisa interessante para se notar é que se você clicar na aba ``Files Changed'' nesse Pull Request, você vai ter o diff ``unificado'' -- isto é, o agregado total das diferenças que seriam introduzidas no seu branch principal se este tópico de branch levasse merge. O `git diff` basicamente mostra automaticamente `git master...` para o branch no qual este Pull Request se baseia. Veja <> para mais informação sobre este tipo de diff. +Uma coisa interessante para se notar é que se você clicar na aba ``Files Changed'' nesse Pull Request, você vai ter o diff ``unificado'' -- isto é, o agregado total das diferenças que seriam introduzidas no seu branch principal se este tópico de branch levasse merge. O `git diff` basicamente mostra automaticamente `git master...` para o branch no qual este Pull Request se baseia. Veja <> para mais informação sobre este tipo de diff. A outra coisa de você vai notar é que o GitHub confere se o Pull Request fez um merge válido e te fornece um botão para fazer merge no servidor. Esse botão apenas mostra se você tem acesso de escrita no repositório e um merge trivial se possível. Se você clicar nele, o GitHub fornecerá um merge ``no-fast-forward'', significando que mesmo se *pudesse* ser um fast-forward, será criado um commit de merge. @@ -189,17 +189,17 @@ Agora que cobrimos o básico sobre contribuição de um projeto no GitHub, vamos Esta é um distinção importante, porque normalmente a alteração é sugerida antes do código atingir a perfeição, o que é muito mais raro em séries de patches de contribuições baseadas em listas de emails. Isso possibilita uma conversação mais cedo com os mantenedores para chegar a uma solução adequada por meio da dedicação da comunidade. Quando código é proposto com um Pull Request e os mantenedores ou a comunidade sugerem uma alteração, a série de patches normalmente não é recarregado, mas sim a diferença sofre push como um novo commit na branch, movendo a conversação para frente com o contexto do trabalho anterior preservado. -Por exemplo, se você voltar e olhar de novo em <>, você vai notar que o contribuinte não deu rebase no seu commit e enviou outro Pull Request. Em vez disso ele adicionou novos commits e fez push deles para uma branch existente. Desta forma se você voltar e olhar esse Pull Request no futuro, você poderá facilmente encontrar todo o contexto do motivo de cada decisão. Pressionar o botão ``Merge'' no site intencionalmente cria commit de merge que referencia o Pull Request e torna mais fácil voltar e pesquisar a conversação original caso necessário. +Por exemplo, se você voltar e olhar de novo em <<_pr_final>>, você vai notar que o contribuinte não deu rebase no seu commit e enviou outro Pull Request. Em vez disso ele adicionou novos commits e fez push deles para uma branch existente. Desta forma se você voltar e olhar esse Pull Request no futuro, você poderá facilmente encontrar todo o contexto do motivo de cada decisão. Pressionar o botão ``Merge'' no site intencionalmente cria commit de merge que referencia o Pull Request e torna mais fácil voltar e pesquisar a conversação original caso necessário. ===== Mantendo-se no Upstream Se o seu Pull Request ficar desatualizado ou de qualquer modo não for um merge válido, você vai querer consertá-lo para que o mantenedor possa facilmente fazer merge dele. O GitHub vai testar isso para você e informar na parte inferior de cada Pull Request se o merge é trivial ou não. -[[r_pr_fail]] +[[_pr_fail]] .Pull Request que não é um merge válido image::images/pr-01-fail.png[PR merge failure] -Se você ver algo como <>, você vai querer consertar seu branch para que ele fique verde e o para que mantenedor não tenha trabalho extra. +Se você ver algo como <<_pr_fail>>, você vai querer consertar seu branch para que ele fique verde e o para que mantenedor não tenha trabalho extra. Você tem duas opções principais para lidar com isso. Você pode fazer rebase da sua branch no topo ou em qualquer branch alvo (que normalmente é a branch `master` do repositório que você deu fork), ou você pode fazer merge da branch alvo na sua branch. @@ -250,13 +250,13 @@ To https://github.com/tonychacon/blink Uma vez que você fez isso, o Pull Request será automaticamnete atualizado e re-avaliado para ver se é um merge válido. -[[r_pr_merge_fix]] +[[_pr_merge_fix]] .O Pull Request agora é válído image::images/pr-02-merge-fix.png[PR fixed] Um dos grandes feitos do Git é que você pode fazer isso continuamente. Se você tem um projeto muito grande, você pode facilmente fazer merge de uma branch específica de novo e de novo se preocupando apenas com conflitos que sugiram desde da última vez que você deu merge, tornando o projeto muito mais gerenciável. -Se você realmente quer fazer rebase da branch para limpá-la, você até pode fazê-lo, mas uma atitude muito mais encorajada é não forçar uma branch em um Pull Request que já está aberto. Se outra pessoa deu push e trabalhou mais no projeto, você pode conferir todos os erros destacados em <>. Em vez disso, faça push da branch rebaseada para uma nova branch no GitHub e abra um novo Pull Request referenciando o antigo, e então feche o original. +Se você realmente quer fazer rebase da branch para limpá-la, você até pode fazê-lo, mas uma atitude muito mais encorajada é não forçar uma branch em um Pull Request que já está aberto. Se outra pessoa deu push e trabalhou mais no projeto, você pode conferir todos os erros destacados em <>. Em vez disso, faça push da branch rebaseada para uma nova branch no GitHub e abra um novo Pull Request referenciando o antigo, e então feche o original. ===== Referências @@ -264,23 +264,23 @@ Sua próxima pergunta deve ser ``Como eu referencio um Pull Request antigo?''. N Vamos começar com como referenciar outro Pull Request ou Issue. Todos os Pull Requests e Issues são números atribuídos e eles são únicos dentro do projeto. Por exemplo, você não pode ter um Pull Request #3 _e_ uma Issue #3. Se você quiser referenciar qualquer Pull Request ou Issue de outro repositório, você pode simplesmente # em qualquer comentário ou descrição. Você também pode ser mais específico quanto se a Issue ou o Pull Request está ativo em outro lugar; escreva username# se você está referenciando uma Issue ou um Pull Request em algum fork do repositório em que você está, ou usernam/repo# para referenciar algo em outro repositório. -Vamos olhar um exemplo. Digamos que rebaseamos a branch no exemplo anterior, criamos um novo pull request para ele e agora queremos referenciar um antigo pull request para o novo. Nós também queremos referenciar um problema no fork do repositório e um problema em um projeto completamente diferente. Podemos preencher a descrição como em <>. +Vamos olhar um exemplo. Digamos que rebaseamos a branch no exemplo anterior, criamos um novo pull request para ele e agora queremos referenciar um antigo pull request para o novo. Nós também queremos referenciar um problema no fork do repositório e um problema em um projeto completamente diferente. Podemos preencher a descrição como em <<_pr_references>>. -[[r_pr_references]] +[[_pr_references]] .Referências cruzadas em um Pull Request. image::images/mentions-01-syntax.png[PR references] -Quando fazemos submit deste pull request, veremos tudo renderizado como em <>. -[[r_pr_references_render]] +Quando fazemos submit deste pull request, veremos tudo renderizado como em <<_pr_references_render>>. +[[_pr_references_render]] .Referências cruzadas renderizadas em um Pull Request. image::images/mentions-02-render.png[PR references rendered] Note que a URL completa que colocamos no GitHub foi encurtada para a informação necessária. -Agora se Tony voltar e fechar o Pull Request original, poderemos ver isso sendo mencionado no novo, o GitHub automaticamente cria um evento de trackback na timeline do Pull Request. Isso significa que qualquer um que visite este Pull Request e veja que está fechado pode facilmente seguir o link para o que o sucedeu. O link parecerá algo parecido com <>. +Agora se Tony voltar e fechar o Pull Request original, poderemos ver isso sendo mencionado no novo, o GitHub automaticamente cria um evento de trackback na timeline do Pull Request. Isso significa que qualquer um que visite este Pull Request e veja que está fechado pode facilmente seguir o link para o que o sucedeu. O link parecerá algo parecido com <<_pr_closed>>. -[[r_pr_closed]] +[[_pr_closed]] .Referências cruzadas renderizadas em um Pull Request. image::images/mentions-03-closed.png[PR closed] @@ -290,9 +290,9 @@ Além de números de issues, você também pode referenciar um commit específic Fazer link com outras Issues é só o começo das coisas interessantes que você pode fazer com quase qualquer caixa de texto no GitHub. Em uma Issue e em descrições de Pull Request, comentários, comentários de código e outros, você pode usar o chamado ``Markdown aprimorado do GitHub''. Markdown é similar a um texto comum mas renderizado de forma rica. -Veja <> para um exemplo de como comentários ou textos podem ser escritos e renderizados usando Markdown. +Veja <<_example_markdown>> para um exemplo de como comentários ou textos podem ser escritos e renderizados usando Markdown. -[[r_example_markdown]] +[[_example_markdown]] .Um exemplo escrito e renderizado do Markdown melhorado do GitHub. image::images/markdown-01-example.png[Example Markdown] @@ -311,17 +311,17 @@ Você pode criar uma task list como essa: - [ ] Document the code ---- -Se incluírmos isso na descrição do nosso Pull Request ou Issue, nós veremos ele ser renderizado como em <> +Se incluírmos isso na descrição do nosso Pull Request ou Issue, nós veremos ele ser renderizado como em <<_task_lists>> -[[r_task_lists]] +[[_task_lists]] .Task lists renderizadas em um comentário de Markdown. image::images/markdown-02-tasks.png[Example Task List] Isso é normalmente usado em Pull Requests para indicar tudo aquilo que você gostaria de fazer em uma branch antes do Pull Request estar pronto para merge. A parte realmente legal é que você pode simplesmente clicar nas checkboxes para atualizar o comentário -- você não precisa editar o Markdown diretamente para marcar suas tasks. -Não só isso, o GitHub vai procurar task lists nas suas Issues e Pull Requests e vai mostrá-las como metadata em uma páginas que as lista. Por exemplo, se você tem um Pull Request com tasks e você olha na página de resumo de todos os Pull Requests, você pode ver o quão longe isso vai. Isso ajuda as pessoas a dividir Pull Requests em subtasks e ajudar outras pessoas a acompanhar o progresso da branch. Você pode ver um exemplo disso em <>. +Não só isso, o GitHub vai procurar task lists nas suas Issues e Pull Requests e vai mostrá-las como metadata em uma páginas que as lista. Por exemplo, se você tem um Pull Request com tasks e você olha na página de resumo de todos os Pull Requests, você pode ver o quão longe isso vai. Isso ajuda as pessoas a dividir Pull Requests em subtasks e ajudar outras pessoas a acompanhar o progresso da branch. Você pode ver um exemplo disso em <<_task_list_progress>>. -[[r_task_list_progress]] +[[_task_list_progress]] .Resumo das Task lists na lista de Pull Requests. image::images/markdown-03-task-summary.png[Example Task List] @@ -343,9 +343,9 @@ for(int i=0 ; i < 5 ; i++) ``` ---- -Se você adicionar um nome de linguagem como fizemos com 'java', o GitHub também vai tentar destacar o trecho. No caso do exemplo acima, o código vai ser renderizado como em <>. +Se você adicionar um nome de linguagem como fizemos com 'java', o GitHub também vai tentar destacar o trecho. No caso do exemplo acima, o código vai ser renderizado como em <<_md_code>>. -[[r_md_code]] +[[_md_code]] .Um exemplo de código cercado renderizado. image::images/markdown-04-fenced-code.png[Rendered fenced code] @@ -363,9 +363,9 @@ A citação vai parecer algo como isto: How big are these slings and in particular, these arrows? ---- -Uma vez renderizado, o comentário vai se parecer com <>. +Uma vez renderizado, o comentário vai se parecer com <<_md_quote>>. -[[r_md_quote]] +[[_md_quote]] .Exemplo de citação renderizada image::images/markdown-05-quote.png[Rendered quoting] @@ -373,7 +373,7 @@ image::images/markdown-05-quote.png[Rendered quoting] Finalmente, você também pode usar emoji nos seus comentários. Na verdade isso é usado extensivamente em comentários que você encontra em várias Issues e Pull Requests no GitHub. Também há um auxiliador de emoji no GitHub. Se você está digitando um comentário e começa com o caractere `:`, um autocompletador vai te ajudar a achar o que você está procurando. -[[r_md_emoji_auto]] +[[_md_emoji_auto]] .Autocompletador de emoji em ação. image::images/markdown-06-emoji-complete.png[Emoji autocompleter] @@ -390,9 +390,9 @@ I :eyes: that :bug: and I :cold_sweat:. :clap::tada::panda_face: ---- -Quando renderizado, deveria se parecer com <>. +Quando renderizado, deveria se parecer com <<_md_emoji>>. -[[r_md_emoji]] +[[_md_emoji]] .Comentando que nem louco com emoji image::images/markdown-07-emoji.png[Emoji] @@ -410,8 +410,8 @@ http://www.emoji-cheat-sheet.com Isso tecnicamente não é o Markdown aprimorado do GitHub, mas é incrivelmente útil. Além de adicionar links Markdown de images nos comentários, o que pode ser bem difícil de encontrar e inserir as URLs, o GitHub permite arrastar e soltar imagens em áreas de texto para incorporá-las.. -[[r_md_drag]] +[[_md_drag]] .Arraste e solte imagens para carregá-las e incorporá-las. image::images/markdown-08-drag-drop.png[Drag and drop images] -Se você olhar em <>, você pode ver um pequeno aviso ``Ver como Markdown'' acima da área de texto. Clicando nele gera uma cola de tudo que você pode fazer com o Markdown no GitHub. +Se você olhar em <<_md_drag>>, você pode ver um pequeno aviso ``Ver como Markdown'' acima da área de texto. Clicando nele gera uma cola de tudo que você pode fazer com o Markdown no GitHub. diff --git a/book/06-github/sections/3-maintaining.asc b/book/06-github/sections/3-maintaining.asc index 49e7b0f8..f0500cb7 100644 --- a/book/06-github/sections/3-maintaining.asc +++ b/book/06-github/sections/3-maintaining.asc @@ -1,4 +1,4 @@ -[[r_maintaining_gh_project]] +[[_maintaining_gh_project]] === Maintaining a Project Now that we're comfortable contributing to a project, let's look at the other side: creating, maintaining and administering your own project. @@ -6,12 +6,12 @@ Now that we're comfortable contributing to a project, let's look at the other si ==== Creating a New Repository Let's create a new repository to share our project code with. -Start by clicking the ``New repository'' button on the right-hand side of the dashboard, or from the `+` button in the top toolbar next to your username as seen in <>. +Start by clicking the ``New repository'' button on the right-hand side of the dashboard, or from the `+` button in the top toolbar next to your username as seen in <<_new_repo_dropdown>>. .The ``Your repositories'' area. image::images/newrepo.png[The ``Your repositories'' area.] -[[r_new_repo_dropdown]] +[[_new_repo_dropdown]] .The ``New repository'' dropdown. image::images/new-repo.png[The ``new repository'' dropdown.] @@ -24,7 +24,7 @@ All you really have to do here is provide a project name; the rest of the fields For now, just click the ``Create Repository'' button, and boom – you have a new repository on GitHub, named `/`. Since you have no code there yet, GitHub will show you instructions for how to create a brand-new Git repository, or connect an existing Git project. -We won't belabor this here; if you need a refresher, check out <>. +We won't belabor this here; if you need a refresher, check out <>. Now that your project is hosted on GitHub, you can give the URL to anyone you want to share your project with. Every project on GitHub is accessible over HTTPS as `https://github.com//`, and over SSH as `git@github.com:/`. @@ -65,13 +65,13 @@ The only difference is that the ones in a fork are often from people where you c For these examples, let's assume you are ``tonychacon'' and you've created a new Arduino code project named ``fade''. -[[r_email_notifications]] +[[_email_notifications]] ===== Email Notifications Someone comes along and makes a change to your code and sends you a Pull Request. -You should get an email notifying you about the new Pull Request and it should look something like <>. +You should get an email notifying you about the new Pull Request and it should look something like <<_email_pr>>. -[[r_email_pr]] +[[_email_pr]] .Email notification of a new Pull Request. image::images/maint-01-email.png[Pull Request email notification] @@ -81,7 +81,7 @@ It gives you a link to the Pull Request on GitHub. It also gives you a few URLs that you can use from the command line. If you notice the line that says `git pull patch-1`, this is a simple way to merge in a remote branch without having to add a remote. -We went over this quickly in <>. +We went over this quickly in <>. If you wish, you can create and switch to a topic branch and then run this command to merge in the Pull Request changes. The other interesting URLs are the `.diff` and `.patch` URLs, which as you may guess, provide unified diff and patch versions of the Pull Request. @@ -94,7 +94,7 @@ $ curl http://github.com/tonychacon/fade/pull/1.patch | git am ===== Collaborating on the Pull Request -As we covered in <>, you can now have a conversation with the person who opened the Pull Request. +As we covered in <<_github_flow>>, you can now have a conversation with the person who opened the Pull Request. You can comment on specific lines of code, comment on whole commits or comment on the entire Pull Request itself, using GitHub Flavored Markdown everywhere. Every time someone else comments on the Pull Request you will continue to get email notifications so you know there is activity happening. @@ -108,24 +108,24 @@ Once the code is in a place you like and want to merge it in, you can either pul If the merge is trivial, you can also just hit the ``Merge'' button on the GitHub site. This will do a ``non-fast-forward'' merge, creating a merge commit even if a fast-forward merge was possible. This means that no matter what, every time you hit the merge button, a merge commit is created. -As you can see in <>, GitHub gives you all of this information if you click the hint link. +As you can see in <<_merge_button>>, GitHub gives you all of this information if you click the hint link. -[[r_merge_button]] +[[_merge_button]] .Merge button and instructions for merging a Pull Request manually. image::images/maint-02-merge.png[Merge button] If you decide you don't want to merge it, you can also just close the Pull Request and the person who opened it will be notified. -[[r_pr_refs]] +[[_pr_refs]] ===== Pull Request Refs If you're dealing with a *lot* of Pull Requests and don't want to add a bunch of remotes or do one time pulls every time, there is a neat trick that GitHub allows you to do. -This is a bit of an advanced trick and we'll go over the details of this a bit more in <>, but it can be pretty useful. +This is a bit of an advanced trick and we'll go over the details of this a bit more in <>, but it can be pretty useful. GitHub actually advertises the Pull Request branches for a repository as sort of pseudo-branches on the server. By default you don't get them when you clone, but they are there in an obscured way and you can access them pretty easily. -To demonstrate this, we're going to use a low-level command (often referred to as a ``plumbing'' command, which we'll read about more in <>) called `ls-remote`. +To demonstrate this, we're going to use a low-level command (often referred to as a ``plumbing'' command, which we'll read about more in <>) called `ls-remote`. This command is generally not used in day-to-day Git operations but it's useful to show us what references are present on the server. If we run this command against the ``blink'' repository we were using earlier, we will get a list of all the branches and tags and other references in the repository. @@ -229,7 +229,7 @@ If you see a Pull Request that is moving in the right direction and you have an When you go to open a Pull Request, there is a box at the top of the page that specifies which branch you're requesting to pull to and which you're requesting to pull from. If you hit the ``Edit'' button at the right of that box you can change not only the branches but also which fork. -[[r_pr_targets]] +[[_pr_targets]] .Manually change the Pull Request target fork and branch. image::images/maint-04-target.png[PR targets] @@ -270,9 +270,9 @@ The two choices are to get notifications over ``Email'' and over ``Web'' and you ====== Web Notifications Web notifications only exist on GitHub and you can only check them on GitHub. -If you have this option selected in your preferences and a notification is triggered for you, you will see a small blue dot over your notifications icon at the top of your screen as seen in <>. +If you have this option selected in your preferences and a notification is triggered for you, you will see a small blue dot over your notifications icon at the top of your screen as seen in <<_not_center>>. -[[r_not_center]] +[[_not_center]] .Notification center. image::images/maint-08-notifications-page.png[Notification center] @@ -288,12 +288,12 @@ Many GitHub power users will simply turn off email notifications entirely and ma Email notifications are the other way you can handle notifications through GitHub. If you have this turned on you will get emails for each notification. -We saw examples of this in <> and <>. +We saw examples of this in <<_email_notification>> and <<_email_pr>>. The emails will also be threaded properly, which is nice if you're using a threading email client. There is also a fair amount of metadata embedded in the headers of the emails that GitHub sends you, which can be really helpful for setting up custom filters and rules. -For instance, if we look at the actual email headers sent to Tony in the email shown in <>, we will see the following among the information sent: +For instance, if we look at the actual email headers sent to Tony in the email shown in <<_email_pr>>, we will see the following among the information sent: [source,mbox] ---- @@ -341,9 +341,9 @@ Since GitHub will render this file, you can embed images or links in it for adde ==== CONTRIBUTING The other special file that GitHub recognizes is the `CONTRIBUTING` file. -If you have a file named `CONTRIBUTING` with any file extension, GitHub will show <> when anyone starts opening a Pull Request. +If you have a file named `CONTRIBUTING` with any file extension, GitHub will show <<_contrib_file>> when anyone starts opening a Pull Request. -[[r_contrib_file]] +[[_contrib_file]] .Opening a Pull Request when a CONTRIBUTING file exists. image::images/maint-09-contrib.png[Contributing notice] @@ -358,7 +358,7 @@ Generally there are not a lot of administrative things you can do with a single If you are using a branch other than ``master'' as your default branch that you want people to open Pull Requests on or see by default, you can change that in your repository's settings page under the ``Options'' tab. -[[r_default_branch]] +[[_default_branch]] .Change the default branch for a project. image::images/maint-10-default-branch.png[Default branch] @@ -368,7 +368,7 @@ Simply change the default branch in the dropdown and that will be the default fo If you would like to transfer a project to another user or an organization in GitHub, there is a ``Transfer ownership'' option at the bottom of the same ``Options'' tab of your repository settings page that allows you to do this. -[[r_transfer_project]] +[[_transfer_project]] .Transfer a project to another GitHub user or Organization. image::images/maint-11-transfer.png[Transfer] diff --git a/book/06-github/sections/4-managing-organization.asc b/book/06-github/sections/4-managing-organization.asc index 0a6bd942..ea211908 100644 --- a/book/06-github/sections/4-managing-organization.asc +++ b/book/06-github/sections/4-managing-organization.asc @@ -1,4 +1,4 @@ -[[r_github_orgs]] +[[_github_orgs]] === Managing an organization (((GitHub, organizations))) @@ -24,7 +24,7 @@ As an owner in an organization, when you fork a repository, you'll have the choi When you create new repositories you can create them either under your personal account or under any of the organizations that you are an owner in. You also automatically ``watch'' any new repository created under these organizations. -Just like in <>, you can upload an avatar for your organization to personalize it a bit. +Just like in <<_personal_avatar>>, you can upload an avatar for your organization to personalize it a bit. Also just like personal accounts, you have a landing page for the organization that lists all of your repositories and can be viewed by other people. Now let's cover some of the things that are a bit different with an organizational account. @@ -39,16 +39,16 @@ Teams make this easy, without having to manage the collaborators for every indiv The Organization page shows you a simple dashboard of all the repositories, users and teams that are under this organization. -[[r_org_page]] +[[_org_page]] .The Organization page. image::images/orgs-01-page.png[] -To manage your Teams, you can click on the Teams sidebar on the right hand side of the page in <>. +To manage your Teams, you can click on the Teams sidebar on the right hand side of the page in <<_org_page>>. This will bring you to a page you can use to add members to the team, add repositories to the team or manage the settings and access control levels for the team. Each team can have read only, read/write or administrative access to the repositories. -You can change that level by clicking the ``Settings'' button in <>. +You can change that level by clicking the ``Settings'' button in <<_team_page>>. -[[r_team_page]] +[[_team_page]] .The Team page. image::images/orgs-02-teams.png[] @@ -65,7 +65,7 @@ Special-interest teams like `ux`, `css`, or `refactoring` are useful for certain Organizations also give owners access to all the information about what went on under the organization. You can go to the 'Audit Log' tab and see what events have happened at an organization level, who did them and where in the world they were done. -[[r_audit_log]] +[[_audit_log]] .The Audit log. image::images/orgs-03-audit.png[] diff --git a/book/06-github/sections/5-scripting.asc b/book/06-github/sections/5-scripting.asc index 95ccbce7..45646cb1 100644 --- a/book/06-github/sections/5-scripting.asc +++ b/book/06-github/sections/5-scripting.asc @@ -13,18 +13,18 @@ The Hooks and Services section of GitHub repository administration is the easies First we'll take a look at Services. Both the Hooks and Services integrations can be found in the Settings section of your repository, where we previously looked at adding Collaborators and changing the default branch of your project. -Under the ``Webhooks and Services'' tab you will see something like <>. +Under the ``Webhooks and Services'' tab you will see something like <<_services_hooks>>. -[[r_services_hooks]] +[[_services_hooks]] .Services and Hooks configuration section. image::images/scripting-01-services.png[Services and hooks] There are dozens of services you can choose from, most of them integrations into other commercial and open source systems. Most of them are for Continuous Integration services, bug and issue trackers, chat room systems and documentation systems. We'll walk through setting up a very simple one, the Email hook. -If you choose ``email'' from the ``Add Service'' dropdown, you'll get a configuration screen like <>. +If you choose ``email'' from the ``Add Service'' dropdown, you'll get a configuration screen like <<_service_config>>. -[[r_service_config]] +[[_service_config]] .Email service configuration. image::images/scripting-02-email-service.png[Email service] @@ -42,10 +42,10 @@ You specify a URL and GitHub will post an HTTP payload to that URL on any event Generally the way this works is you can setup a small web service to listen for a GitHub hook payload and then do something with the data when it is received. -To enable a hook, you click the ``Add webhook'' button in <>. -This will bring you to a page that looks like <>. +To enable a hook, you click the ``Add webhook'' button in <<_services_hooks>>. +This will bring you to a page that looks like <<_web_hook>>. -[[r_web_hook]] +[[_web_hook]] .Web hook configuration. image::images/scripting-03-webhook.png[Web hook] @@ -101,7 +101,7 @@ You can see the last few deliveries that GitHub has tried to make for that webho For each hook you can dig down into when it was delivered, if it was successful and the body and headers for both the request and the response. This makes it incredibly easy to test and debug your hooks. -[[r_web_hook_debug]] +[[_web_hook_debug]] .Web hook debugging information. image::images/scripting-04-webhook-debug.png[Webhook debug] @@ -174,7 +174,7 @@ There are several ways to authenticate. You can use basic authentication with just your username and password, but generally it's a better idea to use a personal access token. You can generate this from the ``Applications'' tab of your settings page. -[[r_access_token]] +[[_access_token]] .Generate your access token from the ``Applications'' tab of your settings page. image::images/scripting-05-access-token.png[Access Token] @@ -215,9 +215,9 @@ $ curl -H "Content-Type: application/json" \ } ---- -Now if you go to that issue, you can see the comment that we just successfully posted as in <>. +Now if you go to that issue, you can see the comment that we just successfully posted as in <<_api_comment>>. -[[r_api_comment]] +[[_api_comment]] .A comment posted from the GitHub API. image::images/scripting-06-comment.png[API Comment] @@ -282,9 +282,9 @@ In this web hook handler we look through each commit that was just pushed, we lo In this case you can send a state ('success', 'failure', 'error'), a description of what happened, a target URL the user can go to for more information and a ``context'' in case there are multiple statuses for a single commit. For example, a testing service may provide a status and a validation service like this may also provide a status -- the ``context'' field is how they're differentiated. -If someone opens a new Pull Request on GitHub and this hook is set up, you may see something like <>. +If someone opens a new Pull Request on GitHub and this hook is set up, you may see something like <<_commit_status>>. -[[r_commit_status]] +[[_commit_status]] .Commit status via the API. image::images/scripting-07-status.png[Commit status] @@ -296,7 +296,7 @@ This is really useful if you're using this API for test results so you don't acc Though we've been doing nearly everything through `curl` and simple HTTP requests in these examples, several open-source libraries exist that make this API available in a more idiomatic way. At the time of this writing, the supported languages include Go, Objective-C, Ruby, and .NET. -Check out http://github.com/octokit[] for more information on these, as they handle much of the HTTP for you. +Check out https://github.com/octokit[] for more information on these, as they handle much of the HTTP for you. Hopefully these tools can help you customize and modify GitHub to work better for your specific workflows. For complete documentation on the entire API as well as guides for common tasks, check out https://developer.github.com[]. diff --git a/book/07-git-tools/sections/advanced-merging.asc b/book/07-git-tools/sections/advanced-merging.asc index df385986..bb52ef68 100644 --- a/book/07-git-tools/sections/advanced-merging.asc +++ b/book/07-git-tools/sections/advanced-merging.asc @@ -1,4 +1,4 @@ -[[r_advanced_merging]] +[[_advanced_merging]] === Advanced Merging Merging in Git is typically fairly easy. @@ -14,7 +14,7 @@ We'll also cover some of the different, non-standard types of merges you can do, ==== Merge Conflicts -While we covered some basics on resolving merge conflicts in <>, for more complex conflicts, Git provides a few tools to help you figure out what's going on and how to better deal with the conflict. +While we covered some basics on resolving merge conflicts in <>, for more complex conflicts, Git provides a few tools to help you figure out what's going on and how to better deal with the conflict. First of all, if at all possible, try to make sure your working directory is clean before doing a merge that may have conflicts. If you have work in progress, either commit it to a temporary branch or stash it. @@ -106,7 +106,7 @@ CONFLICT (content): Merge conflict in hello.rb Automatic merge failed; fix conflicts and then commit the result. ---- -[[r_abort_merge]] +[[_abort_merge]] ===== Aborting a Merge We now have a few options. @@ -154,7 +154,7 @@ Since in this case, the actual file changes were not conflicting, once we ignore This is a lifesaver if you have someone on your team who likes to occasionally reformat everything from spaces to tabs or vice-versa. -[[r_manual_remerge]] +[[_manual_remerge]] ===== Manual File Re-merging Though Git handles whitespace pre-processing pretty well, there are other types of changes that perhaps Git can't handle automatically, but are scriptable fixes. @@ -301,7 +301,7 @@ Removing hello.ours.rb Removing hello.theirs.rb ---- -[[r_checking_out_conflicts]] +[[_checking_out_conflicts]] ===== Checking Out Conflicts Perhaps we're not happy with the resolution at this point for some reason, or maybe manually editing one or both sides still didn't work well and we need more context. @@ -399,14 +399,14 @@ The `git checkout` command can also take `--ours` and `--theirs` options, which This can be particularly useful for conflicts of binary files where you can simply choose one side, or where you only want to merge certain files in from another branch - you can do the merge and then checkout certain files from one side or the other before committing. -[[r_merge_log]] +[[_merge_log]] ===== Merge Log Another useful tool when resolving merge conflicts is `git log`. This can help you get context on what may have contributed to the conflicts. Reviewing a little bit of history to remember why two lines of development were touching the same area of code can be really helpful sometimes. -To get a full list of all of the unique commits that were included in either branch involved in this merge, we can use the ``triple dot'' syntax that we learned in <>. +To get a full list of all of the unique commits that were included in either branch involved in this merge, we can use the ``triple dot'' syntax that we learned in <<_triple_dot>>. [source,console] ---- @@ -525,7 +525,7 @@ index 0399cd5,59727f0..e1d0799 hello() ---- -[[r_undoing_merges]] +[[_undoing_merges]] ==== Undoing Merges Now that you know how to create a merge commit, you'll probably make some by mistake. @@ -547,7 +547,7 @@ In most cases, if you follow the errant `git merge` with `git reset --hard HEAD~ .History after `git reset --hard HEAD~` image::images/undomerge-reset.png[History after `git reset --hard HEAD~`.] -We covered `reset` back in <>, so it shouldn't be too hard to figure out what's going on here. +We covered `reset` back in <<_git_reset>>, so it shouldn't be too hard to figure out what's going on here. Here's a quick refresher: `reset --hard` usually goes through three steps: . Move the branch HEAD points to. @@ -556,10 +556,10 @@ Here's a quick refresher: `reset --hard` usually goes through three steps: . Make the working directory look like the index. The downside of this approach is that it's rewriting history, which can be problematic with a shared repository. -Check out <> for more on what can happen; the short version is that if other people have the commits you're rewriting, you should probably avoid `reset`. +Check out <> for more on what can happen; the short version is that if other people have the commits you're rewriting, you should probably avoid `reset`. This approach also won't work if any other commits have been created since the merge; moving the refs would effectively lose those changes. -[[r_reverse_commit]] +[[_reverse_commit]] ===== Reverse the commit If moving the branch pointers around isn't going to work for you, Git gives you the option of making a new commit which undoes all the changes from an existing one. diff --git a/book/07-git-tools/sections/bundling.asc b/book/07-git-tools/sections/bundling.asc index b5efa839..489f455f 100644 --- a/book/07-git-tools/sections/bundling.asc +++ b/book/07-git-tools/sections/bundling.asc @@ -1,4 +1,4 @@ -[[r_bundling]] +[[_bundling]] === Bundling Though we've covered the common ways to transfer Git data over a network (HTTP, SSH, etc), there is actually one more way to do so that is not commonly used but can actually be quite useful. @@ -83,7 +83,7 @@ Unlike the network protocols which figure out the minimum set of data to transfe Now, you could just do the same thing and bundle the entire repository, which will work, but it's better to just bundle up the difference - just the three commits we just made locally. In order to do that, you'll have to calculate the difference. -As we described in <>, you can specify a range of commits in a number of ways. +As we described in <<_commit_ranges>>, you can specify a range of commits in a number of ways. To get the three commits that we have in our master branch that weren't in the branch we originally cloned, we can use something like `origin/master..master` or `master ^origin/master`. You can test that with the `log` command. diff --git a/book/07-git-tools/sections/credentials.asc b/book/07-git-tools/sections/credentials.asc index 175fb7ea..4628bf8a 100644 --- a/book/07-git-tools/sections/credentials.asc +++ b/book/07-git-tools/sections/credentials.asc @@ -1,4 +1,4 @@ -[[r_credential_caching]] +[[_credential_caching]] === Credential Storage (((credentials))) diff --git a/book/07-git-tools/sections/debugging.asc b/book/07-git-tools/sections/debugging.asc index 85438091..bf65ddf8 100644 --- a/book/07-git-tools/sections/debugging.asc +++ b/book/07-git-tools/sections/debugging.asc @@ -3,7 +3,7 @@ Git also provides a couple of tools to help you debug issues in your projects. Because Git is designed to work with nearly any type of project, these tools are pretty generic, but they can often help you hunt for a bug or culprit when things go wrong. -[[r_file_annotation]] +[[_file_annotation]] ==== File Annotation If you track down a bug in your code and want to know when it was introduced and why, file annotation is often your best tool. @@ -63,7 +63,7 @@ This is really useful. Normally, you get as the original commit the commit where you copied the code over, because that is the first time you touched those lines in this file. Git tells you the original commit where you wrote those lines, even if it was in another file. -[[r_binary_search]] +[[_binary_search]] ==== Binary Search Annotating a file helps if you know where the issue is to begin with. diff --git a/book/07-git-tools/sections/interactive-staging.asc b/book/07-git-tools/sections/interactive-staging.asc index 1c939cc7..d448ebc5 100644 --- a/book/07-git-tools/sections/interactive-staging.asc +++ b/book/07-git-tools/sections/interactive-staging.asc @@ -1,4 +1,4 @@ -[[r_interactive_staging]] +[[_interactive_staging]] === Interactive Staging Git comes with a couple of scripts that make some command-line tasks easier. diff --git a/book/07-git-tools/sections/replace.asc b/book/07-git-tools/sections/replace.asc index d4b0ea79..dd931c66 100644 --- a/book/07-git-tools/sections/replace.asc +++ b/book/07-git-tools/sections/replace.asc @@ -1,4 +1,4 @@ -[[r_replace]] +[[_replace]] === Replace Git's objects are unchangeable, but it does provide an interesting way to pretend to replace objects in its database with other objects. @@ -94,7 +94,7 @@ $ echo 'get history from blah blah blah' | git commit-tree 9c68fdc^{tree} The `commit-tree` command is one of a set of commands that are commonly referred to as 'plumbing' commands. These are commands that are not generally meant to be used directly, but instead are used by *other* Git commands to do smaller jobs. On occasions when we're doing weirder things like this, they allow us to do really low-level things but are not meant for daily use. -You can read more about plumbing commands in <> +You can read more about plumbing commands in <> ===== image::images/replace3.png[] diff --git a/book/07-git-tools/sections/rerere.asc b/book/07-git-tools/sections/rerere.asc index 1fe82139..d8e16f9f 100644 --- a/book/07-git-tools/sections/rerere.asc +++ b/book/07-git-tools/sections/rerere.asc @@ -1,4 +1,4 @@ -[[r_rerere]] +[[ref_rerere]] === Rerere The `git rerere` functionality is a bit of a hidden feature. @@ -146,7 +146,7 @@ You can see that it "Recorded resolution for FILE". image::images/rerere2.png[] Now, let's undo that merge and then rebase it on top of our master branch instead. -We can move our branch back by using `reset` as we saw in <>. +We can move our branch back by using `reset` as we saw in <<_git_reset>>. [source,console] ---- @@ -224,7 +224,7 @@ def hello end ---- -We saw an example of this in <>. +We saw an example of this in <<_advanced_merging>>. For now though, let's re-resolve it by just running `rerere` again: [source,console] diff --git a/book/07-git-tools/sections/reset.asc b/book/07-git-tools/sections/reset.asc index 8f80d65b..f817d354 100644 --- a/book/07-git-tools/sections/reset.asc +++ b/book/07-git-tools/sections/reset.asc @@ -1,4 +1,4 @@ -[[r_git_reset]] +[[_git_reset]] === Reset Demystified Before moving on to more specialized tools, let's talk about `reset` and `checkout`. @@ -48,7 +48,7 @@ $ git ls-tree -r HEAD The `cat-file` and `ls-tree` commands are ``plumbing'' commands that are used for lower level things and not really used in day-to-day work, but they help us see what's going on here. -[[r_the_index]] +[[_the_index]] ===== The Index The Index is your *proposed next commit*. @@ -161,7 +161,7 @@ With `reset --soft`, it will simply stop there. Now take a second to look at that diagram and realize what happened: it essentially undid the last `git commit` command. When you run `git commit`, Git creates a new commit and moves the branch that HEAD points to up to it. When you `reset` back to `HEAD~` (the parent of HEAD), you are moving the branch back to where it was, without changing the Index or Working Directory. -You could now update the Index and run `git commit` again to accomplish what `git commit --amend` would have done (see <>). +You could now update the Index and run `git commit` again to accomplish what `git commit --amend` would have done (see <<_git_amend>>). ===== Step 2: Updating the Index (--mixed) @@ -222,7 +222,7 @@ If we look at the diagram for that command and think about what `git add` does, image::images/reset-path2.png[] This is why the output of the `git status` command suggests that you run this to unstage a file. -(See <> for more on this.) +(See <> for more on this.) We could just as easily not let Git assume we meant ``pull the data from HEAD'' by specifying a specific commit to pull that file version from. We would just run something like `git reset eb43bf file.txt`. @@ -241,7 +241,7 @@ Let's look at how to do something interesting with this newfound power – squas Say you have a series of commits with messages like ``oops.'', ``WIP'' and ``forgot this file''. You can use `reset` to quickly and easily squash them into a single commit that makes you look really smart. -(<> shows another way to do this, but in this example it's simpler to use `reset`.) +(<<_squashing>> shows another way to do this, but in this example it's simpler to use `reset`.) Let's say you have a project where the first commit has one file, the second commit added a new file and changed the first, and the third commit changed the first file again. The second commit was a work in progress and you want to squash it down. diff --git a/book/07-git-tools/sections/revision-selection.asc b/book/07-git-tools/sections/revision-selection.asc index f77a7f43..bc6de589 100644 --- a/book/07-git-tools/sections/revision-selection.asc +++ b/book/07-git-tools/sections/revision-selection.asc @@ -1,4 +1,4 @@ -[[r_revision_selection]] +[[_revision_selection]] === Revision Selection Git allows you to specify specific commits or a range of commits in several ways. @@ -85,7 +85,7 @@ If all 6.5 billion humans on Earth were programming, and every second, each one A higher probability exists that every member of your programming team will be attacked and killed by wolves in unrelated incidents on the same night. ==== -[[r_branch_references]] +[[_branch_references]] ==== Branch References The most straightforward way to specify a commit requires that it has a branch reference pointed at it. @@ -109,7 +109,7 @@ $ git rev-parse topic1 ca82a6dff817ec66f44342007202690a93763949 ---- -[[r_git_reflog]] +[[_git_reflog]] ==== RefLog Shortnames One of the things Git does in the background while you’re working away is keep a ``reflog'' – a log of where your HEAD and branch references have been for the last few months. @@ -257,7 +257,7 @@ Date: Fri Nov 7 13:47:59 2008 -0500 You can also combine these syntaxes – you can get the second parent of the previous reference (assuming it was a merge commit) by using `HEAD~3^2`, and so on. -[[r_commit_ranges]] +[[_commit_ranges]] ==== Commit Ranges Now that you can specify individual commits, let’s see how to specify ranges of commits. @@ -331,7 +331,7 @@ $ git log refA refB --not refC This makes for a very powerful revision query system that should help you figure out what is in your branches. -[[r_triple_dot]] +[[_triple_dot]] ===== Triple Dot The last major range-selection syntax is the triple-dot syntax, which specifies all the commits that are reachable by either of two references but not by both of them. diff --git a/book/07-git-tools/sections/rewriting-history.asc b/book/07-git-tools/sections/rewriting-history.asc index e7b287c5..9819e090 100644 --- a/book/07-git-tools/sections/rewriting-history.asc +++ b/book/07-git-tools/sections/rewriting-history.asc @@ -1,4 +1,4 @@ -[[r_rewriting_history]] +[[_rewriting_history]] === Rewriting History Many times, when working with Git, you may want to revise your commit history for some reason. @@ -8,7 +8,7 @@ This can involve changing the order of the commits, changing messages or modifyi In this section, you’ll cover how to accomplish these very useful tasks so that you can make your commit history look the way you want before you share it with others. -[[r_git_amend]] +[[_git_amend]] ==== Changing the Last Commit Changing your last commit is probably the most common rewriting of history that you’ll do. @@ -30,7 +30,7 @@ You stage the changes you want by editing a file and running `git add` on it or You need to be careful with this technique because amending changes the SHA-1 of the commit. It’s like a very small rebase – don’t amend your last commit if you’ve already pushed it. -[[r_changing_multiple]] +[[_changing_multiple]] ==== Changing Multiple Commit Messages To modify a commit that is farther back in your history, you must move to more complex tools. @@ -162,7 +162,7 @@ pick f7f3f6d changed my name a bit When you save and exit the editor, Git rewinds your branch to the parent of these commits, applies `310154e` and then `f7f3f6d`, and then stops. You effectively change the order of those commits and remove the ``added cat-file'' commit completely. -[[r_squashing]] +[[_squashing]] ==== Squashing Commits It’s also possible to take a series of commits and squash them down into a single commit with the interactive rebasing tool. @@ -266,7 +266,7 @@ The command is `filter-branch`, and it can rewrite huge swaths of your history, However, it can be very useful. You’ll learn a few of the common uses so you can get an idea of some of the things it’s capable of. -[[r_removing_file_every_commit]] +[[_removing_file_every_commit]] ===== Removing a File from Every Commit This occurs fairly commonly. diff --git a/book/07-git-tools/sections/searching.asc b/book/07-git-tools/sections/searching.asc index 233b4860..3d728051 100644 --- a/book/07-git-tools/sections/searching.asc +++ b/book/07-git-tools/sections/searching.asc @@ -1,11 +1,11 @@ -[[r_searching]] +[[_searching]] === Searching With just about any size codebase, you'll often need to find where a function is called or defined, or find the history of a method. Git provides a couple of useful tools for looking through the code and commits stored in its database quickly and easily. We'll go through a few of them. -[[r_git_grep]] +[[_git_grep]] ==== Git Grep Git ships with a command called `grep` that allows you to easily search through any committed tree or the working directory for a string or regular expression. diff --git a/book/07-git-tools/sections/signing.asc b/book/07-git-tools/sections/signing.asc index c99fb6f8..faedd85f 100644 --- a/book/07-git-tools/sections/signing.asc +++ b/book/07-git-tools/sections/signing.asc @@ -1,4 +1,4 @@ -[[r_signing]] +[[_signing]] === Signing Your Work Git is cryptographically secure, but it's not foolproof. @@ -109,7 +109,7 @@ gpg: Can't check signature: public key not found error: could not verify the tag 'v1.4.2.1' ---- -[[r_signing_commits]] +[[_signing_commits]] ==== Signing Commits In more recent versions of Git (v1.7.9 and above), you can now also sign individual commits. diff --git a/book/07-git-tools/sections/stashing-cleaning.asc b/book/07-git-tools/sections/stashing-cleaning.asc index 35312b58..8df90b10 100644 --- a/book/07-git-tools/sections/stashing-cleaning.asc +++ b/book/07-git-tools/sections/stashing-cleaning.asc @@ -1,4 +1,4 @@ -[[r_git_stashing]] +[[_git_stashing]] === Stashing and Cleaning Often, when you’ve been working on part of your project, things are in a messy state and you want to switch branches for a bit to work on something else. @@ -213,7 +213,7 @@ Dropped refs/stash@{0} (29d385a81d163dfd45a452a2ce816487a6b8b014) This is a nice shortcut to recover stashed work easily and work on it in a new branch. -[[r_git_clean]] +[[_git_clean]] ==== Cleaning your Working Directory Finally, you may not want to stash some work or files in your working directory, but simply get rid of them. diff --git a/book/07-git-tools/sections/submodules.asc b/book/07-git-tools/sections/submodules.asc index 0cd50398..d54e894e 100644 --- a/book/07-git-tools/sections/submodules.asc +++ b/book/07-git-tools/sections/submodules.asc @@ -1,4 +1,4 @@ -[[r_git_submodules]] +[[_git_submodules]] === Submodules It often happens that while working on one project, you need to use another project from within it. @@ -16,7 +16,7 @@ Git addresses this issue using submodules. Submodules allow you to keep a Git repository as a subdirectory of another Git repository. This lets you clone another repository into your project and keep your commits separate. -[[r_starting_submodules]] +[[_starting_submodules]] ==== Starting with Submodules We'll walk through developing a simple project that has been split up into a main project and a few sub-projects. @@ -133,7 +133,7 @@ Lastly, push these changes: $ git push origin master ---- -[[r_cloning_submodules]] +[[_cloning_submodules]] ==== Cloning a Project with Submodules Here we’ll clone a project with a submodule in it. @@ -481,7 +481,7 @@ Unable to merge 'c75e92a2b3855c9e5b66f915308390d9db204aca' in submodule path 'Db You can go into the submodule directory and fix the conflict just as you normally would. -[[r_publishing_submodules]] +[[_publishing_submodules]] ===== Publishing Submodule Changes Now we have some changes in our submodule directory. @@ -776,7 +776,7 @@ This is obviously a simplified example, but hopefully it gives you an idea of ho ===== Useful Aliases You may want to set up some aliases for some of these commands as they can be quite long and you can't set configuration options for most of them to make them defaults. -We covered setting up Git aliases in <>, but here is an example of what you may want to set up if you plan on working with submodules in Git a lot. +We covered setting up Git aliases in <>, but here is an example of what you may want to set up if you plan on working with submodules in Git a lot. [source,console] ---- diff --git a/book/07-git-tools/sections/subtree-merges.asc b/book/07-git-tools/sections/subtree-merges.asc index 214e824d..d3574bad 100644 --- a/book/07-git-tools/sections/subtree-merges.asc +++ b/book/07-git-tools/sections/subtree-merges.asc @@ -1,4 +1,4 @@ -[[r_subtree_merge]] +[[_subtree_merge]] ===== Subtree Merging The idea of the subtree merge is that you have two projects, and one of the projects maps to a subdirectory of the other one. @@ -82,7 +82,7 @@ Automatic merge went well; stopped before committing as requested All the changes from the Rack project are merged in and ready to be committed locally. You can also do the opposite – make changes in the `rack` subdirectory of your master branch and then merge them into your `rack_branch` branch later to submit them to the maintainers or push them upstream. -This gives us a way to have a workflow somewhat similar to the submodule workflow without using submodules (which we will cover in <>). +This gives us a way to have a workflow somewhat similar to the submodule workflow without using submodules (which we will cover in <<_git_submodules>>). We can keep branches with other related projects in our repository and subtree merge them into our project occasionally. It is nice in some ways, for example all the code is committed to a single place. However, it has other drawbacks in that it's a bit more complex and easier to make mistakes in reintegrating changes or accidentally pushing a branch into an unrelated repository. diff --git a/book/08-customizing-git/sections/attributes.asc b/book/08-customizing-git/sections/attributes.asc index 9accd46b..e8a8abc2 100644 --- a/book/08-customizing-git/sections/attributes.asc +++ b/book/08-customizing-git/sections/attributes.asc @@ -152,7 +152,7 @@ index 88839c4..4afcb7c 100644 You can easily see that the file size and image dimensions have both changed. -[[r_keyword_expansion]] +[[_keyword_expansion]] ==== Keyword Expansion (((keyword expansion))) diff --git a/book/08-customizing-git/sections/config.asc b/book/08-customizing-git/sections/config.asc index 0085c893..43005a86 100644 --- a/book/08-customizing-git/sections/config.asc +++ b/book/08-customizing-git/sections/config.asc @@ -1,8 +1,8 @@ -[[r_git_config]] +[[_git_config]] === Git Configuration (((git commands, config))) -As you briefly saw in <>, you can specify Git configuration settings with the `git config` command. +As you briefly saw in <>, you can specify Git configuration settings with the `git config` command. One of the first things you did was set up your name and email address: [source,console] @@ -123,7 +123,7 @@ If you run that, Git will page the entire output of all commands, no matter how ===== `user.signingkey` (((GPG))) -If you're making signed annotated tags (as discussed in <>), setting your GPG signing key as a configuration setting makes things easier. +If you're making signed annotated tags (as discussed in <>), setting your GPG signing key as a configuration setting makes things easier. Set your key ID like so: [source,console] @@ -141,7 +141,7 @@ $ git tag -s ===== `core.excludesfile` (((excludes)))(((.gitignore))) -You can put patterns in your project's `.gitignore` file to have Git not see them as untracked files or try to stage them when you run `git add` on them, as discussed in <>. +You can put patterns in your project's `.gitignore` file to have Git not see them as untracked files or try to stage them when you run `git add` on them, as discussed in <>. But sometimes you want to ignore certain files for all repositories that you work with. If your computer is running Mac OS X, you're probably familiar with `.DS_Store` files. @@ -230,7 +230,7 @@ $ git config --global color.diff.meta "blue black bold" You can set the color to any of the following values: `normal`, `black`, `red`, `green`, `yellow`, `blue`, `magenta`, `cyan`, or `white`. If you want an attribute like bold in the previous example, you can choose from `bold`, `dim`, `ul` (underline), `blink`, and `reverse` (swap foreground and background). -[[r_external_merge_tools]] +[[_external_merge_tools]] ==== External Merge and Diff Tools (((mergetool)))(((difftool))) @@ -501,4 +501,4 @@ $ git config --system receive.denyDeletes true This denies any deletion of branches or tags – no user can do it. To remove remote branches, you must remove the ref files from the server manually. -There are also more interesting ways to do this on a per-user basis via ACLs, as you'll learn in <>. +There are also more interesting ways to do this on a per-user basis via ACLs, as you'll learn in <<_an_example_git_enforced_policy>>. diff --git a/book/08-customizing-git/sections/hooks.asc b/book/08-customizing-git/sections/hooks.asc index bb1fc30a..ce300105 100644 --- a/book/08-customizing-git/sections/hooks.asc +++ b/book/08-customizing-git/sections/hooks.asc @@ -1,4 +1,4 @@ -[[r_git_hooks]] +[[_git_hooks]] === Git Hooks (((hooks))) @@ -27,7 +27,7 @@ This section splits them into committing-workflow hooks, email-workflow scripts, [NOTE] ==== It's important to note that client-side hooks are *not* copied when you clone a repository. -If your intent with these scripts is to enforce a policy, you'll probably want to do that on the server side; see the example in <>. +If your intent with these scripts is to enforce a policy, you'll probably want to do that on the server side; see the example in <<_an_example_git_enforced_policy>>. ==== ===== Committing-Workflow Hooks @@ -53,7 +53,7 @@ After the entire commit process is completed, the `post-commit` hook runs. It doesn't take any parameters, but you can easily get the last commit by running `git log -1 HEAD`. Generally, this script is used for notification or something similar. -[[r_email_hooks]] +[[_email_hooks]] ===== Email Workflow Hooks You can set up three client-side hooks for an email-based workflow. @@ -74,7 +74,7 @@ The last hook to run during a `git am` operation is `post-applypatch`, which run You can use it to notify a group or the author of the patch you pulled in that you've done so. You can't stop the patching process with this script. -[[r_other_client_hooks]] +[[_other_client_hooks]] ===== Other Client Hooks The `pre-rebase` hook runs before you rebase anything and can halt the process by exiting non-zero. diff --git a/book/08-customizing-git/sections/policy.asc b/book/08-customizing-git/sections/policy.asc index 1ef14b29..d83ba2c2 100644 --- a/book/08-customizing-git/sections/policy.asc +++ b/book/08-customizing-git/sections/policy.asc @@ -1,4 +1,4 @@ -[[r_an_example_git_enforced_policy]] +[[_an_example_git_enforced_policy]] === An Example Git-Enforced Policy (((policy example))) @@ -37,7 +37,7 @@ puts "(#{$refname}) (#{$oldrev[0,6]}) (#{$newrev[0,6]})" Yes, those are global variables. Don't judge – it's easier to demonstrate this way. -[[r_enforcing_commit_message_format]] +[[_enforcing_commit_message_format]] ===== Enforcing a Specific Commit-Message Format Your first challenge is to enforce that each commit message adheres to a particular format. @@ -167,7 +167,7 @@ On the ACL file you looked at earlier, this `get_acl_access_data` method returns Now that you have the permissions sorted out, you need to determine what paths the commits being pushed have modified, so you can make sure the user who's pushing has access to all of them. -You can pretty easily see what files have been modified in a single commit with the `--name-only` option to the `git log` command (mentioned briefly in <>): +You can pretty easily see what files have been modified in a single commit with the `--name-only` option to the `git log` command (mentioned briefly in <>): [source,console] ---- @@ -428,7 +428,7 @@ target_shas.each do |sha| end ---- -This script uses a syntax that wasn't covered in <>. +This script uses a syntax that wasn't covered in <>. You get a list of commits that have already been pushed up by running this: [source,ruby] diff --git a/book/09-git-and-other-scms/sections/client-p4.asc b/book/09-git-and-other-scms/sections/client-p4.asc index 0080e599..8cbb2261 100644 --- a/book/09-git-and-other-scms/sections/client-p4.asc +++ b/book/09-git-and-other-scms/sections/client-p4.asc @@ -11,7 +11,7 @@ There are two options if you'd like to mix your use of Perforce and Git. The first one we'll cover is the ``Git Fusion'' bridge from the makers of Perforce, which lets you expose subtrees of your Perforce depot as read-write Git repositories. The second is git-p4, a client-side bridge that lets you use Git as a Perforce client, without requiring any reconfiguration of the Perforce server. -[[r_p4_git_fusion]] +[[_p4_git_fusion]] ===== Git Fusion (((Perforce, Git Fusion))) @@ -595,7 +595,7 @@ Our history became linear, just as though we had rebased before submitting (whic This means you can be free to create, work on, throw away, and merge branches on the Git side without fear that your history will somehow become incompatible with Perforce. If you can rebase it, you can contribute it to a Perforce server. -[[r_git_p4_branches]] +[[_git_p4_branches]] ====== Branching If your Perforce project has multiple branches, you're not out of luck; git-p4 can handle that in a way that makes it feel like Git. diff --git a/book/09-git-and-other-scms/sections/client-svn.asc b/book/09-git-and-other-scms/sections/client-svn.asc index 5430a8c2..74fcf00f 100644 --- a/book/09-git-and-other-scms/sections/client-svn.asc +++ b/book/09-git-and-other-scms/sections/client-svn.asc @@ -1,4 +1,4 @@ -[[r_git_svn]] +[[_git_svn]] ==== Git and Subversion (((Subversion)))(((Interoperation with other VCSs, Subversion))) diff --git a/book/09-git-and-other-scms/sections/import-custom.asc b/book/09-git-and-other-scms/sections/import-custom.asc index bd3c1bcb..14bc9c00 100644 --- a/book/09-git-and-other-scms/sections/import-custom.asc +++ b/book/09-git-and-other-scms/sections/import-custom.asc @@ -1,4 +1,4 @@ -[[r_custom_importer]] +[[_custom_importer]] ==== A Custom Importer (((git commands, fast-import))) @@ -29,7 +29,7 @@ As you may remember, Git is fundamentally a linked list of commit objects that p All you have to do is tell `fast-import` what the content snapshots are, what commit data points to them, and the order they go in. Your strategy will be to go through the snapshots one at a time and create commits with the contents of each directory, linking each commit back to the previous one. -As we did in <>, we'll write this in Ruby, because it's what we generally work with and it tends to be easy to read. +As we did in <>, we'll write this in Ruby, because it's what we generally work with and it tends to be easy to read. You can write this example pretty easily in anything you're familiar with – it just needs to print the appropriate information to `stdout`. And, if you are running on Windows, this means you'll need to take special care to not introduce carriage returns at the end your lines – `git fast-import` is very particular about just wanting line feeds (LF) not the carriage return line feeds (CRLF) that Windows uses. diff --git a/book/09-git-and-other-scms/sections/import-p4.asc b/book/09-git-and-other-scms/sections/import-p4.asc index 71465851..a8501fba 100644 --- a/book/09-git-and-other-scms/sections/import-p4.asc +++ b/book/09-git-and-other-scms/sections/import-p4.asc @@ -1,4 +1,4 @@ -[[r_perforce_import]] +[[_perforce_import]] ==== Perforce (((Perforce)))(((Importing, from Perforce))) @@ -8,11 +8,11 @@ As we discussed above, there are two ways to let Git and Perforce talk to each o ===== Perforce Git Fusion Git Fusion makes this process fairly painless. -Just configure your project settings, user mappings, and branches using a configuration file (as discussed in <>), and clone the repository. +Just configure your project settings, user mappings, and branches using a configuration file (as discussed in <<_p4_git_fusion>>), and clone the repository. Git Fusion leaves you with what looks like a native Git repository, which is then ready to push to a native Git host if you desire. You could even use Perforce as your Git host if you like. -[[r_git_p4]] +[[_git_p4]] ===== Git-p4 Git-p4 can also act as an import tool. @@ -43,7 +43,7 @@ Importing revision 9957 (100%) ---- This particular project has only one branch, but if you have branches that are configured with branch views (or just a set of directories), you can use the `--detect-branches` flag to `git p4 clone` to import all the project's branches as well. -See <> for a bit more detail on this. +See <<_git_p4_branches>> for a bit more detail on this. At this point you're almost done. If you go to the `p4import` directory and run `git log`, you can see your imported work: diff --git a/book/10-git-internals/sections/environment.asc b/book/10-git-internals/sections/environment.asc index af6ef0e2..fbebd7d2 100644 --- a/book/10-git-internals/sections/environment.asc +++ b/book/10-git-internals/sections/environment.asc @@ -219,7 +219,7 @@ It's probably easier just to use the `~/.ssh/config` file for that. *`GIT_ASKPASS`* is an override for the `core.askpass` configuration value. This is the program invoked whenever Git needs to ask the user for credentials, which can expect a text prompt as a command-line argument, and should return the answer on `stdout`. -(See <> for more on this subsystem.) +(See <> for more on this subsystem.) *`GIT_NAMESPACE`* controls access to namespaced refs, and is equivalent to the `--namespace` flag. This is mostly useful on the server side, where you may want to store multiple forks of a single repository in one repository, only keeping the refs separate. diff --git a/book/10-git-internals/sections/maintenance.asc b/book/10-git-internals/sections/maintenance.asc index 7a01fd0d..fa6080bf 100644 --- a/book/10-git-internals/sections/maintenance.asc +++ b/book/10-git-internals/sections/maintenance.asc @@ -3,7 +3,7 @@ Occasionally, you may have to do some cleanup – make a repository more compact, clean up an imported repository, or recover lost work. This section will cover some of these scenarios. -[[r_git_gc]] +[[_git_gc]] ==== Maintenance Occasionally, Git automatically runs a command called ``auto gc''. @@ -55,7 +55,7 @@ However, if you can't find a reference in the `refs` directory, it's probably in Notice the last line of the file, which begins with a `^`. This means the tag directly above is an annotated tag and that line is the commit that the annotated tag points to. -[[r_data_recovery]] +[[_data_recovery]] ==== Data Recovery At some point in your Git journey, you may accidentally lose a commit. @@ -94,7 +94,7 @@ The trick is finding that latest commit SHA-1 – it's not like you've memorized Often, the quickest way is to use a tool called `git reflog`. As you're working, Git silently records what your HEAD is every time you change it. Each time you commit or change branches, the reflog is updated. -The reflog is also updated by the `git update-ref` command, which is another reason to use it instead of just writing the SHA-1 value to your ref files, as we covered in <>. +The reflog is also updated by the `git update-ref` command, which is another reason to use it instead of just writing the SHA-1 value to your ref files, as we covered in <<_git_refs>>. You can see where you've been at any time by running `git reflog`: [source,console] @@ -171,7 +171,7 @@ dangling blob 7108f7ecb345ee9d0084193f147cdad4d2998293 In this case, you can see your missing commit after the string ``dangling commit''. You can recover it the same way, by adding a branch that points to that SHA-1. -[[r_removing_objects]] +[[_removing_objects]] ==== Removing Objects There are a lot of great things about Git, but one feature that can cause issues is the fact that a `git clone` downloads the entire history of the project, including every version of every file. @@ -262,7 +262,7 @@ dadf7258d699da2c8d89b09ef6670edb7d5f91b4 commit 229 159 12 ---- The big object is at the bottom: 5MB. -To find out what file it is, you'll use the `rev-list` command, which you used briefly in <>. +To find out what file it is, you'll use the `rev-list` command, which you used briefly in <>. If you pass `--objects` to `rev-list`, it lists all the commit SHA-1s and also the blob SHA-1s with the file paths associated with them. You can use this to find your blob's name: @@ -283,7 +283,7 @@ dadf725 oops - removed large tarball ---- You must rewrite all the commits downstream from `7b30847` to fully remove this file from your Git history. -To do so, you use `filter-branch`, which you used in <>: +To do so, you use `filter-branch`, which you used in <>: [source,console] ---- @@ -294,7 +294,7 @@ Rewrite dadf7258d699da2c8d89b09ef6670edb7d5f91b4 (2/2) Ref 'refs/heads/master' was rewritten ---- -The `--index-filter` option is similar to the `--tree-filter` option used in <>, except that instead of passing a command that modifies files checked out on disk, you're modifying your staging area or index each time. +The `--index-filter` option is similar to the `--tree-filter` option used in <>, except that instead of passing a command that modifies files checked out on disk, you're modifying your staging area or index each time. Rather than remove a specific file with something like `rm file`, you have to remove it with `git rm --cached` – you must remove it from the index, not from disk. The reason to do it this way is speed – because Git doesn't have to check out each revision to disk before running your filter, the process can be much, much faster. diff --git a/book/10-git-internals/sections/objects.asc b/book/10-git-internals/sections/objects.asc index 966cd46d..4653520e 100644 --- a/book/10-git-internals/sections/objects.asc +++ b/book/10-git-internals/sections/objects.asc @@ -1,4 +1,4 @@ -[[r_objects]] +[[_objects]] === Objetos do Git O Git é um sistema de arquivos de conteúdo endereçável. @@ -116,7 +116,7 @@ $ git cat-file -t 1f7a7a472abf3dd9643fd615f6da379c4acb3e3a blob ---- -[[r_tree_objects]] +[[_tree_objects]] ==== Objetos Tree O próximo tipo que iremos ver é a _tree_ (árvore), que resolve o problema de armazenar o nome de arquivo e também permite armazenar de forma conjunta um grupo de arquivos. @@ -229,7 +229,7 @@ Você pode pensar nos dados que o Git armazena para essas estruturas como sendo .A estrutura atual do conteúdo dos seus dados no Git. image::images/data-model-2.png[A estrutura atual do conteúdo dos seus dados no Git.] -[[r_git_commit_objects]] +[[_git_commit_objects]] ==== Objetos Commit Agora você tem três _trees_ que especificam os diferentes _snapshots_ do seu projeto que você gostaria de rastrear, mas o problema anterior se mantém: você precisa lembrar dos três valores dos SHA-1 para encontrar os _snapshots_ diff --git a/book/10-git-internals/sections/plumbing-porcelain.asc b/book/10-git-internals/sections/plumbing-porcelain.asc index 91254baf..6b52c0d4 100644 --- a/book/10-git-internals/sections/plumbing-porcelain.asc +++ b/book/10-git-internals/sections/plumbing-porcelain.asc @@ -1,4 +1,4 @@ -[[r_plumbing_porcelain]] +[[_plumbing_porcelain]] === Encanamento e Porcelana Este livro cobre como usar o Git com mais ou menos 30 verbos como `checkout`, `branch`, `remote`, entre outros. @@ -29,7 +29,7 @@ refs/ Talvez você veja outros arquivos nesse diretório, porém esse é um repositório logo após um `git init` - isso é o que você vê por padrão. O arquivo `description` só é usado pelo programa GitWeb, então não se preocupe com ele. O arquivo `config` contem opções de configuração específicas do seu projeto, e o diretório `info` mantém um arquivo `exclude` global (((excludes))) para padrões ignorados que você não gostaria de colocar em um arquivo `.gitignore`. -O diretório `hooks` contém scripts _hooks_ tanto para o lado do cliente quanto do servidor, que são discutidos em detalhes em <>. +O diretório `hooks` contém scripts _hooks_ tanto para o lado do cliente quanto do servidor, que são discutidos em detalhes em <>. Isto nos deixa quatro importantes entradas: o arquivo `HEAD` e o (ainda a ser criado) arquivo `index`, além dos diretórios `objects` e `refs`. Essas são as partes principais do Git. diff --git a/book/10-git-internals/sections/refs.asc b/book/10-git-internals/sections/refs.asc index b1cd034d..3f483de6 100644 --- a/book/10-git-internals/sections/refs.asc +++ b/book/10-git-internals/sections/refs.asc @@ -1,4 +1,4 @@ -[[r_git_refs]] +[[_git_refs]] === Referências do Git Você pode executar algo como `git log 1a410e` para ver todo o seu histórico, mas você ainda precisa lembrar que `1a410e` é o último _commit_ para poder caminhar nesse histórico para encontrar todos esses objetos. @@ -65,7 +65,7 @@ image::images/data-model-4.png[Objetos do diretório Git com todas as referênci Quando você executa comandos como `git branch (nome da branch)`, o Git basicamente executa esse comando `update-ref` para adicionar o SHA-1 do último _commit_ da _branch_ que você está em qualquer nova referência que você quer criar. -[[r_the_head]] +[[ref_the_ref]] ==== A HEAD A questão agora é, quando você executa `git branch (nome da branch)`, como o Git sabe o SHA-1 do último _commit_? @@ -124,7 +124,7 @@ O objeto _tag_ é bem parecido com um objeto _commit_, ele contém um _tagger_, A principal diferença é que um objeto _tag_ geralmente aponta para um _commit_ em vez de uma _tree_. Ele é bem parecido com uma referência do tipo _branch_, mas ele nunca se move - ele sempre aponta para o mesmo _commit_ mas dá a ele um nome mais amigável. -Como discutimos em <>, exitem dois tipos de _tags_: anotada e leve. +Como discutimos em <>, exitem dois tipos de _tags_: anotada e leve. Você pode criar uma _tag_ leve executando algo assim: [source,console] diff --git a/book/10-git-internals/sections/refspec.asc b/book/10-git-internals/sections/refspec.asc index a1fde893..ac66550e 100644 --- a/book/10-git-internals/sections/refspec.asc +++ b/book/10-git-internals/sections/refspec.asc @@ -1,4 +1,4 @@ -[[r_refspec]] +[[_refspec]] === The Refspec Throughout this book, we've used simple mappings from remote branches to local references, but they can be more complex. @@ -95,7 +95,7 @@ If you have a QA team that pushes a series of branches, and you want to get the If you have a complex workflow process that has a QA team pushing branches, developers pushing branches, and integration teams pushing and collaborating on remote branches, you can namespace them easily this way. -[[r_pushing_refspecs]] +[[_pushing_refspecs]] ==== Pushing Refspecs It's nice that you can fetch namespaced references that way, but how does the QA team get their branches into a `qa/` namespace in the first place? diff --git a/book/A-git-in-other-environments/sections/guis.asc b/book/A-git-in-other-environments/sections/guis.asc index 45caba38..b1e403ab 100644 --- a/book/A-git-in-other-environments/sections/guis.asc +++ b/book/A-git-in-other-environments/sections/guis.asc @@ -112,7 +112,7 @@ If you already have a local repository, just drag its directory from the Finder Once it's installed and configured, you can use the GitHub client for many common Git tasks. The intended workflow for this tool is sometimes called the ``GitHub Flow.'' -We cover this in more detail in <>, but the general gist is that (a) you'll be committing to a branch, and (b) you'll be syncing up with a remote repository fairly regularly. +We cover this in more detail in <>, but the general gist is that (a) you'll be committing to a branch, and (b) you'll be syncing up with a remote repository fairly regularly. Branch management is one of the areas where the two tools diverge. On Mac, there's a button at the top of the window for creating a new branch: diff --git a/book/A-git-in-other-environments/sections/powershell.asc b/book/A-git-in-other-environments/sections/powershell.asc index c93a1fd2..64ca0af7 100644 --- a/book/A-git-in-other-environments/sections/powershell.asc +++ b/book/A-git-in-other-environments/sections/powershell.asc @@ -1,4 +1,4 @@ -[[r_git_powershell]] +[[_git_powershell]] === Git in Powershell (((powershell)))(((tab completion, powershell)))(((shell prompts, powershell))) diff --git a/book/B-embedding-git/sections/dulwich.asc b/book/B-embedding-git/sections/dulwich.asc new file mode 100644 index 00000000..62cab950 --- /dev/null +++ b/book/B-embedding-git/sections/dulwich.asc @@ -0,0 +1,42 @@ +=== Dulwich + +(((Dulwich)))(((Python))) +There is also a pure-Python Git implementation - Dulwich. +The project is hosted under https://www.dulwich.io/[^]. +It aims to provide an interface to Git repositories (both local and remote) that doesn't call out to Git directly but instead uses pure Python. +It has an optional C extensions though, that significantly improve the performance. + +Dulwich follows Git design and separate two basic levels of API: plumbing and porcelain. + +Here is an example of using the lower level API to access the commit message of the last commit: + +[source, python] +---- +from dulwich.repo import Repo +r = Repo('.') +r.head() +# '57fbe010446356833a6ad1600059d80b1e731e15' + +c = r[r.head()] +c +# + +c.message +# 'Add note about encoding.\n' +---- + +To print a commit log using high-level porcelain API, one can use: + +[source, python] +---- +from dulwich import porcelain +porcelain.log('.', max_entries=1) + +#commit: 57fbe010446356833a6ad1600059d80b1e731e15 +#Author: Jelmer Vernooij +#Date: Sat Apr 29 2017 23:57:34 +0000 +---- + +==== Further Reading + +The API documentation, tutorial, and many examples of how to do specific tasks with Dulwich are available on the official website https://www.dulwich.io[^]. diff --git a/book/B-embedding-git/sections/go-git.asc b/book/B-embedding-git/sections/go-git.asc new file mode 100644 index 00000000..a477cf1b --- /dev/null +++ b/book/B-embedding-git/sections/go-git.asc @@ -0,0 +1,83 @@ +=== go-git + +(((go-git)))(((Go))) +In case you want to integrate Git into a service written in Golang, there also is a pure Go library implementation. +This implementation does not have any native dependencies and thus is not prone to manual memory management errors. +It is also transparent for the standard Golang performance analysis tooling like CPU, Memory profilers, race detector, etc. + +go-git is focused on extensibility, compatibility and supports most of the plumbing APIs, which is documented at https://github.com/go-git/go-git/blob/master/COMPATIBILITY.md[^]. + +Here is a basic example of using Go APIs: + +[source, go] +---- +import "github.com/go-git/go-git/v5" + +r, err := git.PlainClone("/tmp/foo", false, &git.CloneOptions{ + URL: "https://github.com/go-git/go-git", + Progress: os.Stdout, +}) +---- + +As soon as you have a `Repository` instance, you can access information and perform mutations on it: + +[source, go] +---- +// retrieves the branch pointed by HEAD +ref, err := r.Head() + +// get the commit object, pointed by ref +commit, err := r.CommitObject(ref.Hash()) + +// retrieves the commit history +history, err := commit.History() + +// iterates over the commits and print each +for _, c := range history { + fmt.Println(c) +} +---- + +==== Advanced Functionality + +go-git has few notable advanced features, one of which is a pluggable storage system, which is similar to Libgit2 backends. +The default implementation is in-memory storage, which is very fast. + +[source, go] +---- +r, err := git.Clone(memory.NewStorage(), nil, &git.CloneOptions{ + URL: "https://github.com/go-git/go-git", +}) +---- + +Pluggable storage provides many interesting options. +For instance, https://github.com/go-git/go-git/tree/master/_examples/storage[^] allows you to store references, objects, and configuration in an Aerospike database. + +Another feature is a flexible filesystem abstraction. +Using https://pkg.go.dev/github.com/go-git/go-billy/v5?tab=doc#Filesystem[^] it is easy to store all the files in different way i.e by packing all of them to a single archive on disk or by keeping them all in-memory. + +Another advanced use-case includes a fine-tunable HTTP client, such as the one found at https://github.com/go-git/go-git/blob/master/_examples/custom_http/main.go[^]. + +[source, go] +---- +customClient := &http.Client{ + Transport: &http.Transport{ // accept any certificate (might be useful for testing) + TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, + }, + Timeout: 15 * time.Second, // 15 second timeout + CheckRedirect: func(req *http.Request, via []*http.Request) error { + return http.ErrUseLastResponse // don't follow redirect + }, +} + +// Override http(s) default protocol to use our custom client +client.InstallProtocol("https", githttp.NewClient(customClient)) + +// Clone repository using the new client if the protocol is https:// +r, err := git.Clone(memory.NewStorage(), nil, &git.CloneOptions{URL: url}) +---- + +==== Further Reading + +A full treatment of go-git's capabilities is outside the scope of this book. +If you want more information on go-git, there's API documentation at https://pkg.go.dev/github.com/go-git/go-git/v5[^], and a set of usage examples at https://github.com/go-git/go-git/tree/master/_examples[^]. diff --git a/book/B-embedding-git/sections/jgit.asc b/book/B-embedding-git/sections/jgit.asc index 72d5e712..bae93ac3 100644 --- a/book/B-embedding-git/sections/jgit.asc +++ b/book/B-embedding-git/sections/jgit.asc @@ -3,7 +3,7 @@ (((jgit)))(((java))) If you want to use Git from within a Java program, there is a fully featured Git library called JGit. JGit is a relatively full-featured implementation of Git written natively in Java, and is widely used in the Java community. -The JGit project is under the Eclipse umbrella, and its home can be found at http://www.eclipse.org/jgit[]. +The JGit project is under the Eclipse umbrella, and its home can be found at https://www.eclipse.org/jgit/[^]. ==== Getting Set Up @@ -19,10 +19,10 @@ Probably the easiest is to use Maven – the integration is accomplished by addi ---- -The `version` will most likely have advanced by the time you read this; check http://mvnrepository.com/artifact/org.eclipse.jgit/org.eclipse.jgit[] for updated repository information. +The `version` will most likely have advanced by the time you read this; check https://mvnrepository.com/artifact/org.eclipse.jgit/org.eclipse.jgit[^] for updated repository information. Once this step is done, Maven will automatically acquire and use the JGit libraries that you'll need. -If you would rather manage the binary dependencies yourself, pre-built JGit binaries are available from http://www.eclipse.org/jgit/download[]. +If you would rather manage the binary dependencies yourself, pre-built JGit binaries are available from https://www.eclipse.org/jgit/download[^]. You can build them into your project by running a command like this: [source,console] @@ -97,7 +97,7 @@ Ref objects are also used to represent tag refs and objects, so you can ask if t The second line gets the target of the `master` reference, which is returned as an ObjectId instance. ObjectId represents the SHA-1 hash of an object, which might or might not exist in Git's object database. -The third line is similar, but shows how JGit handles the rev-parse syntax (for more on this, see <>); you can pass any object specifier that Git understands, and JGit will return either a valid ObjectId for that object, or `null`. +The third line is similar, but shows how JGit handles the rev-parse syntax (for more on this, see <>); you can pass any object specifier that Git understands, and JGit will return either a valid ObjectId for that object, or `null`. The next two lines show how to load the raw contents of an object. In this example, we call `ObjectLoader.copyTo()` to stream the contents of the object directly to stdout, but ObjectLoader also has methods to read the type and size of an object, as well as return it as a byte array. @@ -155,6 +155,6 @@ Many other commands are available through the Git class, including but not limit This is only a small sampling of JGit's full capabilities. If you're interested and want to learn more, here's where to look for information and inspiration: -* The official JGit API documentation can be found at https://www.eclipse.org/jgit/documentation[]. +* The official JGit API documentation can be found at https://www.eclipse.org/jgit/documentation[^]. These are standard Javadoc, so your favorite JVM IDE will be able to install them locally, as well. -* The JGit Cookbook at https://github.com/centic9/jgit-cookbook[] has many examples of how to do specific tasks with JGit. +* The JGit Cookbook at https://github.com/centic9/jgit-cookbook[^] has many examples of how to do specific tasks with JGit. diff --git a/book/B-embedding-git/sections/libgit2.asc b/book/B-embedding-git/sections/libgit2.asc index 9f6bfc3b..530d6633 100644 --- a/book/B-embedding-git/sections/libgit2.asc +++ b/book/B-embedding-git/sections/libgit2.asc @@ -3,7 +3,7 @@ (((libgit2)))((("C"))) Another option at your disposal is to use Libgit2. Libgit2 is a dependency-free implementation of Git, with a focus on having a nice API for use within other programs. -You can find it at http://libgit2.github.com[]. +You can find it at https://libgit2.org[^]. First, let's take a look at what the C API looks like. Here's a whirlwind tour: @@ -35,7 +35,7 @@ The `git_repository` type represents a handle to a repository with a cache in me This is the simplest method, for when you know the exact path to a repository's working directory or `.git` folder. There's also the `git_repository_open_ext` which includes options for searching, `git_clone` and friends for making a local clone of a remote repository, and `git_repository_init` for creating an entirely new repository. -The second chunk of code uses rev-parse syntax (see <> for more on this) to get the commit that HEAD eventually points to. +The second chunk of code uses rev-parse syntax (see <> for more on this) to get the commit that HEAD eventually points to. The type returned is a `git_object` pointer, which represents something that exists in the Git object database for a repository. `git_object` is actually a ``parent'' type for several different kinds of objects; the memory layout for each of the ``child'' types is the same as for `git_object`, so you can safely cast to the right one. In this case, `git_object_type(commit)` would return `GIT_OBJ_COMMIT`, so it's safe to cast to a `git_commit` pointer. @@ -54,7 +54,7 @@ From this sample, a couple of patterns have started to emerge: (((Ruby))) That last one means it isn't very probable that you'll be writing C when using Libgit2. Fortunately, there are a number of language-specific bindings available that make it fairly easy to work with Git repositories from your specific language and environment. -Let's take a look at the above example written using the Ruby bindings for Libgit2, which are named Rugged, and can be found at https://github.com/libgit2/rugged[]. +Let's take a look at the above example written using the Ruby bindings for Libgit2, which are named Rugged, and can be found at https://github.com/libgit2/rugged[^]. [source,ruby] ---- @@ -106,8 +106,7 @@ commit = repo.lookup(commit_id) # <8> <8> The return value is the SHA-1 hash of a new commit object, which you can then use to get a `Commit` object. The Ruby code is nice and clean, but since Libgit2 is doing the heavy lifting, this code will run pretty fast, too. -If you're not a rubyist, we touch on some other bindings in <>. - +If you're not a rubyist, we touch on some other bindings in <<_libgit2_bindings>>. ==== Advanced Functionality @@ -116,7 +115,7 @@ One example is pluggability: Libgit2 allows you to provide custom ``backends'' f Libgit2 allows custom backends for configuration, ref storage, and the object database, among other things. Let's take a look at how this works. -The code below is borrowed from the set of backend examples provided by the Libgit2 team (which can be found at https://github.com/libgit2/libgit2-backends[]). +The code below is borrowed from the set of backend examples provided by the Libgit2 team (which can be found at https://github.com/libgit2/libgit2-backends[^]). Here's how a custom backend for the object database is set up: [source,c] @@ -179,19 +178,19 @@ The rest of it is arbitrary; this structure can be as large or small as you need The initialization function allocates some memory for the structure, sets up the custom context, and then fills in the members of the `parent` structure that it supports. Take a look at the `include/git2/sys/odb_backend.h` file in the Libgit2 source for a complete set of call signatures; your particular use case will help determine which of these you'll want to support. -[[r_libgit2_bindings]] +[[_libgit2_bindings]] ==== Other Bindings Libgit2 has bindings for many languages. Here we show a small example using a few of the more complete bindings packages as of this writing; libraries exist for many other languages, including C++, Go, Node.js, Erlang, and the JVM, all in various stages of maturity. -The official collection of bindings can be found by browsing the repositories at https://github.com/libgit2[]. +The official collection of bindings can be found by browsing the repositories at https://github.com/libgit2[^]. The code we'll write will return the commit message from the commit eventually pointed to by HEAD (sort of like `git log -1`). ===== LibGit2Sharp (((.NET)))(((C#)))(((Mono))) -If you're writing a .NET or Mono application, LibGit2Sharp (https://github.com/libgit2/libgit2sharp[]) is what you're looking for. +If you're writing a .NET or Mono application, LibGit2Sharp (https://github.com/libgit2/libgit2sharp[^]) is what you're looking for. The bindings are written in C#, and great care has been taken to wrap the raw Libgit2 calls with native-feeling CLR APIs. Here's what our example program looks like: @@ -206,7 +205,7 @@ For desktop Windows applications, there's even a NuGet package that will help yo (((Apple)))(((Objective-C)))(((Cocoa))) If your application is running on an Apple platform, you're likely using Objective-C as your implementation language. -Objective-Git (https://github.com/libgit2/objective-git[]) is the name of the Libgit2 bindings for that environment. +Objective-Git (https://github.com/libgit2/objective-git[^]) is the name of the Libgit2 bindings for that environment. The example program looks like this: [source,objc] @@ -222,7 +221,7 @@ Objective-git is fully interoperable with Swift, so don't fear if you've left Ob ===== pygit2 (((Python))) -The bindings for Libgit2 in Python are called Pygit2, and can be found at http://www.pygit2.org/[]. +The bindings for Libgit2 in Python are called Pygit2, and can be found at https://www.pygit2.org[^]. Our example program: [source,python] @@ -237,5 +236,5 @@ pygit2.Repository("/path/to/repo") # open repository ==== Further Reading Of course, a full treatment of Libgit2's capabilities is outside the scope of this book. -If you want more information on Libgit2 itself, there's API documentation at https://libgit2.github.com/libgit2[], and a set of guides at https://libgit2.github.com/docs[]. +If you want more information on Libgit2 itself, there's API documentation at https://libgit2.github.com/libgit2[^], and a set of guides at https://libgit2.github.com/docs[^]. For the other bindings, check the bundled README and tests; there are often small tutorials and pointers to further reading there. diff --git a/ch01-introduction.asc b/ch01-getting-started.asc similarity index 92% rename from ch01-introduction.asc rename to ch01-getting-started.asc index 0d48076e..3195a5c7 100644 --- a/ch01-introduction.asc +++ b/ch01-getting-started.asc @@ -1,5 +1,4 @@ -[#ch01-introduction] -[[r_getting_started]] +[[ch01-getting-started]] == Começando Este capítulo abordará como começar com o Git. @@ -10,7 +9,7 @@ include::book/01-introduction/sections/about-version-control.asc[] include::book/01-introduction/sections/history.asc[] -include::book/01-introduction/sections/basics.asc[] +include::book/01-introduction/sections/what-is-git.asc[] include::book/01-introduction/sections/command-line.asc[] diff --git a/ch02-git-basics.asc b/ch02-git-basics-chapter.asc similarity index 97% rename from ch02-git-basics.asc rename to ch02-git-basics-chapter.asc index bad46700..6a90787d 100644 --- a/ch02-git-basics.asc +++ b/ch02-git-basics-chapter.asc @@ -1,5 +1,4 @@ -[#ch02-git-basics] -[[r_git_basics_chapter]] +[[ch02-git-basics-chapter]] == Fundamentos de Git Se você pode ler apenas um capítulo antes de começar a usar o Git, este é ele. diff --git a/ch03-git-branching.asc b/ch03-git-branching.asc index 9157528c..02ffb70f 100644 --- a/ch03-git-branching.asc +++ b/ch03-git-branching.asc @@ -1,5 +1,4 @@ -[#ch03-git-branching] -[[r_git_branching]] +[[ch03-git-branching]] == Branches no Git (((branches))) @@ -30,4 +29,4 @@ include::book/03-git-branching/sections/rebasing.asc[] Nós iremos mostrar as funções de Branches e Merges básicas no Git. Sinta-se confortável para criar e alternar para novos branches, alternar entre branches e mesclar branches locais. Você também deve ser capaz de compartilhar seus branches enviando-os (push) para um servidor compartilhado, trabalhando com outras pessoas em branches compartilhados e rebaseando (rebase) seus branches antes de serem compartilhados. -A seguir, vamos apresentar o que você precisa para executar seu próprio servidor para hospedagem do repositório Git. \ No newline at end of file +A seguir, vamos apresentar o que você precisa para executar seu próprio servidor para hospedagem do repositório Git. diff --git a/ch04-git-server.asc b/ch04-git-on-the-server.asc similarity index 99% rename from ch04-git-server.asc rename to ch04-git-on-the-server.asc index 1a7a2767..4f80ce3a 100644 --- a/ch04-git-server.asc +++ b/ch04-git-on-the-server.asc @@ -1,4 +1,4 @@ -[#ch04-git-server] +[[ch04-git-on-the-server]] == Git no servidor (((serving repositories))) @@ -36,4 +36,4 @@ Você tem várias opções para ter um repositório remoto Git executando para q Executar seu próprio servidor te proporcional muito controle e permite que você execute seu servidor por seu próprio firewall, mas é esse tipo de servidor geralmente requer bastante de seu tempo para configuração e manutenção. Se você colocou seus dados em um servidor hospedado é fácil configurar e manter, contudo, você tem que manter seu código no servidor de terceiros, mas algumas organizações não permitem isso. -Isso deve ser o bastante para determinar qual solução ou combinação de soluções é apropriada para você e seus colaboradores. \ No newline at end of file +Isso deve ser o bastante para determinar qual solução ou combinação de soluções é apropriada para você e seus colaboradores. diff --git a/ch05-distributed-git.asc b/ch05-distributed-git.asc index 8142a324..588a2174 100644 --- a/ch05-distributed-git.asc +++ b/ch05-distributed-git.asc @@ -1,9 +1,8 @@ -[#ch05-distributed-git] -[[r_distributed_git]] +[[ch05-distributed-git]] == Distributed Git (((distributed git))) -Now that you have a remote Git repository set up as a point for all the developers to share their code, and you're familiar with basic Git commands in a local workflow, you'll look at how to utilize some of the distributed workflows that Git affords you. +Now that you have a remote Git repository set up as a focal point for all the developers to share their code, and you're familiar with basic Git commands in a local workflow, you'll look at how to utilize some of the distributed workflows that Git affords you. In this chapter, you'll see how to work with Git in a distributed environment as a contributor and an integrator. That is, you'll learn how to contribute code successfully to a project and make it as easy on you and the project maintainer as possible, and also how to maintain a project successfully with a number of developers contributing. diff --git a/ch06-github.asc b/ch06-github.asc index 1c8260f4..e2cd29e7 100644 --- a/ch06-github.asc +++ b/ch06-github.asc @@ -1,5 +1,4 @@ -[#ch06-github] -[[r_github]] +[[ch06-github]] == GitHub (((GitHub))) diff --git a/ch07-git-tools.asc b/ch07-git-tools.asc index 363757ad..0e7fad55 100644 --- a/ch07-git-tools.asc +++ b/ch07-git-tools.asc @@ -1,11 +1,10 @@ -[#ch07-git-tools] -[[r_git_tools]] +[[ch07-git-tools]] == Git Tools -By now, you’ve learned most of the day-to-day commands and workflows that you need to manage or maintain a Git repository for your source code control. -You’ve accomplished the basic tasks of tracking and committing files, and you’ve harnessed the power of the staging area and lightweight topic branching and merging. +By now, you've learned most of the day-to-day commands and workflows that you need to manage or maintain a Git repository for your source code control. +You've accomplished the basic tasks of tracking and committing files, and you've harnessed the power of the staging area and lightweight topic branching and merging. -Now you’ll explore a number of very powerful things that Git can do that you may not necessarily use on a day-to-day basis but that you may need at some point. +Now you'll explore a number of very powerful things that Git can do that you may not necessarily use on a day-to-day basis but that you may need at some point. include::book/07-git-tools/sections/revision-selection.asc[] @@ -37,7 +36,7 @@ include::book/07-git-tools/sections/credentials.asc[] === Summary -You’ve seen a number of advanced tools that allow you to manipulate your commits and staging area more precisely. +You've seen a number of advanced tools that allow you to manipulate your commits and staging area more precisely. When you notice issues, you should be able to easily figure out what commit introduced them, when, and by whom. -If you want to use subprojects in your project, you’ve learned how to accommodate those needs. -At this point, you should be able to do most of the things in Git that you’ll need on the command line day to day and feel comfortable doing so. +If you want to use subprojects in your project, you've learned how to accommodate those needs. +At this point, you should be able to do most of the things in Git that you'll need on the command line day to day and feel comfortable doing so. diff --git a/ch08-customizing-git.asc b/ch08-customizing-git.asc index ed6d6efe..2af938c0 100644 --- a/ch08-customizing-git.asc +++ b/ch08-customizing-git.asc @@ -1,5 +1,4 @@ -[#ch08-customizing-git] -[[r_customizing_git]] +[[ch08-customizing-git]] == Customizing Git So far, we've covered the basics of how Git works and how to use it, and we've introduced a number of tools that Git provides to help you use it easily and efficiently. diff --git a/ch09-git-and-other-scms.asc b/ch09-git-and-other-systems.asc similarity index 95% rename from ch09-git-and-other-scms.asc rename to ch09-git-and-other-systems.asc index 193f5091..ac6a1589 100644 --- a/ch09-git-and-other-scms.asc +++ b/ch09-git-and-other-systems.asc @@ -1,4 +1,4 @@ -[#ch09-git-and-other-scms] +[[ch09-git-and-other-systems]] == Git and Other Systems The world isn't perfect. @@ -13,7 +13,7 @@ The second part of this chapter covers how to migrate your project into Git from (((Git as a client))) Git provides such a nice experience for developers that many people have figured out how to use it on their workstation, even if the rest of their team is using an entirely different VCS. -There are a number of these adapters, called ``bridges,'' available. +There are a number of these adapters, called "`bridges,`" available. Here we'll cover the ones you're most likely to run into in the wild. include::book/09-git-and-other-scms/sections/client-svn.asc[] @@ -24,7 +24,7 @@ include::book/09-git-and-other-scms/sections/client-bzr.asc[] include::book/09-git-and-other-scms/sections/client-p4.asc[] -[[r_migrating]] +[[_migrating]] === Migrating to Git (((Migrating to Git))) diff --git a/ch10-git-internals.asc b/ch10-git-internals.asc index 0376eaae..eeed944e 100644 --- a/ch10-git-internals.asc +++ b/ch10-git-internals.asc @@ -1,5 +1,4 @@ -[#ch10-git-internals] -[[r_git_internals]] +[[ch10-git-internals]] == Funcionamento Interno do Git Talvez você venha de um capítulo anterior para este, ou talvez você tenha chegado aqui depois de ler o resto do livro. De qualquer forma, aqui iremos para o funcionamento e implementação internos do Git. diff --git a/index.asc b/index.asc index 2df4a6b1..9618359a 100644 --- a/index.asc +++ b/index.asc @@ -1,3 +1,3 @@ [#index] [index] -= Index +== Index diff --git a/progit.asc b/progit.asc index c01a9c58..3707ce84 100644 --- a/progit.asc +++ b/progit.asc @@ -1,16 +1,12 @@ -Pro Git -======= -Scott Chacon, Ben Straub -$$VERSION$$, $$DATE$$ += Pro Git +Scott Chacon; Ben Straub :doctype: book :docinfo: :toc: :toclevels: 2 :pagenums: :front-cover-image: image:book/cover.png[width=1050,height=1600] -:lang: ko - -ifdef::ebook-format[:leveloffset: -1] +:icons: font include::book/license.asc[] @@ -20,17 +16,17 @@ include::book/preface_ben.asc[] include::book/dedication.asc[] -//include::book/contributors.asc[] +include::book/contributors.asc[] include::book/introduction.asc[] -include::ch01-introduction.asc[] +include::ch01-getting-started.asc[] -include::ch02-git-basics.asc[] +include::ch02-git-basics-chapter.asc[] include::ch03-git-branching.asc[] -include::ch04-git-server.asc[] +include::ch04-git-on-the-server.asc[] include::ch05-distributed-git.asc[] @@ -40,16 +36,16 @@ include::ch07-git-tools.asc[] include::ch08-customizing-git.asc[] -include::ch09-git-and-other-scms.asc[] +include::ch09-git-and-other-systems.asc[] include::ch10-git-internals.asc[] include::A-git-in-other-environments.asc[] -include::B-embedding-git.asc[] +include::B-embedding-git-in-your-applications.asc[] include::C-git-commands.asc[] -ifndef::ebook-format[include::index.asc[]] +ifdef::backend-pdf[include::index.asc[]] include::TRANSLATION_NOTES.asc[]