「Git」の版間の差分

提供: ArchWiki
ナビゲーションに移動 検索に移動
(en:Gitへの転送ページ)
 
1行目: 1行目:
  +
[[Category:バージョン管理システム]]
#redirect[[en:Git]]
 
  +
[[en:Git]]
  +
[[zh-CN:Git]]
  +
{{Related articles start}}
  +
{{Related4|Super Quick Git Guide}}
  +
{{Related4|Gitweb}}
  +
{{Related4|Cgit}}
  +
{{Related3|HTTP tunneling#Tunneling Git|HTTP トンネリング#Git のトンネリング}}
  +
{{Related|Subversion}}
  +
{{Related4|Concurrent Versions System}}
  +
{{Related articles end}}
  +
  +
[[wikipedia:ja:Git|Git]] は Linux カーネルの創設者である Linus Torvalds によって設計・開発されたバージョン管理システム (VCS) です。現在 Git は Linux カーネルのソースの管理だけでなく、様々な他のプロジェクトにも使われており、Arch Linux プロジェクトもそれに含まれます。
  +
  +
== インストール ==
  +
  +
{{Pkg|git}} パッケージを[[インストール]]してください。
  +
  +
Git の補助ツールを使いたい場合は、必要に応じて任意の依存パッケージもインストールしてください。GUI ツール (例: ''gitk'' や ''git gui'') は {{Pkg|tk}} パッケージを必要とし、インストールしていない場合エラーで起動できません:
  +
  +
/usr/bin/gitk: line 3: exec: wish: not found.
  +
  +
また、GUI ツールは {{pkg|gsfonts}} を必要とし、インストールしていない場合セグメンテーション違反でクラッシュします。
  +
  +
Git SVN ブリッジ (''git svn'') を使いたい場合は {{pkg|perl-term-readkey}} も必要です。インストールしていない場合、次のエラーが表示されます:
  +
  +
Can't locate Term/ReadKey.pm in @INC (you may need to install the Term::ReadKey module)
  +
  +
== 基本設定 ==
  +
  +
Git を使うには少なくとも名前とメールアドレスを設定する必要があります:
  +
  +
$ git config --global user.name "''John Doe''"
  +
$ git config --global user.email "''johndoe@foobar.com''"
  +
  +
他の設定については [[#高度な設定]] を見て下さい。
  +
  +
== 基本的な使い方 ==
  +
  +
このチュートリアルでは Git によるプロジェクトの基本的な分散バージョン管理について説明します。典型的な Git のワークフローは以下の通りです:
  +
  +
# 新しいプロジェクトを作成、またはリモートのプロジェクトを複製する。
  +
# ブランチを作成して変更を加え、変更をコミットする。
  +
# コミットを統合して上手くまとめて分かりやすくする。
  +
# メインのブランチにコミットをマージする。
  +
# (任意) 変更をリモートサーバーにプッシュする。
  +
  +
=== ローカルリポジトリ ===
  +
  +
==== 準備 ====
  +
  +
'''Initialize''' a new repository:
  +
  +
$ git init
  +
  +
To record the changes to the repository, they must first be added to the ''index'', or ''staging area'', with an operation often also referred to as ''staging''. To '''add files''':
  +
  +
$ git add ''file1'' ''file2''
  +
  +
'''Add all''' files:
  +
  +
$ git add .
  +
  +
{{Tip|To '''ignore''' some files from, e.g. {{ic|git add .}}, create a {{ic|.gitignore}} file (or files):
  +
  +
{{hc|.gitignore|
  +
# File I'll likely delete
  +
test-script
  +
  +
# Ignore all .html files, except 'important.html'
  +
*.html
  +
!important.html
  +
  +
# Ignore all files recursively in 'DoNotInclude'
  +
DoNotInclude/**
  +
}}
  +
  +
See [http://git-scm.com/docs/gitignore gitignore(5)] for details.
  +
}}
  +
  +
'''Remove''' a file from staging ({{ic|--cached}} preserves the actual file(s)):
  +
  +
$ git rm ''(--cached)'' ''file''
  +
  +
'''Remove all''' files:
  +
  +
$ git reset HEAD -- .
  +
  +
Or:
  +
  +
$ git rm --cached -r .
  +
  +
'''Rename''' a file:
  +
  +
$ git mv ''file1'' ''file2''
  +
  +
'''List''' files:
  +
  +
$ git ls-files
  +
  +
==== 変更をコミット ====
  +
  +
Once the content to be recorded is ''staged'', '''commit''' them with:
  +
  +
$ git commit -m "''First commit.''"
  +
  +
The {{ic|-m}}, {{ic|--message}} option is for a short message: if omitted, the preset editor will be spawned to allow entering a longer message.
  +
  +
{{Tip|
  +
* Always commit small changes frequently and with meaningful messages.
  +
* To '''add''' all the modified files to the index, '''and commit''' them in a single command ({{ic|-a}} stands for {{ic|--all}}):
  +
  +
$ git commit -am "''First commit.''"
  +
}}
  +
  +
Go back and '''edit''' the commit message:
  +
  +
$ git commit --amend -m "''Message.''"
  +
  +
Many of the commands in this article take commits as arguments. A commit can be identified by any of the following:
  +
  +
* Its 40-digit SHA-1 hash (the first 7 digits are usually sufficient to identify it uniquely)
  +
* Any commit label such as a branch or tag name
  +
* The label {{ic|HEAD}} always refers to the currently checked-out commit (usually the head of the branch, unless you used {{ic|git checkout}} to jump back in history to an old commit)
  +
* Any of the above plus {{ic|~}} to refer to previous commits. For example, {{ic|HEAD~}} refers to one commit before {{ic|HEAD}} and {{ic|HEAD~5}} refers to five commits before {{ic|HEAD}}.
  +
  +
==== 変更を閲覧 ====
  +
  +
'''Show differences''' between commits:
  +
  +
$ git diff
  +
  +
'''Get''' a general '''overview''' of the changes:
  +
  +
$ git status
  +
  +
'''View history''' of changes (where "''-N''" is the number of latest commits):
  +
  +
$ git log ''(-N)''
  +
  +
==== ブランチの作成 ====
  +
  +
Fixes and new features are usually tested in branches. When changes are satisfactory they can merged back into the default (master) branch. '''Create''' a branch, whose name accurately reflects its purpose:
  +
  +
$ git branch ''help-section-addition''
  +
  +
'''List''' branches:
  +
  +
$ git branch
  +
  +
'''Switch''' branches:
  +
  +
$ git checkout ''branch''
  +
  +
'''Create and switch''':
  +
  +
$ git checkout -b ''branch''
  +
  +
'''Merge''' a branch back to the master branch:
  +
  +
$ git checkout master
  +
$ git merge ''branch''
  +
  +
The changes will be merged if they do not conflict. If they do, the conflicts will be recorded. What is causing the conflicts can been seen with {{ic|git diff}}, then conflict resolution will need to be done manually.
  +
  +
When done with a branch, '''delete''' it with:
  +
  +
$ git branch -d ''branch''
  +
  +
=== 共同作業 ===
  +
  +
==== Adopting a good etiquette ====
  +
  +
* When considering contributing to an existing project, read and understand its license, as it may excessively limit your ability to change the code. Some licenses can generate disputes over the ownership of the code.
  +
* Think about the project's community and how well you can fit into it. To get a feeling of the direction of the project, read any documentation and even the [[#History and versioning|log]] of the repository.
  +
* When requesting to pull a commit, or submit a patch, keep it small and well documented; this will help the maintainers understand your changes and decide whether to merge them or ask you to make some amendments.
  +
* If a contribution is rejected, do not get discouraged, it is their project after all. If it is important, discuss the reasoning for the contribution as clearly and as patiently as possible: with such an approach a resolution may eventually be possible.
  +
  +
==== リポジトリを複製 ====
  +
  +
To begin contributing to a project, '''clone''' its repository:
  +
  +
$ git clone ''location'' ''folder''
  +
  +
{{ic|''location''}} can be either a path or network address. Also, when cloning is done, the location is recorded so just a {{ic|git pull}} will be needed later.
  +
  +
==== プルリクエスト ====
  +
  +
After making and committing some changes, the contributor can ask the original author to merge them. This is called a ''pull request''. To '''pull''':
  +
  +
$ git pull ''location'' master
  +
  +
The ''pull'' command combines both ''fetching'' and ''merging''. If there are conflicts (e.g. the original author made changes in the same time span), then it will be necessary to manually fix them.
  +
  +
Alternatively, the original author can '''pick''' the '''changes''' wanting to be incorporated. Using the ''fetch'' option (and ''log'' option with a special {{ic|FETCH_HEAD}} symbol), the contents of the pull request can be viewed before deciding what to do:
  +
  +
$ git fetch ''location'' master
  +
$ git log -p HEAD..FETCH_HEAD
  +
$ git merge ''location'' master
  +
  +
==== リモートの使用 ====
  +
  +
Remotes are tracked repositories, a ''label'' defining a location. They are commonly used for frequently accessed repositories. '''Create''' a remote:
  +
  +
$ git remote add ''label'' ''location''
  +
  +
'''Fetch''' a remote:
  +
  +
$ git fetch ''label''
  +
  +
'''Show differences''' between master and a remote master:
  +
  +
$ git log -p master..''label''/master
  +
  +
'''View''' remotes for the current repository:
  +
  +
$ git remote -v
  +
  +
When defining a remote that is a parent of the fork (the project lead), it is defined as ''upstream''.
  +
  +
==== リポジトリにプッシュ ====
  +
  +
After being given rights from the original authors, '''push''' changes with:
  +
  +
$ git push ''location'' ''branch''
  +
  +
When {{ic|git clone}} is performed, it records the original location and gives it a remote name of {{ic|origin}}. So what '''typically''' is done is this:
  +
  +
$ git push origin master
  +
  +
If the {{ic|--set-upstream}} option is used, the location is recorded so the next time just a {{ic|git push}} is necessary.
  +
  +
==== マージの対処 ====
  +
  +
See [http://git-scm.com/book/en/Git-Branching-Basic-Branching-and-Merging#Basic-Merge-Conflicts Basic Merge Conflicts] in the Git Book for a detailed explanation on how to resolve merge conflicts. Merges are generally reversible. If wanting to back out of a merge one can usually use the {{ic|--abort}} command (e.g. {{ic|git merge --abort}} or {{ic|git pull --abort}}).
  +
  +
==== メーリングリストにパッチを送信 ====
  +
  +
If you want to send patches directly to a mailing list, you have to install the following packages: {{Pkg|perl-authen-sasl}}, {{Pkg|perl-net-smtp-ssl}} and {{Pkg|perl-mime-tools}}.
  +
  +
Make sure you have configured you username and e-mail address, see [[#Basic configuration]].
  +
  +
'''Configure''' your '''e-mail''' settings:
  +
  +
$ git config --global sendemail.smtpserver ''smtp.gmail.com''
  +
$ git config --global sendemail.smtpserverport ''587''
  +
$ git config --global sendemail.smtpencryption ''tls''
  +
$ git config --global sendemail.smtpuser ''foobar@gmail.com''
  +
  +
Now you should be able to '''send''' the '''patch''' to the mailing list (see also [http://www.openembedded.org/wiki/How_to_submit_a_patch_to_OpenEmbedded#Sending_patches OpenEmbedded:How to submit a patch to OpenEmbedded#Sending patches]):
  +
  +
$ git add ''filename''
  +
$ git commit -s
  +
$ git send-email --to=''openembedded-core@lists.openembedded.org'' --confirm=always -M -1
  +
  +
=== History and versioning ===
  +
  +
==== Searching the history ====
  +
  +
{{ic|git log}} will give the history with a commit checksum, author, date, and the short message. For '''history''' with a '''long message''' (where the "''checksum''" can be truncated, as long as it is unique):
  +
  +
$ git show (''checksum'')
  +
  +
'''Search''' for ''pattern'' in tracked files:
  +
  +
$ git grep ''pattern''
  +
  +
'''Search''' in '''{{ic|.c}}''' and '''{{ic|.h}}''' files:
  +
  +
$ git grep ''pattern'' -- '*.[ch]'
  +
  +
==== Versioning for release ====
  +
  +
'''Tag''' commits for versioning:
  +
  +
$ git tag 2.14 ''checksum''
  +
  +
''Tagging'' is generally done for [https://www.drupal.org/node/1066342 releasing/versioning] but it can be any string. Generally annotated tags are used, because they get added to the Git database. '''Tag''' the '''current''' commit with:
  +
  +
$ git tag -a 2.14 -m "Version 2.14"
  +
  +
'''List''' tags:
  +
  +
$ git tag -l
  +
  +
'''Delete''' a tag:
  +
  +
$ git tag -d 2.08
  +
  +
'''Update remote''' tags with a separate:
  +
  +
$ git push --tags
  +
  +
==== Organizing commits ====
  +
  +
Before submitting a pull request it may be desirable to '''consolidate/organize''' the commits. This is done with the {{ic|git rebase}} interactive option:
  +
  +
$ git rebase -i ''checksum''
  +
  +
This will open the editor with a summary of all the commits in the range specified; in this case including the newest ({{ic|HEAD}}) to, but excluding, {{ic|''checksum''}}. Or to use a number notation, use for example {{ic|HEAD~3}}, which will rebase the last three commits:
  +
  +
pick d146cc7 Mountpoint test.
  +
pick 4f47712 Explain -o option in readme.
  +
pick 8a4d479 Rename documentation.
  +
  +
Editing the action in the first column will dictate how the rebase will be done. The options are:
  +
  +
* {{ic|pick}} — Apply this commit as is (the default).
  +
* {{ic|edit}} — Edit files and/or commit message.
  +
* {{ic|reword}} — Edit commit message.
  +
* {{ic|squash}} — Merge/fold into previous commit.
  +
* {{ic|fixup}} — Merge/fold into previous commit discarding its message.
  +
  +
The commits can be re-ordered or erased from the history (but be very careful with these). After editing the file, Git will perform the specified actions; if prompted to resolve merge problems, fix them and continue with {{ic|git rebase --continue}} or back out with the {{ic|git rebase --abort}} command.
  +
  +
{{Note|Squashing commits is only used for local commits, it will cause troubles on a repository that is shared by other people.}}
  +
  +
== 高度な設定 ==
  +
  +
Git reads its configuration from a few INI-type configuration files:
  +
  +
* Each repository contains a {{ic|.git/config}} file for specific configuration.
  +
* Each user has a {{ic|$HOME/.gitconfig}} file for fallback values.
  +
* {{ic|/etc/gitconfig}} is used for system-wide defaults.
  +
  +
These files can be edited directly, but the usual method is to use {{ic|git config}}, as shown in the examples below.
  +
  +
List the currently set variables:
  +
  +
$ git config {--local,--global,--system} --list
  +
  +
Set the default editor from [[vim]] to [[nano]]:
  +
  +
$ git config --global core.editor "nano -w"
  +
  +
Set the default push action:
  +
  +
$ git config --global push.default simple
  +
  +
Set a different tool for {{ic|git difftool}} (''meld'' by default):
  +
  +
$ git config --global diff.tool vimdiff
  +
  +
See [https://www.kernel.org/pub/software/scm/git/docs/git-config.html git-config(1)] and [http://git-scm.com/book/en/v2/Customizing-Git-Git-Configuration Git Configuration] for more information.
  +
  +
=== SSH の高速化 ===
  +
  +
Often if you find yourself pushing constantly to a few common servers, you may wish to remove the hassle of setting your username for each repository.
  +
  +
If you do not already have the keys created, make them now.
  +
  +
$ ssh-keygen -N ’’ -b 4096 -t rsa -f ~/.ssh/aur -C "''user@domain.com''"
  +
$ ssh-keygen -N ’’ -b 4096 -t rsa -f ~/.ssh/github -C "''user@domain.com''"
  +
  +
Add the resulting public keys to your accounts.
  +
  +
Additionally, reusing the same SSH connection will drastically improve the time {{ic|git push}} takes.
  +
  +
$ mkdir -p ~/.ssh/sockets/
  +
  +
You may wish to adjust the {{ic|ServerAliveInterval}} depending on your connection.
  +
  +
{{hc|~/.ssh/config|
  +
Host *
  +
ControlMaster auto
  +
ControlPath ~/.ssh/sockets/%r@%h-%p
  +
ControlPersist 8760h
  +
'''ServerAliveInterval 5'''
  +
ServerAliveCountMax 1
  +
TCPKeepAlive yes
  +
  +
Host aur-dev.archlinux.org
  +
IdentityFile ~/.ssh/aur
  +
User aur
  +
Port 2222
  +
  +
Host github.com
  +
IdentityFile ~/.ssh/github
  +
User [username here]
  +
}}
  +
  +
=== Protocol Defaults ===
  +
  +
If you are running a multiplexed SSH connection as shown above, Git over SSH might be faster than HTTPS. Also, you will not have to enter your password on every push until your multiplexed connection goes down (and only if there is a passphrase on it). For example, the following config will set Git over SSH for any repository hosted on GitHub.
  +
  +
{{hc|~/.gitconfig|
  +
[url "ssh://git@github.com/"]
  +
insteadOf = https://github.com/
  +
insteadOf = http://github.com/
  +
insteadOf = git://github.com/
  +
}}
  +
  +
Optionally, the Git protocol could be used for pulling instead.
  +
  +
{{Warning|There is absolutely no encryption or verification with the server using the Git protocol by itself. Please be careful with software after obtaining through this method.}}
  +
  +
{{hc|~/.gitconfig|
  +
[url "ssh://git@github.com/"]
  +
pushInsteadOf = https://github.com/
  +
[url "git://github.com/"]
  +
insteadOf = https://github.com/
  +
insteadOf = http://github.com/
  +
}}
  +
  +
{{Note|Some corporate firewalls block port 9418/TCP, which the Git protocol uses. In those situations, Git over SSH or HTTPS will likely be the best option.}}
  +
  +
=== Bash 補完 ===
  +
  +
In order to enable Bash completion, source {{ic|/usr/share/git/completion/git-completion.bash}} in a [[Bash#Configuration_files|Bash startup file]]. Alternatively, install {{pkg|bash-completion}}.
  +
  +
=== Git プロンプト ===
  +
  +
The Git package comes with a prompt script. To enable it, source the {{ic|/usr/share/git/completion/git-prompt.sh}} script in a [[Autostarting#Shells|shell startup file]], then set a custom prompt with the {{ic|%s}} parameter:
  +
  +
* For [[Bash]]: {{ic|1=PS1='[\u@\h \W$(__git_ps1 " (%s)")]\$ '}}
  +
* For [[zsh]]: {{ic|1=PS1='[%n@%m %c$(__git_ps1 " (%s)")]\$ '}}
  +
  +
When changing to a directory of a Git repository, the prompt will change to show the branch name. Extra details can be set to be shown by the prompt:
  +
  +
{| class="wikitable"
  +
|+
  +
! Shell variable !! Information
  +
|-
  +
| GIT_PS1_SHOWDIRTYSTATE || '''+''' for staged, '''*''' if unstaged.
  +
|-
  +
| GIT_PS1_SHOWSTASHSTATE || '''$''' if something is stashed.
  +
|-
  +
| GIT_PS1_SHOWUNTRACKEDFILES || '''%''' if there are untracked files.
  +
|-
  +
| GIT_PS1_SHOWUPSTREAM || '''<,>,<>''' behind, ahead, or diverged from upstream.
  +
|}
  +
  +
{{ic|GIT_PS1_SHOWUPSTREAM}} will need to be set to {{ic|auto}} for changes to take effect.
  +
  +
{{Note|If you experience that {{ic|$(__git_ps1)}} returns {{ic|((unknown))}}, then there is a {{ic|.git}} folder in your current directory which does not contain any repository, and therefore Git does not recognize it. This can, for example, happen if you mistake Git's configuration file to be {{ic|~/.git/config}} instead of {{ic|~/.gitconfig}}.}}
  +
  +
== 高度な使い方 ==
  +
  +
To get an idea of the amount of work done:
  +
  +
$ git diff --stat
  +
  +
{{ic|git log}} with forking representation:
  +
  +
$ git log --graph --oneline --decorate
  +
  +
{{ic|git log}} graph alias (i.e. {{ic|git graph}} will show a decorated version):
  +
  +
$ git config --global alias.graph 'log --graph --oneline --decorate'
  +
  +
Reset to previous commit (very dangerous, erases everything to specified commit):
  +
  +
$ git reset --hard HEAD^
  +
  +
If a repository address gets changed, its remote location will need to be updated:
  +
  +
$ git remote set-url origin git@''address'':''user''/''repo''.git
  +
  +
Signed-off-by line append (a name-email signature is added to the commit which is required by some projects):
  +
  +
$ git commit -s
  +
  +
Signed-off-by automatically append to patches (when using {{ic|git format-patch ''commit''}}):
  +
  +
$ git config --local format.signoff true
  +
  +
Commit specific parts of files that have changed. This is useful if there are a large number of changes made that would be best split into several commits:
  +
  +
$ git add -p
  +
  +
=== マスター以外のブランチで作業 ===
  +
  +
Occasionally a maintainer will ask that work be done on a branch. These branches are often called {{ic|devel}} or {{ic|testing}}. Begin by cloning the repository.
  +
  +
To enter another branch beside master ({{ic|git clone}} only shows master branch but others still exist, {{ic|git branch -a}} to show):
  +
  +
$ git checkout -b ''branch'' origin/''branch''
  +
  +
Now edit normally; however to keep the repository tree in sync be sure to use both:
  +
  +
$ git pull --all
  +
$ git push --all
  +
  +
== Git サーバー ==
  +
  +
How to set up connecting to repositories using varying protocols.
  +
  +
=== SSH ===
  +
  +
To use the SSH protocol, first set up a public SSH key; for that follow the guide at [[SSH keys]]. To set up a SSH server, follow the [[SSH]] guide.
  +
  +
With SSH working and a key generated, paste the contents of {{ic|~/.ssh/id_rsa.pub}} to {{ic|~/.ssh/authorized_keys}} (be sure it is all on one line). Now the Git repository can be accessed with SSH by doing:
  +
  +
$ git clone ''user''@''foobar.com'':''my_repository''.git
  +
  +
You should now get an SSH yes/no question, if you have the SSH client setting {{ic|StrictHostKeyChecking}} set to {{ic|ask}} (the default). Type {{ic|yes}} followed by {{ic|Enter}}. Then you should have your repository checked out. Because this is with SSH, you also have commit rights now.
  +
  +
To modify an existing repository to use SSH, the remote location will need to be redefined:
  +
  +
$ git remote set-url origin git@localhost:''my_repository''.git
  +
  +
Connecting on a port other than 22 can be configured on a per-host basis in {{ic|/etc/ssh/ssh_config}} or {{ic|~/.ssh/config}}. To set up ports for a repository, if the repository is in {{ic|~/}} and using 443 for the port:
  +
  +
{{hc|~/.git/config|2=
  +
[remote "origin"]
  +
url = ssh://''user''@''foobar''.com:443/~''my_repository''/repo.git
  +
}}
  +
  +
=== Smart HTTP ===
  +
  +
Git is able to use the HTTP(S) protocol as efficiently as the SSH or Git protocols, by utilizing the git-http-backend. Furthermore it is not only possible to clone or pull from repositories, but also to push into repositories over HTTP(S).
  +
  +
The setup for this is rather simple as all you need to have installed is the Apache web server ({{pkg|apache}}, with {{ic|mod_cgi}}, {{ic|mod_alias}}, and {{ic|mod_env}} enabled) and of course, {{pkg|git}}.
  +
  +
Once you have your basic setup running, add the following to your Apache configuration file, which is usually located at:
  +
  +
{{hc|/etc/httpd/conf/httpd.conf|
  +
<Directory "/usr/lib/git-core*">
  +
Require all granted
  +
</Directory>
  +
  +
SetEnv GIT_PROJECT_ROOT /srv/git
  +
SetEnv GIT_HTTP_EXPORT_ALL
  +
ScriptAlias /git/ /usr/lib/git-core/git-http-backend/
  +
}}
  +
  +
This assumes your Git repositories are located at {{ic|/srv/git}} and that you want to access them via something like: {{ic|<nowiki>http(s)://your_address.tld/git/your_repo.git</nowiki>}}.
  +
  +
{{Note|Make sure that Apache can read and write to your repositories.}}
  +
  +
For more detailed documentation, visit the following links:
  +
* http://progit.org/2010/03/04/smart-http.html
  +
* https://www.kernel.org/pub/software/scm/git/docs/v1.7.10.1/git-http-backend.html
  +
  +
=== Git ===
  +
  +
{{Note|The Git protocol only allows read access.}}
  +
  +
[[start|Start and enable]] {{ic|git-daemon.socket}}.
  +
  +
The daemon is started with the following options:
  +
  +
ExecStart=-/usr/lib/git-core/git-daemon --inetd --export-all --base-path=/srv/git
  +
  +
Repositories placed in {{ic|/srv/git/}} will be recognized by the daemon. Clients can connect with something similar to:
  +
  +
$ git clone git://''location''/''repository''.git
  +
  +
=== アクセス権限の設定 ===
  +
  +
To restrict read and/or write access, use standard Unix permissions. Refer to http://sitaramc.github.com/gitolite/doc/overkill.html{{Dead link|2013|11|06}} ([https://web.archive.org/web/20111004134500/http://sitaramc.github.com/gitolite/doc/overkill.html archive.org mirror]) for more information.
  +
  +
For fine-grained access management, refer to [[gitolite]] and [[gitosis]].
  +
  +
== 参照 ==
  +
  +
* [http://git-scm.com/book Pro Git book]
  +
* [http://gitref.org/ Git Reference]
  +
* https://www.kernel.org/pub/software/scm/git/docs/
  +
* [https://gun.io/blog/how-to-github-fork-branch-and-pull-request Git overall]
  +
* [http://nathanhoad.net/git-workflow-forks-remotes-and-pull-requests Git overall2]
  +
* https://wiki.videolan.org/Git
  +
* [https://gist.github.com/grawity/4392747 A comparison of protocols offered by GitHub]

2015年6月18日 (木) 21:09時点における版

関連記事

Git は Linux カーネルの創設者である Linus Torvalds によって設計・開発されたバージョン管理システム (VCS) です。現在 Git は Linux カーネルのソースの管理だけでなく、様々な他のプロジェクトにも使われており、Arch Linux プロジェクトもそれに含まれます。

インストール

git パッケージをインストールしてください。

Git の補助ツールを使いたい場合は、必要に応じて任意の依存パッケージもインストールしてください。GUI ツール (例: gitkgit gui) は tk パッケージを必要とし、インストールしていない場合エラーで起動できません:

/usr/bin/gitk: line 3: exec: wish: not found.

また、GUI ツールは gsfonts を必要とし、インストールしていない場合セグメンテーション違反でクラッシュします。

Git SVN ブリッジ (git svn) を使いたい場合は perl-term-readkey も必要です。インストールしていない場合、次のエラーが表示されます:

Can't locate Term/ReadKey.pm in @INC (you may need to install the Term::ReadKey module)

基本設定

Git を使うには少なくとも名前とメールアドレスを設定する必要があります:

$ git config --global user.name  "John Doe"
$ git config --global user.email "johndoe@foobar.com"

他の設定については #高度な設定 を見て下さい。

基本的な使い方

このチュートリアルでは Git によるプロジェクトの基本的な分散バージョン管理について説明します。典型的な Git のワークフローは以下の通りです:

  1. 新しいプロジェクトを作成、またはリモートのプロジェクトを複製する。
  2. ブランチを作成して変更を加え、変更をコミットする。
  3. コミットを統合して上手くまとめて分かりやすくする。
  4. メインのブランチにコミットをマージする。
  5. (任意) 変更をリモートサーバーにプッシュする。

ローカルリポジトリ

準備

Initialize a new repository:

$ git init

To record the changes to the repository, they must first be added to the index, or staging area, with an operation often also referred to as staging. To add files:

$ git add file1 file2

Add all files:

$ git add .
ヒント: To ignore some files from, e.g. git add ., create a .gitignore file (or files):
.gitignore
# File I'll likely delete
test-script

# Ignore all .html files, except 'important.html'
*.html
!important.html

# Ignore all files recursively in 'DoNotInclude'
DoNotInclude/**

See gitignore(5) for details.

Remove a file from staging (--cached preserves the actual file(s)):

$ git rm (--cached) file

Remove all files:

$ git reset HEAD -- .

Or:

$ git rm --cached -r .

Rename a file:

$ git mv file1 file2

List files:

$ git ls-files

変更をコミット

Once the content to be recorded is staged, commit them with:

$ git commit -m "First commit."

The -m, --message option is for a short message: if omitted, the preset editor will be spawned to allow entering a longer message.

ヒント:
  • Always commit small changes frequently and with meaningful messages.
  • To add all the modified files to the index, and commit them in a single command (-a stands for --all):
$ git commit -am "First commit."

Go back and edit the commit message:

$ git commit --amend -m "Message."

Many of the commands in this article take commits as arguments. A commit can be identified by any of the following:

  • Its 40-digit SHA-1 hash (the first 7 digits are usually sufficient to identify it uniquely)
  • Any commit label such as a branch or tag name
  • The label HEAD always refers to the currently checked-out commit (usually the head of the branch, unless you used git checkout to jump back in history to an old commit)
  • Any of the above plus ~ to refer to previous commits. For example, HEAD~ refers to one commit before HEAD and HEAD~5 refers to five commits before HEAD.

変更を閲覧

Show differences between commits:

$ git diff

Get a general overview of the changes:

$ git status

View history of changes (where "-N" is the number of latest commits):

$ git log (-N)

ブランチの作成

Fixes and new features are usually tested in branches. When changes are satisfactory they can merged back into the default (master) branch. Create a branch, whose name accurately reflects its purpose:

$ git branch help-section-addition

List branches:

$ git branch

Switch branches:

$ git checkout branch

Create and switch:

$ git checkout -b branch

Merge a branch back to the master branch:

$ git checkout master
$ git merge branch

The changes will be merged if they do not conflict. If they do, the conflicts will be recorded. What is causing the conflicts can been seen with git diff, then conflict resolution will need to be done manually.

When done with a branch, delete it with:

$ git branch -d branch

共同作業

Adopting a good etiquette

  • When considering contributing to an existing project, read and understand its license, as it may excessively limit your ability to change the code. Some licenses can generate disputes over the ownership of the code.
  • Think about the project's community and how well you can fit into it. To get a feeling of the direction of the project, read any documentation and even the log of the repository.
  • When requesting to pull a commit, or submit a patch, keep it small and well documented; this will help the maintainers understand your changes and decide whether to merge them or ask you to make some amendments.
  • If a contribution is rejected, do not get discouraged, it is their project after all. If it is important, discuss the reasoning for the contribution as clearly and as patiently as possible: with such an approach a resolution may eventually be possible.

リポジトリを複製

To begin contributing to a project, clone its repository:

$ git clone location folder

location can be either a path or network address. Also, when cloning is done, the location is recorded so just a git pull will be needed later.

プルリクエスト

After making and committing some changes, the contributor can ask the original author to merge them. This is called a pull request. To pull:

$ git pull location master

The pull command combines both fetching and merging. If there are conflicts (e.g. the original author made changes in the same time span), then it will be necessary to manually fix them.

Alternatively, the original author can pick the changes wanting to be incorporated. Using the fetch option (and log option with a special FETCH_HEAD symbol), the contents of the pull request can be viewed before deciding what to do:

$ git fetch location master
$ git log -p HEAD..FETCH_HEAD
$ git merge location master

リモートの使用

Remotes are tracked repositories, a label defining a location. They are commonly used for frequently accessed repositories. Create a remote:

$ git remote add label location

Fetch a remote:

$ git fetch label

Show differences between master and a remote master:

$ git log -p master..label/master

View remotes for the current repository:

$ git remote -v

When defining a remote that is a parent of the fork (the project lead), it is defined as upstream.

リポジトリにプッシュ

After being given rights from the original authors, push changes with:

$ git push location branch

When git clone is performed, it records the original location and gives it a remote name of origin. So what typically is done is this:

$ git push origin master

If the --set-upstream option is used, the location is recorded so the next time just a git push is necessary.

マージの対処

See Basic Merge Conflicts in the Git Book for a detailed explanation on how to resolve merge conflicts. Merges are generally reversible. If wanting to back out of a merge one can usually use the --abort command (e.g. git merge --abort or git pull --abort).

メーリングリストにパッチを送信

If you want to send patches directly to a mailing list, you have to install the following packages: perl-authen-sasl, perl-net-smtp-ssl and perl-mime-tools.

Make sure you have configured you username and e-mail address, see #Basic configuration.

Configure your e-mail settings:

$ git config --global sendemail.smtpserver smtp.gmail.com
$ git config --global sendemail.smtpserverport 587
$ git config --global sendemail.smtpencryption tls
$ git config --global sendemail.smtpuser foobar@gmail.com

Now you should be able to send the patch to the mailing list (see also OpenEmbedded:How to submit a patch to OpenEmbedded#Sending patches):

$ git add filename
$ git commit -s
$ git send-email --to=openembedded-core@lists.openembedded.org --confirm=always -M -1

History and versioning

Searching the history

git log will give the history with a commit checksum, author, date, and the short message. For history with a long message (where the "checksum" can be truncated, as long as it is unique):

$ git show (checksum)

Search for pattern in tracked files:

$ git grep pattern

Search in .c and .h files:

$ git grep pattern -- '*.[ch]'

Versioning for release

Tag commits for versioning:

$ git tag 2.14 checksum

Tagging is generally done for releasing/versioning but it can be any string. Generally annotated tags are used, because they get added to the Git database. Tag the current commit with:

$ git tag -a 2.14 -m "Version 2.14"

List tags:

$ git tag -l

Delete a tag:

$ git tag -d 2.08

Update remote tags with a separate:

$ git push --tags

Organizing commits

Before submitting a pull request it may be desirable to consolidate/organize the commits. This is done with the git rebase interactive option:

$ git rebase -i checksum

This will open the editor with a summary of all the commits in the range specified; in this case including the newest (HEAD) to, but excluding, checksum. Or to use a number notation, use for example HEAD~3, which will rebase the last three commits:

pick d146cc7 Mountpoint test.
pick 4f47712 Explain -o option in readme.
pick 8a4d479 Rename documentation.

Editing the action in the first column will dictate how the rebase will be done. The options are:

  • pick — Apply this commit as is (the default).
  • edit — Edit files and/or commit message.
  • reword — Edit commit message.
  • squash — Merge/fold into previous commit.
  • fixup — Merge/fold into previous commit discarding its message.

The commits can be re-ordered or erased from the history (but be very careful with these). After editing the file, Git will perform the specified actions; if prompted to resolve merge problems, fix them and continue with git rebase --continue or back out with the git rebase --abort command.

ノート: Squashing commits is only used for local commits, it will cause troubles on a repository that is shared by other people.

高度な設定

Git reads its configuration from a few INI-type configuration files:

  • Each repository contains a .git/config file for specific configuration.
  • Each user has a $HOME/.gitconfig file for fallback values.
  • /etc/gitconfig is used for system-wide defaults.

These files can be edited directly, but the usual method is to use git config, as shown in the examples below.

List the currently set variables:

$ git config {--local,--global,--system} --list

Set the default editor from vim to nano:

$ git config --global core.editor "nano -w"

Set the default push action:

$ git config --global push.default simple

Set a different tool for git difftool (meld by default):

$ git config --global diff.tool vimdiff

See git-config(1) and Git Configuration for more information.

SSH の高速化

Often if you find yourself pushing constantly to a few common servers, you may wish to remove the hassle of setting your username for each repository.

If you do not already have the keys created, make them now.

$ ssh-keygen -N ’’ -b 4096 -t rsa -f ~/.ssh/aur -C "user@domain.com"
$ ssh-keygen -N ’’ -b 4096 -t rsa -f ~/.ssh/github -C "user@domain.com"

Add the resulting public keys to your accounts.

Additionally, reusing the same SSH connection will drastically improve the time git push takes.

$ mkdir -p ~/.ssh/sockets/

You may wish to adjust the ServerAliveInterval depending on your connection.

~/.ssh/config
Host *
ControlMaster auto
ControlPath ~/.ssh/sockets/%r@%h-%p
ControlPersist 8760h
ServerAliveInterval 5
ServerAliveCountMax 1
TCPKeepAlive yes

Host aur-dev.archlinux.org
IdentityFile ~/.ssh/aur
User aur
Port 2222

Host github.com
IdentityFile ~/.ssh/github
User [username here]

Protocol Defaults

If you are running a multiplexed SSH connection as shown above, Git over SSH might be faster than HTTPS. Also, you will not have to enter your password on every push until your multiplexed connection goes down (and only if there is a passphrase on it). For example, the following config will set Git over SSH for any repository hosted on GitHub.

~/.gitconfig
[url "ssh://git@github.com/"]
        insteadOf = https://github.com/
        insteadOf = http://github.com/
        insteadOf = git://github.com/

Optionally, the Git protocol could be used for pulling instead.

警告: There is absolutely no encryption or verification with the server using the Git protocol by itself. Please be careful with software after obtaining through this method.
~/.gitconfig
[url "ssh://git@github.com/"]
        pushInsteadOf = https://github.com/
[url "git://github.com/"]
        insteadOf = https://github.com/
        insteadOf = http://github.com/
ノート: Some corporate firewalls block port 9418/TCP, which the Git protocol uses. In those situations, Git over SSH or HTTPS will likely be the best option.

Bash 補完

In order to enable Bash completion, source /usr/share/git/completion/git-completion.bash in a Bash startup file. Alternatively, install bash-completion.

Git プロンプト

The Git package comes with a prompt script. To enable it, source the /usr/share/git/completion/git-prompt.sh script in a shell startup file, then set a custom prompt with the %s parameter:

  • For Bash: PS1='[\u@\h \W$(__git_ps1 " (%s)")]\$ '
  • For zsh: PS1='[%n@%m %c$(__git_ps1 " (%s)")]\$ '

When changing to a directory of a Git repository, the prompt will change to show the branch name. Extra details can be set to be shown by the prompt:

Shell variable Information
GIT_PS1_SHOWDIRTYSTATE + for staged, * if unstaged.
GIT_PS1_SHOWSTASHSTATE $ if something is stashed.
GIT_PS1_SHOWUNTRACKEDFILES % if there are untracked files.
GIT_PS1_SHOWUPSTREAM <,>,<> behind, ahead, or diverged from upstream.

GIT_PS1_SHOWUPSTREAM will need to be set to auto for changes to take effect.

ノート: If you experience that $(__git_ps1) returns ((unknown)), then there is a .git folder in your current directory which does not contain any repository, and therefore Git does not recognize it. This can, for example, happen if you mistake Git's configuration file to be ~/.git/config instead of ~/.gitconfig.

高度な使い方

To get an idea of the amount of work done:

$ git diff --stat

git log with forking representation:

$ git log --graph --oneline --decorate

git log graph alias (i.e. git graph will show a decorated version):

$ git config --global alias.graph 'log --graph --oneline --decorate'

Reset to previous commit (very dangerous, erases everything to specified commit):

$ git reset --hard HEAD^

If a repository address gets changed, its remote location will need to be updated:

$ git remote set-url origin git@address:user/repo.git

Signed-off-by line append (a name-email signature is added to the commit which is required by some projects):

 $ git commit -s

Signed-off-by automatically append to patches (when using git format-patch commit):

$ git config --local format.signoff true

Commit specific parts of files that have changed. This is useful if there are a large number of changes made that would be best split into several commits:

$ git add -p

マスター以外のブランチで作業

Occasionally a maintainer will ask that work be done on a branch. These branches are often called devel or testing. Begin by cloning the repository.

To enter another branch beside master (git clone only shows master branch but others still exist, git branch -a to show):

$ git checkout -b branch origin/branch

Now edit normally; however to keep the repository tree in sync be sure to use both:

$ git pull --all
$ git push --all

Git サーバー

How to set up connecting to repositories using varying protocols.

SSH

To use the SSH protocol, first set up a public SSH key; for that follow the guide at SSH keys. To set up a SSH server, follow the SSH guide.

With SSH working and a key generated, paste the contents of ~/.ssh/id_rsa.pub to ~/.ssh/authorized_keys (be sure it is all on one line). Now the Git repository can be accessed with SSH by doing:

$ git clone user@foobar.com:my_repository.git

You should now get an SSH yes/no question, if you have the SSH client setting StrictHostKeyChecking set to ask (the default). Type yes followed by Enter. Then you should have your repository checked out. Because this is with SSH, you also have commit rights now.

To modify an existing repository to use SSH, the remote location will need to be redefined:

$ git remote set-url origin git@localhost:my_repository.git

Connecting on a port other than 22 can be configured on a per-host basis in /etc/ssh/ssh_config or ~/.ssh/config. To set up ports for a repository, if the repository is in ~/ and using 443 for the port:

~/.git/config
[remote "origin"]
    url = ssh://user@foobar.com:443/~my_repository/repo.git

Smart HTTP

Git is able to use the HTTP(S) protocol as efficiently as the SSH or Git protocols, by utilizing the git-http-backend. Furthermore it is not only possible to clone or pull from repositories, but also to push into repositories over HTTP(S).

The setup for this is rather simple as all you need to have installed is the Apache web server (apache, with mod_cgi, mod_alias, and mod_env enabled) and of course, git.

Once you have your basic setup running, add the following to your Apache configuration file, which is usually located at:

/etc/httpd/conf/httpd.conf
<Directory "/usr/lib/git-core*">
    Require all granted
</Directory>
 
SetEnv GIT_PROJECT_ROOT /srv/git
SetEnv GIT_HTTP_EXPORT_ALL
ScriptAlias /git/ /usr/lib/git-core/git-http-backend/

This assumes your Git repositories are located at /srv/git and that you want to access them via something like: http(s)://your_address.tld/git/your_repo.git.

ノート: Make sure that Apache can read and write to your repositories.

For more detailed documentation, visit the following links:

Git

ノート: The Git protocol only allows read access.

Start and enable git-daemon.socket.

The daemon is started with the following options:

ExecStart=-/usr/lib/git-core/git-daemon --inetd --export-all --base-path=/srv/git

Repositories placed in /srv/git/ will be recognized by the daemon. Clients can connect with something similar to:

$ git clone git://location/repository.git

アクセス権限の設定

To restrict read and/or write access, use standard Unix permissions. Refer to http://sitaramc.github.com/gitolite/doc/overkill.html[リンク切れ 2013-11-06] (archive.org mirror) for more information.

For fine-grained access management, refer to gitolite and gitosis.

参照